先看FFmpeg怎么说。
/**
* 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);
注释说申请流的私有数据然后把流信息写到媒体文件里面。
看源码之后感觉申请数据没发现什么,这个函数最重要的就干了两个事情,第一个是调用avformat_init_output,初始化mutex,实际上大部分都是检查格式,然后写入options。第二个就是调用对应格式的write_header,完成写入packet之前的一些格式上的初始化操作。
下面详细介绍一下代码。
里面的重点就是avformat_init_output函数和write_header函数。
int avformat_write_header(AVFormatContext *s, AVDictionary **options)
{
int ret = 0;
int already_initialized = s->internal->initialized;
int streams_already_initialized = s->internal->streams_initialized;
if (!already_initialized)
// 这里初始化,一般来说,正常路径调用avformat_write_header,都会调用到这里
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) {
// 调用write_header函数,这个也是这里面最重要的函数。
// 比如在写入mp4的时候,会根据stream的extradata初始化一些参数。
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 (!s->internal->streams_initialized) {
if ((ret = init_pts(s)) < 0)
goto fail;
}
return streams_already_initialized;
fail:
deinit_muxer(s);
return ret;
}
其实就是init_muxer的一个封装,avformat_init_output在回输出多个文件的格式中会调用多次,比如m3u8格式。
int avformat_init_output(AVFormatContext *s, AVDictionary **options)
{
int ret = 0;
if ((ret = init_muxer(s, options)) < 0)
return ret;
s->internal->initialized = 1;
s->internal->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;
}
这个函数就三个作用,第一个作用是把options设置到AVFormatContext中,第二个作用就是遍历所有的AVStream,然后检测AVStream中的参数是否正确。 第三个就是看当前的AVOutputFormat是否实现了init方法,然后调用init
static int init_muxer(AVFormatContext *s, AVDictionary **options)
{
int ret = 0, i;
AVStream *st;
AVDictionary *tmp = NULL;
AVCodecParameters *par = NULL;
const AVOutputFormat *of = s->oformat;
const AVCodecDescriptor *desc;
AVDictionaryEntry *e;
if (options)
av_dict_copy(&tmp, *options, 0);
// 设置options到AVFormatContext中
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 FF_API_FORMAT_FILENAME
FF_DISABLE_DEPRECATION_WARNINGS
if (!s->url && !(s->url = av_strdup(s->filename))) {
FF_ENABLE_DEPRECATION_WARNINGS
#else
if (!s->url && !(s->url = av_strdup(""))) {
#endif
ret = AVERROR(ENOMEM);
goto fail;
}
#if FF_API_LAVF_AVCTX
FF_DISABLE_DEPRECATION_WARNINGS
if (s->nb_streams && s->streams[0]->codec->flags & AV_CODEC_FLAG_BITEXACT) {
if (!(s->flags & AVFMT_FLAG_BITEXACT)) {
av_log(s, AV_LOG_WARNING,
"The AVFormatContext is not in set to bitexact mode, only "
"the AVCodecContext. If this is not intended, set "
"AVFormatContext.flags |= AVFMT_FLAG_BITEXACT.\n");
}
}
FF_ENABLE_DEPRECATION_WARNINGS
#endif
// some sanity checks
if (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;
}
// 遍历所有的AVStream,然后检测格式
for (i = 0; i < s->nb_streams; i++) {
st = s->streams[i];
par = st->codecpar;
#if FF_API_LAVF_AVCTX
FF_DISABLE_DEPRECATION_WARNINGS
if (st->codecpar->codec_type == AVMEDIA_TYPE_UNKNOWN &&
st->codec->codec_type != AVMEDIA_TYPE_UNKNOWN) {
av_log(s, AV_LOG_WARNING, "Using AVStream.codec to pass codec "
"parameters to muxers is deprecated, use AVStream.codecpar "
"instead.\n");
ret = avcodec_parameters_from_context(st->codecpar, st->codec);
if (ret < 0)
goto fail;
}
FF_ENABLE_DEPRECATION_WARNINGS
#endif
//如果没有设置时间戳,就用avpriv_set_pts_info设置时间戳
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);
else
avpriv_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 (!par->block_align)
par->block_align = par->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)
st->internal->reorder = 1;
st->internal->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 here
par->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;
}
} else
par->codec_tag = av_codec_get_tag(of->codec_tag, par->codec_id);
}
if (par->codec_type != AVMEDIA_TYPE_ATTACHMENT)
s->internal->nb_interleaved_streams++;
}
// 检测是否为AVOuputFormat分配上下文空间
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;
}
// 这里调用init方法
// 在mp4中,根据context中设置的flag初始化一些数据,然后根据AVStream初始化对应的MOVTrack
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;
}