1. 程式人生 > >ffmpeg實戰教程(四)格式轉換如MP4轉MKV等

ffmpeg實戰教程(四)格式轉換如MP4轉MKV等

知識延伸:

I,P,B幀和PTS,DTS的關係

基本概念:

I frame :幀內編碼幀 又稱intra picture,I 幀通常是每個 GOP(MPEG 所使用的一種視訊壓縮技術)的第一個幀,經過適度地壓縮,做為隨機訪問的參考點,可以當成圖象。I幀可以看成是一個影象經過壓縮後的產物。

P frame: 前向預測編碼幀 又稱predictive-frame,通過充分將低於影象序列中前面已編碼幀的時間冗餘資訊來壓縮傳輸資料量的編碼影象,也叫預測幀;

B frame: 雙向預測內插編碼幀 又稱bi-directional interpolated prediction frame,既考慮與源影象序列前面已編碼幀,也顧及源影象序列後面已編碼幀之間的時間冗餘資訊來壓縮傳輸資料量的編碼影象,也叫雙向預測幀;

PTS:Presentation Time Stamp。PTS主要用於度量解碼後的視訊幀什麼時候被顯示出來

DTS:Decode Time Stamp。DTS主要是標識讀入記憶體中的bit流在什麼時候開始送入解碼器中進行解碼。

在沒有B幀存在的情況下DTS的順序和PTS的順序應該是一樣的。

IPB幀的不同:

I frame:自身可以通過視訊解壓演算法解壓成一張單獨的完整的圖片。

P frame:需要參考其前面的一個I frame 或者B frame來生成一張完整的圖片。

B frame:則要參考其前一個I或者P幀及其後面的一個P幀來生成一張完整的圖片。

兩個I frame之間形成一個GOP,在x264中同時可以通過引數來設定bf的大小,即:I 和p或者兩個P之間B的數量。

通過上述基本可以說明如果有B frame 存在的情況下一個GOP的最後一個frame一定是P.

DTS和PTS的不同:

DTS主要用於視訊的解碼,在解碼階段使用.PTS主要用於視訊的同步和輸出.在display的時候使用.在沒有B frame的情況下.DTS和PTS的輸出順序是一樣的.

用ffmpeg實現格式的轉化,比如MP4轉MKV。

本程式並不進行視音訊的編碼和解碼工作。而是直接將視音訊壓縮碼流從一種封裝格式檔案中獲取出來然後打包成另外一種封裝格式的檔案。因為不需要進行視音訊的編碼和解碼,所以不會有視音訊的壓縮損傷。

思路: 
程式包含了對兩個檔案的處理:讀取輸入檔案和寫入輸出檔案。然後使用了一個avcodec_copy_context()拷貝輸入的AVCodecContext到輸出的AVCodecContext。然後再從輸出的AVCodecContext寫進輸出檔案

關鍵函式: 
輸入檔案操作:

avformat_open_input():開啟媒體的的過程開始於avformat_open_input。

av_read_frame():從輸入檔案中讀取一個AVPacket。

輸出檔案操作:

avformat_alloc_output_context2():初始化輸出視訊碼流的AVFormatContext。

avformat_new_stream():建立輸出碼流的AVStream。

avcodec_copy_context():拷貝輸入視訊碼流的AVCodecContex的數值t到輸出視訊的AVCodecContext。

avio_open():開啟輸出檔案。

avformat_write_header():寫檔案頭(對於某些沒有檔案頭的封裝格式,不需要此函式。比如說MPEG2TS)。

av_interleaved_write_frame():將AVPacket(儲存視訊壓縮碼流資料)寫入檔案。

av_write_trailer():寫檔案尾(對於某些沒有檔案頭的封裝格式,不需要此函式。比如說MPEG2TS)。

效果示例,把一個MP4格式轉為AVI。 
這裡寫圖片描述

原始碼:



#include <stdio.h>

#define __STDC_CONSTANT_MACROS

#ifdef _WIN32
//Windows
extern "C"
{
#include "libavformat/avformat.h"
};
#else
//Linux...
#ifdef __cplusplus
extern "C"
{
#endif
#include <libavformat/avformat.h>
#ifdef __cplusplus
};
#endif
#endif


int main(int argc, char* argv[])
{
    AVOutputFormat *ofmt = NULL;
    //Input AVFormatContext and Output AVFormatContext
    AVFormatContext *ifmt_ctx = NULL, *ofmt_ctx = NULL;
    AVPacket pkt;
    const char *in_filename, *out_filename;
    int ret, i;
    int frame_index=0;
    in_filename  = "ws.mp4";//Input file URL
    out_filename = "ws.avi";//Output file URL

    av_register_all();
    //Input
    if ((ret = avformat_open_input(&ifmt_ctx, in_filename, 0, 0)) < 0) {//開啟媒體檔案
        printf( "Could not open input file.");
        goto end;
    }
    if ((ret = avformat_find_stream_info(ifmt_ctx, 0)) < 0) {//獲取視訊資訊
        printf( "Failed to retrieve input stream information");
        goto end;
    }
    av_dump_format(ifmt_ctx, 0, in_filename, 0);
    //初始化輸出視訊碼流的AVFormatContext。
    avformat_alloc_output_context2(&ofmt_ctx, NULL, NULL, out_filename);
    if (!ofmt_ctx) {
        printf( "Could not create output context\n");
        ret = AVERROR_UNKNOWN;
        goto end;
    }
    ofmt = ofmt_ctx->oformat;
    for (i = 0; i < ifmt_ctx->nb_streams; i++) {
        //Create output AVStream according to input AVStream
        AVStream *in_stream = ifmt_ctx->streams[i];
        AVStream *out_stream = avformat_new_stream(ofmt_ctx, in_stream->codec->codec);// 初始化AVStream 
        if (!out_stream) {
            printf( "Failed allocating output stream\n");
            ret = AVERROR_UNKNOWN;
            goto end;
        }
        //關鍵:Copy the settings of AVCodecContext
        if (avcodec_copy_context(out_stream->codec, in_stream->codec) < 0) {
            printf( "Failed to copy context from input to output stream codec context\n");
            goto end;
        }
        out_stream->codec->codec_tag = 0;
        if (ofmt_ctx->oformat->flags & AVFMT_GLOBALHEADER)
            out_stream->codec->flags |= CODEC_FLAG_GLOBAL_HEADER;
    }
    //Output information------------------
    av_dump_format(ofmt_ctx, 0, out_filename, 1);
    //Open output file
    if (!(ofmt->flags & AVFMT_NOFILE)) {
        ret = avio_open(&ofmt_ctx->pb, out_filename, AVIO_FLAG_WRITE);//開啟輸出檔案。
        if (ret < 0) {
            printf( "Could not open output file '%s'", out_filename);
            goto end;
        }
    }
    //Write file header
    if (avformat_write_header(ofmt_ctx, NULL) < 0) {
        printf( "Error occurred when opening output file\n");
        goto end;
    }

    while (1) {
        AVStream *in_stream, *out_stream;
        //Get an AVPacket
        ret = av_read_frame(ifmt_ctx, &pkt);
        if (ret < 0)
            break;
        in_stream  = ifmt_ctx->streams[pkt.stream_index];
        out_stream = ofmt_ctx->streams[pkt.stream_index];

        //Convert PTS/DTS
        pkt.pts = av_rescale_q_rnd(pkt.pts, in_stream->time_base, out_stream->time_base, (AVRounding)(AV_ROUND_NEAR_INF|AV_ROUND_PASS_MINMAX));
        pkt.dts = av_rescale_q_rnd(pkt.dts, in_stream->time_base, out_stream->time_base, (AVRounding)(AV_ROUND_NEAR_INF|AV_ROUND_PASS_MINMAX));
        pkt.duration = av_rescale_q(pkt.duration, in_stream->time_base, out_stream->time_base);
        pkt.pos = -1;
        //Write
        if (av_interleaved_write_frame(ofmt_ctx, &pkt) < 0) {//將AVPacket(儲存視訊壓縮碼流資料)寫入檔案
            printf( "Error muxing packet\n");
            break;
        }
        printf("Write %8d frames to output file\n",frame_index);
        av_free_packet(&pkt);
        frame_index++;
    }
    //Write file trailer
    av_write_trailer(ofmt_ctx);
end:
    avformat_close_input(&ifmt_ctx);
    /* close output */
    if (ofmt_ctx && !(ofmt->flags & AVFMT_NOFILE))
        avio_close(ofmt_ctx->pb);
    avformat_free_context(ofmt_ctx);

    return 0;
}