參考鏈接
- FFmpeg源代碼簡單分析:avformat_alloc_output_context2()_雷霄驊的博客-CSDN博客_avformat_alloc_context
avformat_alloc_output_context2()
- 在基于FFmpeg的視音頻編碼器程序中,該函數通常是第一個調用的函數(除了組件注冊函數av_register_all())
- avformat_alloc_output_context2()函數可以初始化一個用于輸出的AVFormatContext結構體
- 它的聲明位于libavformat\avformat.h,如下所示
/*** Allocate an AVFormatContext for an output format.* avformat_free_context() can be used to free the context and* everything allocated by the framework within it.** @param *ctx is set to the created format context, or to NULL in* case of failure* @param oformat format to use for allocating the context, if NULL* format_name and filename are used instead* @param format_name the name of output format to use for allocating the* context, if NULL filename is used instead* @param filename the name of the filename to use for allocating the* context, may be NULL* @return >= 0 in case of success, a negative AVERROR code in case of* failure*/
int avformat_alloc_output_context2(AVFormatContext **ctx, const AVOutputFormat *oformat,const char *format_name, const char *filename);
- 參數介紹
- ctx:函數調用成功之后創建的AVFormatContext結構體。
- oformat:指定AVFormatContext中的AVOutputFormat,用于確定輸出格式。如果指定為NULL,可以設定后兩個參數(format_name或者filename)由FFmpeg猜測輸出格式。
- PS:使用該參數需要自己手動獲取AVOutputFormat,相對于使用后兩個參數來說要麻煩一些。
- format_name:指定輸出格式的名稱。根據格式名稱,FFmpeg會推測輸出格式。輸出格式可以是“flv”,“mkv”等等。
- filename:指定輸出文件的名稱。根據文件名稱,FFmpeg會推測輸出格式。文件名稱可以是“xx.flv”,“yy.mkv”等等。
- 函數執行成功的話,其返回值大于等于0。?
- avformat_alloc_output_context2()的函數定義。該函數的定義位于libavformat\mux.c中
int avformat_alloc_output_context2(AVFormatContext **avctx, const AVOutputFormat *oformat,const char *format, const char *filename)
{AVFormatContext *s = avformat_alloc_context();int ret = 0;*avctx = NULL;if (!s)goto nomem;if (!oformat) {if (format) {oformat = av_guess_format(format, NULL, NULL);if (!oformat) {av_log(s, AV_LOG_ERROR, "Requested output format '%s' is not a suitable output format\n", format);ret = AVERROR(EINVAL);goto error;}} else {oformat = av_guess_format(NULL, filename, NULL);if (!oformat) {ret = AVERROR(EINVAL);av_log(s, AV_LOG_ERROR, "Unable to find a suitable output format for '%s'\n",filename);goto error;}}}s->oformat = oformat;if (s->oformat->priv_data_size > 0) {s->priv_data = av_mallocz(s->oformat->priv_data_size);if (!s->priv_data)goto nomem;if (s->oformat->priv_class) {*(const AVClass**)s->priv_data= s->oformat->priv_class;av_opt_set_defaults(s->priv_data);}} elses->priv_data = NULL;if (filename) {if (!(s->url = av_strdup(filename)))goto nomem;}*avctx = s;return 0;
nomem:av_log(s, AV_LOG_ERROR, "Out of memory\n");ret = AVERROR(ENOMEM);
error:avformat_free_context(s);return ret;
}
- 從代碼中可以看出,avformat_alloc_output_context2()的流程如要包含以下2步:
- 1) ?調用avformat_alloc_context()初始化一個默認的AVFormatContext。
- 2) 如果指定了輸入的AVOutputFormat,則直接將輸入的AVOutputFormat賦值給AVOutputFormat的oformat。如果沒有指定輸入的AVOutputFormat,就需要根據文件格式名稱或者文件名推測輸出的AVOutputFormat。無論是通過文件格式名稱還是文件名推測輸出格式,都會調用一個函數av_guess_format()。?
函數調用結構圖
- 函數調用結構圖如下所示
?
avformat_alloc_context()
- avformat_alloc_context()的是一個FFmpeg的API,它的定義如下。
AVFormatContext *avformat_alloc_context(void)
{FFFormatContext *const si = av_mallocz(sizeof(*si));AVFormatContext *s;if (!si)return NULL;s = &si->pub;s->av_class = &av_format_context_class;s->io_open = io_open_default;s->io_close = ff_format_io_close_default;s->io_close2= io_close2_default;av_opt_set_defaults(s);si->pkt = av_packet_alloc();si->parse_pkt = av_packet_alloc();if (!si->pkt || !si->parse_pkt) {avformat_free_context(s);return NULL;}si->shortest_end = AV_NOPTS_VALUE;return s;
}
- 從代碼中可以看出,avformat_alloc_context()首先調用av_malloc()為AVFormatContext分配一塊內存。
- 然后調用了一個函數av_opt_set_defaults()用于給AVFormatContext設置默認值。
- av_opt_set_defaults()的定義如下。?
void av_opt_set_defaults(void *s)
{av_opt_set_defaults2(s, 0, 0);
}void av_opt_set_defaults2(void *s, int mask, int flags)
{const AVOption *opt = NULL;while ((opt = av_opt_next(s, opt))) {void *dst = ((uint8_t*)s) + opt->offset;if ((opt->flags & mask) != flags)continue;if (opt->flags & AV_OPT_FLAG_READONLY)continue;switch (opt->type) {case AV_OPT_TYPE_CONST:/* Nothing to be done here */break;case AV_OPT_TYPE_BOOL:case AV_OPT_TYPE_FLAGS:case AV_OPT_TYPE_INT:case AV_OPT_TYPE_INT64:case AV_OPT_TYPE_UINT64:case AV_OPT_TYPE_DURATION:
#if FF_API_OLD_CHANNEL_LAYOUT
FF_DISABLE_DEPRECATION_WARNINGScase AV_OPT_TYPE_CHANNEL_LAYOUT:
FF_ENABLE_DEPRECATION_WARNINGS
#endifcase AV_OPT_TYPE_PIXEL_FMT:case AV_OPT_TYPE_SAMPLE_FMT:write_number(s, opt, dst, 1, 1, opt->default_val.i64);break;case AV_OPT_TYPE_DOUBLE:case AV_OPT_TYPE_FLOAT: {double val;val = opt->default_val.dbl;write_number(s, opt, dst, val, 1, 1);}break;case AV_OPT_TYPE_RATIONAL: {AVRational val;val = av_d2q(opt->default_val.dbl, INT_MAX);write_number(s, opt, dst, 1, val.den, val.num);}break;case AV_OPT_TYPE_COLOR:set_string_color(s, opt, opt->default_val.str, dst);break;case AV_OPT_TYPE_STRING:set_string(s, opt, opt->default_val.str, dst);break;case AV_OPT_TYPE_IMAGE_SIZE:set_string_image_size(s, opt, opt->default_val.str, dst);break;case AV_OPT_TYPE_VIDEO_RATE:set_string_video_rate(s, opt, opt->default_val.str, dst);break;case AV_OPT_TYPE_BINARY:set_string_binary(s, opt, opt->default_val.str, dst);break;case AV_OPT_TYPE_CHLAYOUT:set_string_channel_layout(s, opt, opt->default_val.str, dst);break;case AV_OPT_TYPE_DICT:set_string_dict(s, opt, opt->default_val.str, dst);break;default:av_log(s, AV_LOG_DEBUG, "AVOption type %d of option %s not implemented yet\n",opt->type, opt->name);}}
}
- 從代碼中可以看出,avformat_alloc_context()首先調用memset()將AVFormatContext的內存置零
- 然后指定它的AVClass(指定了AVClass之后,該結構體就支持和AVOption相關的功能)
- 最后調用av_opt_set_defaults()給AVFormatContext的成員變量設置默認值(av_opt_set_defaults()就是和AVOption有關的一個函數,專門用于給指定的結構體設定默認值,此處暫不分析)。?
av_guess_format()
- av_guess_format()是FFmpeg的一個API
- 它的聲明如下
/*** Return the output format in the list of registered output formats* which best matches the provided parameters, or return NULL if* there is no match.** @param short_name if non-NULL checks if short_name matches with the* names of the registered formats* @param filename if non-NULL checks if filename terminates with the* extensions of the registered formats* @param mime_type if non-NULL checks if mime_type matches with the* MIME type of the registered formats*/
const AVOutputFormat *av_guess_format(const char *short_name,const char *filename,const char *mime_type);
- 拿中文簡單解釋一下參數。
- short_name:格式的名稱。
- filename:文件的名稱。
- mime_type:MIME類型。
- 返回最匹配的AVOutputFormat。如果沒有很匹配的AVOutputFormat,則返回NULL。
- av_guess_format()的代碼如下所示。
const AVOutputFormat *av_guess_format(const char *short_name, const char *filename,const char *mime_type)
{const AVOutputFormat *fmt = NULL;const AVOutputFormat *fmt_found = NULL;void *i = 0;int score_max, score;/* specific test for image sequences */
#if CONFIG_IMAGE2_MUXERif (!short_name && filename &&av_filename_number_test(filename) &&ff_guess_image2_codec(filename) != AV_CODEC_ID_NONE) {return av_guess_format("image2", NULL, NULL);}
#endif/* Find the proper file type. */score_max = 0;while ((fmt = av_muxer_iterate(&i))) {score = 0;if (fmt->name && short_name && av_match_name(short_name, fmt->name))score += 100;if (fmt->mime_type && mime_type && !strcmp(fmt->mime_type, mime_type))score += 10;if (filename && fmt->extensions &&av_match_ext(filename, fmt->extensions)) {score += 5;}if (score > score_max) {score_max = score;fmt_found = fmt;}}return fmt_found;
}
- 從代碼中可以看出,av_guess_format()中使用一個整型變量score記錄每種輸出格式的匹配程度。
- 函數中包含了一個while()循環,該循環利用函數av_muxer_iterate()遍歷FFmpeg中所有的AVOutputFormat,并逐一計算每個輸出格式的score。
- 具體的計算過程分成如下幾步:
- 1) ?如果封裝格式名稱匹配,score增加100。匹配中使用了函數av_match_name()。
- 2) ?如果mime類型匹配,score增加10。匹配直接使用字符串比較函數strcmp()。
- 3) ?如果文件名稱的后綴匹配,score增加5。匹配中使用了函數av_match_ext()。
- while()循環結束后,得到得分最高的格式,就是最匹配的格式。
- 下面看一下一個AVOutputFormat的實例,就可以理解“封裝格式名稱”,“mine類型”,“文件名稱后綴”這些概念了。
- 下面是flv格式的視音頻復用器(Muxer)對應的AVOutputFormat格式的變量ff_flv_muxer。
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,
};
av_muxer_iterate
- 參數不為NULL的時候用于獲得下一個AVOutputFormat
const AVOutputFormat *av_muxer_iterate(void **opaque)
{static const uintptr_t size = sizeof(muxer_list)/sizeof(muxer_list[0]) - 1;uintptr_t i = (uintptr_t)*opaque;const AVOutputFormat *f = NULL;uintptr_t tmp;if (i < size) {f = muxer_list[i];} else if (tmp = atomic_load_explicit(&outdev_list_intptr, memory_order_relaxed)) {const AVOutputFormat *const *outdev_list = (const AVOutputFormat *const *)tmp;f = outdev_list[i - size];}if (f)*opaque = (void*)(i + 1);return f;
}
av_match_name()
- av_match_name()是一個API函數,定義如下所示。
- av_match_name()用于比較兩個格式的名稱。簡單地說就是比較字符串。
- 注意該函數的字符串是不區分大小寫的:字符都轉換為小寫進行比較。
int av_match_name(const char *name, const char *names)
{const char *p;int len, namelen;if (!name || !names)return 0;namelen = strlen(name);while (*names) {int negate = '-' == *names;p = strchr(names, ',');if (!p)p = names + strlen(names);names += negate;len = FFMAX(p - names, namelen);if (!av_strncasecmp(name, names, len) || !strncmp("ALL", names, FFMAX(3, p - names)))return !negate;names = p + (*p == ',');}return 0;
}
- 上述函數還有一點需要注意,其中使用了一個while()循環,用于搜索“,”。
- 這是因為FFmpeg中有些格式是對應多種格式名稱的,例如MKV格式的解復用器(Demuxer)的定義如下。
const AVInputFormat ff_matroska_demuxer = {.name = "matroska,webm",.long_name = NULL_IF_CONFIG_SMALL("Matroska / WebM"),.extensions = "mkv,mk3d,mka,mks,webm",.priv_data_size = sizeof(MatroskaDemuxContext),.flags_internal = FF_FMT_INIT_CLEANUP,.read_probe = matroska_probe,.read_header = matroska_read_header,.read_packet = matroska_read_packet,.read_close = matroska_read_close,.read_seek = matroska_read_seek,.mime_type = "audio/webm,audio/x-matroska,video/webm,video/x-matroska"
};
- 從代碼可以看出,ff_matroska_demuxer中的name字段對應“matroska,webm”。
- av_match_name()函數對于這樣的字符串,會把它按照“,”截斷成一個個封裝格式名稱,然后一一進行比較。
av_match_ext()
- av_match_ext()是一個API函數,聲明如下所示。
/*** Return a positive value if the given filename has one of the given* extensions, 0 otherwise.** @param filename file name to check against the given extensions* @param extensions a comma-separated list of filename extensions*/
int av_match_ext(const char *filename, const char *extensions);
- av_match_ext()用于比較文件的后綴。
- 該函數首先通過反向查找的方式找到輸入文件名中的“.”,就可以通過獲取“.”后面的字符串來得到該文件的后綴。
- 然后調用av_match_name(),采用和比較格式名稱的方法比較兩個后綴。?
/*** @file* Format register and lookup*/int av_match_ext(const char *filename, const char *extensions)
{const char *ext;if (!filename)return 0;ext = strrchr(filename, '.');if (ext)return av_match_name(ext + 1, extensions);return 0;
}
- 經過以上幾步之后,av_guess_format()最終可以得到最合適的AVOutputFormat并且返回給avformat_alloc_output_context2()。
- avformat_alloc_output_context2()接下來將獲得的AVOutputFormat賦值給剛剛新建的AVFormatContext,即可完成初始化工作