天天看點

YUV編碼為H264 H264封裝為MP4

轉載: 

作者:DaveBobo 

來源:CSDN 

原文:https://blog.csdn.net/DaveBobo/article/details/79648900 

1 、YUV編碼為H264

YUV編碼為H264有兩種方式: 

(1)基于FFMPEG調用libx264實作YUV420P的像素資料編碼為H.264的壓縮編碼資料; 

(2)直接調用libx264将輸入的YUV資料編碼為H.264碼流檔案; 

1.1 基于FFmpeg YUV編碼為H264 

使用FFmpeg編碼視訊涉及的主要函數: 

av_register_all():注冊FFmpeg所有編解碼器。 

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

avio_open():打開輸出檔案。 

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

avcodec_find_encoder():查找編碼器。 

avcodec_open2():打開編碼器。 

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

avcodec_encode_video2():編碼一幀視訊。即将AVFrame(存儲YUV像素資料)編碼為AVPacket(存儲H.264等格式的碼流資料)。 

av_write_frame():将編碼後的視訊碼流寫入檔案。 

flush_encoder():輸入的像素資料讀取完成後調用此函數。用于輸出編碼器中剩餘的AVPacket。 

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

1.2 直接調用libx264 YUV編碼為H264 

調用libx264進行視訊編碼涉及的主要函數: 

x264_param_default():設定參數集結構體x264_param_t的預設值。 

x264_picture_alloc():為圖像結構體x264_picture_t配置設定記憶體。 

x264_encoder_open():打開編碼器。 

x264_encoder_encode():編碼一幀圖像。 

x264_encoder_close():關閉編碼器。 

x264_picture_clean():釋放x264_picture_alloc()申請的資源。

存儲資料的結構體如下所示。 

x264_picture_t:存儲壓縮編碼前的像素資料。 

x264_nal_t:存儲壓縮編碼後的碼流資料。 

2 、H264封裝為MP4

H264封裝為MP4有兩種方式: 

(1)基于FFmpeg使用mp4封裝格式封裝視訊資料;(這種方式效率較低) 

(2)根據MP4檔案協定直接将H264包封裝成MP4格式,通過Mp4v2可以很友善的将H264編碼成MP4格式檔案 

2.1 基于FFmpeg使用mp4封裝格式封裝視訊資料、

使用FFmpeg編碼視訊涉及的主要函數:

avcodec_register_all();     av_register_all();    注冊

avformat_alloc_output_context2();    初始化

avio_open();    打開檔案

avformat_new_stream();    初始化視訊碼流

為CodecContext 設定參數

 avcodec_find_encoder();    尋找編碼器并打開編碼器

avcode_open2();    

av_frame_alloc();    初始化幀

avformat_write_header();    寫檔案頭

avcodec_encode_video2();    循環編碼

flush_encoder();   flush encoder

av_write_traler();    寫檔案尾

avcodec_close();  av_free()    avio_close()    avformat_free_context()    fclose();     各種釋放記憶體,關閉檔案

簡單記錄一下,主要是友善自己随時檢視。檢視源碼,還需通路原博文。