参考链接
- 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文件头的定义比对一下上面的代码