FFmpeg源代碼簡單分析-編碼-avformat_write_header()

參考鏈接

  • FFmpeg源代碼簡單分析:avformat_write_header()_雷霄驊的博客-CSDN博客_avformat_write_header

avformat_write_header()

  • FFmpeg寫文件用到的3個函數:avformat_write_header(),av_write_frame()以及av_write_trailer()
  • 其中av_write_frame()用于寫視頻數據,avformat_write_header()用于寫視頻文件頭,而av_write_trailer()用于寫視頻文件尾
  • 本文首先分析avformat_write_header()。
  • PS:
  • 需要注意的是,盡管這3個函數功能是配套的,但是它們的前綴卻不一樣,寫文件頭Header的函數前綴是“avformat_”,其他兩個函數前綴是“av_”(不太明白其中的原因)。
  • avformat_write_header()的聲明位于libavformat\avformat.h,如下所示
/*** Allocate the stream private data and write the stream header to* an output media file.** @param s Media file handle, must be allocated with avformat_alloc_context().*          Its oformat field must be set to the desired output format;*          Its pb field must be set to an already opened AVIOContext.* @param options  An AVDictionary filled with AVFormatContext and muxer-private options.*                 On return this parameter will be destroyed and replaced with a dict containing*                 options that were not found. May be NULL.** @return AVSTREAM_INIT_IN_WRITE_HEADER on success if the codec had not already been fully initialized in avformat_init,*         AVSTREAM_INIT_IN_INIT_OUTPUT  on success if the codec had already been fully initialized in avformat_init,*         negative AVERROR on failure.** @see av_opt_find, av_dict_set, avio_open, av_oformat_next, avformat_init_output.*/
av_warn_unused_result
int avformat_write_header(AVFormatContext *s, AVDictionary **options);
  • 簡單解釋一下它的參數的含義:
    • s:用于輸出的AVFormatContext。
    • options:額外的選項,目前沒有深入研究過,一般為NULL。
    • 函數正常執行后返回值等于0。
  • avformat_write_header()的定義位于libavformat\mux.c,如下所示
int avformat_write_header(AVFormatContext *s, AVDictionary **options)
{FFFormatContext *const si = ffformatcontext(s);int already_initialized = si->initialized;int streams_already_initialized = si->streams_initialized;int ret = 0;if (!already_initialized)if ((ret = avformat_init_output(s, options)) < 0)return ret;if (!(s->oformat->flags & AVFMT_NOFILE) && s->pb)avio_write_marker(s->pb, AV_NOPTS_VALUE, AVIO_DATA_MARKER_HEADER);if (s->oformat->write_header) {ret = s->oformat->write_header(s);if (ret >= 0 && s->pb && s->pb->error < 0)ret = s->pb->error;if (ret < 0)goto fail;flush_if_needed(s);}if (!(s->oformat->flags & AVFMT_NOFILE) && s->pb)avio_write_marker(s->pb, AV_NOPTS_VALUE, AVIO_DATA_MARKER_UNKNOWN);if (!si->streams_initialized) {if ((ret = init_pts(s)) < 0)goto fail;}return streams_already_initialized;fail:deinit_muxer(s);return ret;
}
  • 從源代碼可以看出,avformat_write_header()完成了以下工作:
  • (1)調用avformat_init_output()初始化復用器?
  • (2)調用AVOutputFormat的write_header()下面看一下這兩個函數。

函數調用關系圖

  • avformat_write_header()的調用關系如下圖所示。
  • init_muxer函數被avformat_init_output函數替代,avformat_init_output內部包含了init_muxer

avformat_init_output

int avformat_init_output(AVFormatContext *s, AVDictionary **options)
{FFFormatContext *const si = ffformatcontext(s);int ret = 0;if ((ret = init_muxer(s, options)) < 0)return ret;si->initialized = 1;si->streams_initialized = ret;if (s->oformat->init && ret) {if ((ret = init_pts(s)) < 0)return ret;return AVSTREAM_INIT_IN_INIT_OUTPUT;}return AVSTREAM_INIT_IN_WRITE_HEADER;
}

init_muxer()

  • init_muxer()用于初始化復用器,它的定義如下所示。
static int init_muxer(AVFormatContext *s, AVDictionary **options)
{FFFormatContext *const si = ffformatcontext(s);AVDictionary *tmp = NULL;const AVOutputFormat *of = s->oformat;AVDictionaryEntry *e;int ret = 0;if (options)av_dict_copy(&tmp, *options, 0);if ((ret = av_opt_set_dict(s, &tmp)) < 0)goto fail;if (s->priv_data && s->oformat->priv_class && *(const AVClass**)s->priv_data==s->oformat->priv_class &&(ret = av_opt_set_dict2(s->priv_data, &tmp, AV_OPT_SEARCH_CHILDREN)) < 0)goto fail;if (!s->url && !(s->url = av_strdup(""))) {ret = AVERROR(ENOMEM);goto fail;}// some sanity checksif (s->nb_streams == 0 && !(of->flags & AVFMT_NOSTREAMS)) {av_log(s, AV_LOG_ERROR, "No streams to mux were specified\n");ret = AVERROR(EINVAL);goto fail;}for (unsigned i = 0; i < s->nb_streams; i++) {AVStream          *const  st = s->streams[i];FFStream          *const sti = ffstream(st);AVCodecParameters *const par = st->codecpar;const AVCodecDescriptor *desc;if (!st->time_base.num) {/* fall back on the default timebase values */if (par->codec_type == AVMEDIA_TYPE_AUDIO && par->sample_rate)avpriv_set_pts_info(st, 64, 1, par->sample_rate);elseavpriv_set_pts_info(st, 33, 1, 90000);}switch (par->codec_type) {case AVMEDIA_TYPE_AUDIO:if (par->sample_rate <= 0) {av_log(s, AV_LOG_ERROR, "sample rate not set\n");ret = AVERROR(EINVAL);goto fail;}#if FF_API_OLD_CHANNEL_LAYOUT
FF_DISABLE_DEPRECATION_WARNINGS/* if the caller is using the deprecated channel layout API,* convert it to the new style */if (!par->ch_layout.nb_channels &&par->channels) {if (par->channel_layout) {av_channel_layout_from_mask(&par->ch_layout, par->channel_layout);} else {par->ch_layout.order       = AV_CHANNEL_ORDER_UNSPEC;par->ch_layout.nb_channels = par->channels;}}
FF_ENABLE_DEPRECATION_WARNINGS
#endifif (!par->block_align)par->block_align = par->ch_layout.nb_channels *av_get_bits_per_sample(par->codec_id) >> 3;break;case AVMEDIA_TYPE_VIDEO:if ((par->width <= 0 || par->height <= 0) &&!(of->flags & AVFMT_NODIMENSIONS)) {av_log(s, AV_LOG_ERROR, "dimensions not set\n");ret = AVERROR(EINVAL);goto fail;}if (av_cmp_q(st->sample_aspect_ratio, par->sample_aspect_ratio)&& fabs(av_q2d(st->sample_aspect_ratio) - av_q2d(par->sample_aspect_ratio)) > 0.004*av_q2d(st->sample_aspect_ratio)) {if (st->sample_aspect_ratio.num != 0 &&st->sample_aspect_ratio.den != 0 &&par->sample_aspect_ratio.num != 0 &&par->sample_aspect_ratio.den != 0) {av_log(s, AV_LOG_ERROR, "Aspect ratio mismatch between muxer ""(%d/%d) and encoder layer (%d/%d)\n",st->sample_aspect_ratio.num, st->sample_aspect_ratio.den,par->sample_aspect_ratio.num,par->sample_aspect_ratio.den);ret = AVERROR(EINVAL);goto fail;}}break;}desc = avcodec_descriptor_get(par->codec_id);if (desc && desc->props & AV_CODEC_PROP_REORDER)sti->reorder = 1;sti->is_intra_only = ff_is_intra_only(par->codec_id);if (of->codec_tag) {if (   par->codec_tag&& par->codec_id == AV_CODEC_ID_RAWVIDEO&& (   av_codec_get_tag(of->codec_tag, par->codec_id) == 0|| av_codec_get_tag(of->codec_tag, par->codec_id) == MKTAG('r', 'a', 'w', ' '))&& !validate_codec_tag(s, st)) {// the current rawvideo encoding system ends up setting// the wrong codec_tag for avi/mov, we override it herepar->codec_tag = 0;}if (par->codec_tag) {if (!validate_codec_tag(s, st)) {const uint32_t otag = av_codec_get_tag(s->oformat->codec_tag, par->codec_id);av_log(s, AV_LOG_ERROR,"Tag %s incompatible with output codec id '%d' (%s)\n",av_fourcc2str(par->codec_tag), par->codec_id, av_fourcc2str(otag));ret = AVERROR_INVALIDDATA;goto fail;}} elsepar->codec_tag = av_codec_get_tag(of->codec_tag, par->codec_id);}if (par->codec_type != AVMEDIA_TYPE_ATTACHMENT)si->nb_interleaved_streams++;}si->interleave_packet = of->interleave_packet;if (!si->interleave_packet)si->interleave_packet = si->nb_interleaved_streams > 1 ?ff_interleave_packet_per_dts :ff_interleave_packet_passthrough;if (!s->priv_data && of->priv_data_size > 0) {s->priv_data = av_mallocz(of->priv_data_size);if (!s->priv_data) {ret = AVERROR(ENOMEM);goto fail;}if (of->priv_class) {*(const AVClass **)s->priv_data = of->priv_class;av_opt_set_defaults(s->priv_data);if ((ret = av_opt_set_dict2(s->priv_data, &tmp, AV_OPT_SEARCH_CHILDREN)) < 0)goto fail;}}/* set muxer identification string */if (!(s->flags & AVFMT_FLAG_BITEXACT)) {av_dict_set(&s->metadata, "encoder", LIBAVFORMAT_IDENT, 0);} else {av_dict_set(&s->metadata, "encoder", NULL, 0);}for (e = NULL; e = av_dict_get(s->metadata, "encoder-", e, AV_DICT_IGNORE_SUFFIX); ) {av_dict_set(&s->metadata, e->key, NULL, 0);}if (options) {av_dict_free(options);*options = tmp;}if (s->oformat->init) {if ((ret = s->oformat->init(s)) < 0) {if (s->oformat->deinit)s->oformat->deinit(s);return ret;}return ret == 0;}return 0;fail:av_dict_free(&tmp);return ret;
}
  • init_muxer()代碼很長,但是它所做的工作比較簡單,可以概括成兩個字:檢查。
  • 函數的流程可以概括成以下幾步:
    • (1)將傳入的AVDictionary形式的選項設置到AVFormatContext
    • (2)遍歷AVFormatContext中的每個AVStream,并作如下檢查:
      • a)AVStream的time_base是否正確設置。如果發現AVStream的time_base沒有設置,則會調用avpriv_set_pts_info()進行設置。
      • b)對于音頻,檢查采樣率設置是否正確;對于視頻,檢查寬、高、寬高比。
      • c)其他一些檢查,不再詳述。

AVOutputFormat->write_header()

  • avformat_write_header()中最關鍵的地方就是調用了AVOutputFormat的write_header()。
  • write_header()是AVOutputFormat中的一個函數指針,指向寫文件頭的函數。
  • 不同的AVOutputFormat有不同的write_header()的實現方法。
  • 在這里我們舉例子看一下FLV封裝格式對應的AVOutputFormat,它的定義位于libavformat\flvenc.c,如下所示。
const AVOutputFormat ff_flv_muxer = {.name           = "flv",.long_name      = NULL_IF_CONFIG_SMALL("FLV (Flash Video)"),.mime_type      = "video/x-flv",.extensions     = "flv",.priv_data_size = sizeof(FLVContext),.audio_codec    = CONFIG_LIBMP3LAME ? AV_CODEC_ID_MP3 : AV_CODEC_ID_ADPCM_SWF,.video_codec    = AV_CODEC_ID_FLV1,.init           = flv_init,.write_header   = flv_write_header,.write_packet   = flv_write_packet,.write_trailer  = flv_write_trailer,.check_bitstream= flv_check_bitstream,.codec_tag      = (const AVCodecTag* const []) {flv_video_codec_ids, flv_audio_codec_ids, 0},.flags          = AVFMT_GLOBALHEADER | AVFMT_VARIABLE_FPS |AVFMT_TS_NONSTRICT,.priv_class     = &flv_muxer_class,
};
  • 從ff_flv_muxer的定義中可以看出,write_header()指向的函數為flv_write_header()。
  • 我們繼續看一下flv_write_header()函數。
  • flv_write_header()的定義同樣位于libavformat\flvenc.c,如下所示。
static int flv_write_header(AVFormatContext *s)
{int i;AVIOContext *pb = s->pb;FLVContext *flv = s->priv_data;avio_write(pb, "FLV", 3);avio_w8(pb, 1);avio_w8(pb, FLV_HEADER_FLAG_HASAUDIO * !!flv->audio_par +FLV_HEADER_FLAG_HASVIDEO * !!flv->video_par);avio_wb32(pb, 9);avio_wb32(pb, 0);for (i = 0; i < s->nb_streams; i++)if (s->streams[i]->codecpar->codec_tag == 5) {avio_w8(pb, 8);     // message typeavio_wb24(pb, 0);   // include flagsavio_wb24(pb, 0);   // time stampavio_wb32(pb, 0);   // reservedavio_wb32(pb, 11);  // sizeflv->reserved = 5;}if (flv->flags & FLV_NO_METADATA) {pb->seekable = 0;} else {write_metadata(s, 0);}for (i = 0; i < s->nb_streams; i++) {flv_write_codec_header(s, s->streams[i]->codecpar, 0);}flv->datastart_offset = avio_tell(pb);return 0;
}
  • 從源代碼可以看出,flv_write_header()完成了FLV文件頭的寫入工作。
  • 該函數的工作可以大體分為以下兩部分:
  • (1)給FLVContext設置參數
  • (2)寫文件頭,以及相關的Tag寫文件頭的代碼很短,如下所示
    avio_write(pb, "FLV", 3);avio_w8(pb, 1);avio_w8(pb, FLV_HEADER_FLAG_HASAUDIO * !!flv->audio_par +FLV_HEADER_FLAG_HASVIDEO * !!flv->video_par);avio_wb32(pb, 9);avio_wb32(pb, 0);
  • 可以參考下圖中FLV文件頭的定義比對一下上面的代碼

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/445945.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/445945.shtml
英文地址,請注明出處:http://en.pswp.cn/news/445945.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

《深入理解JVM.2nd》筆記(二):Java內存區域與內存溢出異常

文章目錄概述運行時數據區域程序計數器Java虛擬機棧本地方法棧Java堆方法區運行時常量池直接內存HotSpot虛擬機對象探秘對象的創建第一步第二步第三步第四步最后一腳對象的內存布局對象頭Header第一部分第二部分實例數據Instance對齊填充Padding對象的訪問定位句柄直接指針對象…

vue底部選擇器_Vue組件-極簡的地址選擇器

一、前言本文用Vue完成一個極簡的地點選擇器&#xff0c;我們接下來帶大家實現這個。當然其中也有一些值得學習與注意的地方。話不多說&#xff0c;我們先上demo圖。因為每個人的需要不一樣&#xff0c;我這邊就不在實現更多的功能&#xff0c;所以留有更大的空間供大家增刪改。…

FFmpeg源代碼簡單分析-編碼-avcodec_encode_video()已被send_frame 和 receive_packet替代

參考鏈接 FFmpeg源代碼簡單分析&#xff1a;avcodec_encode_video()_雷霄驊的博客-CSDN博客_avcodec_encode_video2 avcodec_encode_video() 該函數用于編碼一幀視頻數據。函數已被棄用參考鏈接&#xff1a;FFmpeg 新舊版本編碼 API 的區別_zouzhiheng的博客-CSDN博客 send_f…

《深入理解JVM.2nd》筆記(三):垃圾收集器與垃圾回收策略

文章目錄概述對象已死嗎引用計數算法可達性分析算法再談引用finalize()&#xff1a;生存還是死亡回收方法區垃圾收集算法標記-清除算法復制算法標記-整理算法分代收集算法HotSpot的算法實現枚舉根結點安全點安全區域垃圾收集器SerialParNewParallel ScavengeSerial OldParallel…

python計算股票趨勢_通過機器學習的線性回歸算法預測股票走勢(用Python實現)...

1 波士頓房價數據分析安裝好Python的Sklearn庫后&#xff0c;在安裝包下的路徑中就能看到描述波士頓房價的csv文件&#xff0c;具體路徑是“python安裝路徑\Lib\site-packages\sklearn\datasets\data”&#xff0c;在這個目錄中還包含了Sklearn庫會用到的其他數據文件&#xff…

FFmpeg源代碼簡單分析-編碼-av_write_frame()

參考鏈接 FFmpeg源代碼簡單分析&#xff1a;av_write_frame()_雷霄驊的博客-CSDN博客_av_write_frame av_write_frame() av_write_frame()用于輸出一幀視音頻數據&#xff0c;它的聲明位于libavformat\avformat.h&#xff0c;如下所示。 /*** Write a packet to an output me…

《深入理解JVM.2nd》筆記(四):虛擬機性能監控與故障處理工具

文章目錄概述JDK的命令行工具jps&#xff1a;虛擬機進程狀況工具jstat&#xff1a;虛擬機統計信息監視工具jinfo&#xff1a;Java配置信息工具jmap&#xff1a;Java內存映像工具jhat&#xff1a;虛擬機堆轉儲快照分析工具jstack&#xff1a;Java堆棧跟蹤工具HSDIS&#xff1a;J…

postgresql 主從配置_Postgresql主從配置

一、簡介PostgreSql在9.0之后引入了主從的流復制機制&#xff0c;所謂流復制&#xff0c;就是從服務器通過tcp流從主服務器中同步相應的數據。這樣當主服務器數據丟失時從服務器中仍有備份。與基于文件日志傳送相比&#xff0c;流復制允許保持從服務器更新。 從服務器連接主服務…

FFmpeg源代碼簡單分析-編碼-av_write_trailer()

參考鏈接&#xff1a; FFmpeg源代碼簡單分析&#xff1a;av_write_trailer()_雷霄驊的博客-CSDN博客_av_malloc av_write_trailer() av_write_trailer()用于輸出文件尾&#xff0c;它的聲明位于libavformat\avformat.h&#xff0c;如下所示 /*** Write the stream trailer to…

科沃斯掃地機器人風扇模塊_掃地機器人不能開機,不能關機,風扇不轉

家庭的重要性自不必再細說&#xff0c;而小編今天要說的則是家庭環境的重要性。一般家庭最少居住三口人&#xff0c;兩個大人加一個孩子&#xff0c;每天回到家&#xff0c;看到家里整潔舒適的環境&#xff0c;心情該是多么地愜意。要是我們每天下班回到家中&#xff0c;看到滿…

MySQL關鍵字EXPLAIN的用法及其案例

文章目錄概述EXPLAIN輸出的列的解釋實例說明select_type的說明UNIONDEPENDENT UNION與DEPENDENT SUBQUERYSUBQUERYDERIVEDtype的說明system&#xff0c;consteq_refrefref_or_nullindex_mergeunique_subqueryindex_subqueryrangeindexALLextra的說明DistinctNot existsRange ch…

FFmpeg源代碼簡單分析-其他-日志輸出系統(av_log()等)

參考鏈接 FFmpeg源代碼簡單分析&#xff1a;日志輸出系統&#xff08;av_log()等&#xff09;_雷霄驊的博客-CSDN博客_ffmpeg源碼分析 日志輸出系統&#xff08;av_log()等&#xff09; 本文分析一下FFmpeg的日志&#xff08;Log&#xff09;輸出系統的源代碼。日志輸出部分的…

FFmpeg源代碼簡單分析-其他-AVClass和AVoption

參考鏈接 FFmpeg源代碼簡單分析&#xff1a;結構體成員管理系統-AVClass_雷霄驊的博客-CSDN博客FFmpeg源代碼簡單分析&#xff1a;結構體成員管理系統-AVOption_雷霄驊的博客-CSDN博客 概述 AVOption用于在FFmpeg中描述結構體中的成員變量。它最主要的作用可以概括為兩個字&a…

oracle手工收集awr報告_oracle手工生成AWR報告方法記錄-阿里云開發者社區

AWR(Automatic Workload Repository)報告是我們進行日常數據庫性能評定、問題SQL發現的重要手段。熟練掌握AWR報告&#xff0c;是做好開發、運維DBA工作的重要基本功。AWR報告的原理是基于Oracle數據庫的定時鏡像功能。默認情況下&#xff0c;Oracle數據庫后臺進程會以一定間隔…

IntelliJ IDEA 默認快捷鍵大全

文章目錄Remember these ShortcutsGeneralDebuggingSearch / ReplaceEditingRefactoringNavigationCompile and RunUsage SearchVCS / Local HistoryLive Templates參考資料Remember these Shortcuts 常用功能快捷鍵備注●Smart code completionCtrl Shift Space-●Search e…

python爬蟲的數據如何解決亂碼_寫爬蟲時如何解決網頁亂碼問題

實戰講解&#xff0c;文章較長&#xff0c;對爬蟲比較熟悉的瀏覽翻看章節 2.3 獲取新聞文本內容。寫爬蟲時經常對網址發起請求&#xff0c;結果返回的html數據除了標簽能看懂&#xff0c;其他的全部是亂碼。大家如果對爬蟲感興趣&#xff0c;請耐心閱讀本文&#xff0c;我們就以…

FFmpeg源代碼簡單分析-其他-libswscale的sws_getContext()

參考鏈接 FFmpeg源代碼簡單分析&#xff1a;libswscale的sws_getContext()_雷霄驊的博客-CSDN博客 libswscale的sws_getContext() FFmpeg中類庫libswsscale用于圖像處理&#xff08;縮放&#xff0c;YUV/RGB格式轉換&#xff09;libswscale是一個主要用于處理圖片像素數據的類…

IntelliJ IDEA 學習筆記

IDEA教學視頻 文章目錄1.IntelliJ IDEA的介紹和優勢IDEA 的主要優勢2.版本介紹與安裝前的準備3.IDEA的卸載4.IDEA的安裝5.安裝目錄和設置目錄結構的說明安裝目錄設置目錄6.啟動IDEA并執行HelloWorld7.Module的使用8.IDEA的常用設置9.快捷鍵的設置10.常用的快捷鍵的使用111.常用…

機器學習頂刊文獻_人工智能頂刊TPAMI2019最新《多模態機器學習綜述》

原標題&#xff1a;人工智能頂刊TPAMI2019最新《多模態機器學習綜述》來源&#xff1a;專知摘要&#xff1a;”當研究問題或數據集包括多個這樣的模態時&#xff0c;其特征在于多模態。【導讀】人工智能領域最頂級國際期刊IEEE Transactions on Pattern Analysis and Machine I…

Windows上同時運行兩個Tomcat

步驟 1.獲得免安裝包 從Tomcat官網下載免安裝包。 2.解壓復制 解壓并創建兩個副本tomcat1和tomcat2&#xff0c;它們的路徑分別為&#xff1a; tomcat1&#xff1a;C:\tomcat\double\apache-tomcat-7.0.90-8081tomcat2&#xff1a;C:\tomcat\double\apache-tomcat-7.0.90-…