2 * Copyright (c) 2003 Fabrice Bellard
4 * Permission is hereby granted, free of charge, to any person obtaining a copy
5 * of this software and associated documentation files (the "Software"), to deal
6 * in the Software without restriction, including without limitation the rights
7 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8 * copies of the Software, and to permit persons to whom the Software is
9 * furnished to do so, subject to the following conditions:
11 * The above copyright notice and this permission notice shall be included in
12 * all copies or substantial portions of the Software.
14 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
17 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
25 * libavformat API example.
27 * Output a media file in any supported libavformat format. The default
37 #include <libavutil/opt.h>
38 #include <libavutil/mathematics.h>
39 #include <libavutil/timestamp.h>
40 #include <libavformat/avformat.h>
41 #include <libswscale/swscale.h>
42 #include <libswresample/swresample.h>
44 static int audio_is_eof, video_is_eof;
46 #define STREAM_DURATION 10.0
47 #define STREAM_FRAME_RATE 25 /* 25 images/s */
48 #define STREAM_PIX_FMT AV_PIX_FMT_YUV420P /* default pix_fmt */
50 static int sws_flags = SWS_BICUBIC;
52 static void log_packet(const AVFormatContext *fmt_ctx, const AVPacket *pkt)
54 AVRational *time_base = &fmt_ctx->streams[pkt->stream_index]->time_base;
56 printf("pts:%s pts_time:%s dts:%s dts_time:%s duration:%s duration_time:%s stream_index:%d\n",
57 av_ts2str(pkt->pts), av_ts2timestr(pkt->pts, time_base),
58 av_ts2str(pkt->dts), av_ts2timestr(pkt->dts, time_base),
59 av_ts2str(pkt->duration), av_ts2timestr(pkt->duration, time_base),
63 static int write_frame(AVFormatContext *fmt_ctx, const AVRational *time_base, AVStream *st, AVPacket *pkt)
65 /* rescale output packet timestamp values from codec to stream timebase */
66 av_packet_rescale_ts(pkt, *time_base, st->time_base);
67 pkt->stream_index = st->index;
69 /* Write the compressed frame to the media file. */
70 log_packet(fmt_ctx, pkt);
71 return av_interleaved_write_frame(fmt_ctx, pkt);
74 /* Add an output stream. */
75 static AVStream *add_stream(AVFormatContext *oc, AVCodec **codec,
76 enum AVCodecID codec_id)
81 /* find the encoder */
82 *codec = avcodec_find_encoder(codec_id);
84 fprintf(stderr, "Could not find encoder for '%s'\n",
85 avcodec_get_name(codec_id));
89 st = avformat_new_stream(oc, *codec);
91 fprintf(stderr, "Could not allocate stream\n");
94 st->id = oc->nb_streams-1;
97 switch ((*codec)->type) {
98 case AVMEDIA_TYPE_AUDIO:
99 c->sample_fmt = (*codec)->sample_fmts ?
100 (*codec)->sample_fmts[0] : AV_SAMPLE_FMT_FLTP;
102 c->sample_rate = 44100;
106 case AVMEDIA_TYPE_VIDEO:
107 c->codec_id = codec_id;
109 c->bit_rate = 400000;
110 /* Resolution must be a multiple of two. */
113 /* timebase: This is the fundamental unit of time (in seconds) in terms
114 * of which frame timestamps are represented. For fixed-fps content,
115 * timebase should be 1/framerate and timestamp increments should be
117 c->time_base.den = STREAM_FRAME_RATE;
118 c->time_base.num = 1;
119 c->gop_size = 12; /* emit one intra frame every twelve frames at most */
120 c->pix_fmt = STREAM_PIX_FMT;
121 if (c->codec_id == AV_CODEC_ID_MPEG2VIDEO) {
122 /* just for testing, we also add B frames */
125 if (c->codec_id == AV_CODEC_ID_MPEG1VIDEO) {
126 /* Needed to avoid using macroblocks in which some coeffs overflow.
127 * This does not happen with normal video, it just happens here as
128 * the motion of the chroma plane does not match the luma plane. */
137 /* Some formats want stream headers to be separate. */
138 if (oc->oformat->flags & AVFMT_GLOBALHEADER)
139 c->flags |= CODEC_FLAG_GLOBAL_HEADER;
144 /**************************************************************/
147 static float t, tincr, tincr2;
149 AVFrame *audio_frame;
150 static uint8_t **src_samples_data;
151 static int src_samples_linesize;
152 static int src_nb_samples;
154 static int max_dst_nb_samples;
155 uint8_t **dst_samples_data;
156 int dst_samples_linesize;
157 int dst_samples_size;
160 struct SwrContext *swr_ctx = NULL;
162 static void open_audio(AVFormatContext *oc, AVCodec *codec, AVStream *st)
169 /* allocate and init a re-usable frame */
170 audio_frame = av_frame_alloc();
172 fprintf(stderr, "Could not allocate audio frame\n");
177 ret = avcodec_open2(c, codec, NULL);
179 fprintf(stderr, "Could not open audio codec: %s\n", av_err2str(ret));
183 /* init signal generator */
185 tincr = 2 * M_PI * 110.0 / c->sample_rate;
186 /* increment frequency by 110 Hz per second */
187 tincr2 = 2 * M_PI * 110.0 / c->sample_rate / c->sample_rate;
189 src_nb_samples = c->codec->capabilities & CODEC_CAP_VARIABLE_FRAME_SIZE ?
190 10000 : c->frame_size;
192 ret = av_samples_alloc_array_and_samples(&src_samples_data, &src_samples_linesize, c->channels,
193 src_nb_samples, AV_SAMPLE_FMT_S16, 0);
195 fprintf(stderr, "Could not allocate source samples\n");
199 /* compute the number of converted samples: buffering is avoided
200 * ensuring that the output buffer will contain at least all the
201 * converted input samples */
202 max_dst_nb_samples = src_nb_samples;
204 /* create resampler context */
205 if (c->sample_fmt != AV_SAMPLE_FMT_S16) {
206 swr_ctx = swr_alloc();
208 fprintf(stderr, "Could not allocate resampler context\n");
213 av_opt_set_int (swr_ctx, "in_channel_count", c->channels, 0);
214 av_opt_set_int (swr_ctx, "in_sample_rate", c->sample_rate, 0);
215 av_opt_set_sample_fmt(swr_ctx, "in_sample_fmt", AV_SAMPLE_FMT_S16, 0);
216 av_opt_set_int (swr_ctx, "out_channel_count", c->channels, 0);
217 av_opt_set_int (swr_ctx, "out_sample_rate", c->sample_rate, 0);
218 av_opt_set_sample_fmt(swr_ctx, "out_sample_fmt", c->sample_fmt, 0);
220 /* initialize the resampling context */
221 if ((ret = swr_init(swr_ctx)) < 0) {
222 fprintf(stderr, "Failed to initialize the resampling context\n");
226 ret = av_samples_alloc_array_and_samples(&dst_samples_data, &dst_samples_linesize, c->channels,
227 max_dst_nb_samples, c->sample_fmt, 0);
229 fprintf(stderr, "Could not allocate destination samples\n");
233 dst_samples_data = src_samples_data;
235 dst_samples_size = av_samples_get_buffer_size(NULL, c->channels, max_dst_nb_samples,
239 /* Prepare a 16 bit dummy audio frame of 'frame_size' samples and
240 * 'nb_channels' channels. */
241 static void get_audio_frame(int16_t *samples, int frame_size, int nb_channels)
247 for (j = 0; j < frame_size; j++) {
248 v = (int)(sin(t) * 10000);
249 for (i = 0; i < nb_channels; i++)
256 static void write_audio_frame(AVFormatContext *oc, AVStream *st, int flush)
259 AVPacket pkt = { 0 }; // data and size must be 0;
260 int got_packet, ret, dst_nb_samples;
262 av_init_packet(&pkt);
266 get_audio_frame((int16_t *)src_samples_data[0], src_nb_samples, c->channels);
268 /* convert samples from native format to destination codec format, using the resampler */
270 /* compute destination number of samples */
271 dst_nb_samples = av_rescale_rnd(swr_get_delay(swr_ctx, c->sample_rate) + src_nb_samples,
272 c->sample_rate, c->sample_rate, AV_ROUND_UP);
273 if (dst_nb_samples > max_dst_nb_samples) {
274 av_free(dst_samples_data[0]);
275 ret = av_samples_alloc(dst_samples_data, &dst_samples_linesize, c->channels,
276 dst_nb_samples, c->sample_fmt, 0);
279 max_dst_nb_samples = dst_nb_samples;
280 dst_samples_size = av_samples_get_buffer_size(NULL, c->channels, dst_nb_samples,
284 /* convert to destination format */
285 ret = swr_convert(swr_ctx,
286 dst_samples_data, dst_nb_samples,
287 (const uint8_t **)src_samples_data, src_nb_samples);
289 fprintf(stderr, "Error while converting\n");
293 dst_nb_samples = src_nb_samples;
296 audio_frame->nb_samples = dst_nb_samples;
297 audio_frame->pts = av_rescale_q(samples_count, (AVRational){1, c->sample_rate}, c->time_base);
298 avcodec_fill_audio_frame(audio_frame, c->channels, c->sample_fmt,
299 dst_samples_data[0], dst_samples_size, 0);
300 samples_count += dst_nb_samples;
303 ret = avcodec_encode_audio2(c, &pkt, flush ? NULL : audio_frame, &got_packet);
305 fprintf(stderr, "Error encoding audio frame: %s\n", av_err2str(ret));
315 ret = write_frame(oc, &c->time_base, st, &pkt);
317 fprintf(stderr, "Error while writing audio frame: %s\n",
323 static void close_audio(AVFormatContext *oc, AVStream *st)
325 avcodec_close(st->codec);
326 if (dst_samples_data != src_samples_data) {
327 av_free(dst_samples_data[0]);
328 av_free(dst_samples_data);
330 av_free(src_samples_data[0]);
331 av_free(src_samples_data);
332 av_frame_free(&audio_frame);
335 /**************************************************************/
338 static AVFrame *frame;
339 static AVPicture src_picture, dst_picture;
340 static int frame_count;
342 static void open_video(AVFormatContext *oc, AVCodec *codec, AVStream *st)
345 AVCodecContext *c = st->codec;
348 ret = avcodec_open2(c, codec, NULL);
350 fprintf(stderr, "Could not open video codec: %s\n", av_err2str(ret));
354 /* allocate and init a re-usable frame */
355 frame = av_frame_alloc();
357 fprintf(stderr, "Could not allocate video frame\n");
360 frame->format = c->pix_fmt;
361 frame->width = c->width;
362 frame->height = c->height;
364 /* Allocate the encoded raw picture. */
365 ret = avpicture_alloc(&dst_picture, c->pix_fmt, c->width, c->height);
367 fprintf(stderr, "Could not allocate picture: %s\n", av_err2str(ret));
371 /* If the output format is not YUV420P, then a temporary YUV420P
372 * picture is needed too. It is then converted to the required
374 if (c->pix_fmt != AV_PIX_FMT_YUV420P) {
375 ret = avpicture_alloc(&src_picture, AV_PIX_FMT_YUV420P, c->width, c->height);
377 fprintf(stderr, "Could not allocate temporary picture: %s\n",
383 /* copy data and linesize picture pointers to frame */
384 *((AVPicture *)frame) = dst_picture;
387 /* Prepare a dummy image. */
388 static void fill_yuv_image(AVPicture *pict, int frame_index,
389 int width, int height)
396 for (y = 0; y < height; y++)
397 for (x = 0; x < width; x++)
398 pict->data[0][y * pict->linesize[0] + x] = x + y + i * 3;
401 for (y = 0; y < height / 2; y++) {
402 for (x = 0; x < width / 2; x++) {
403 pict->data[1][y * pict->linesize[1] + x] = 128 + y + i * 2;
404 pict->data[2][y * pict->linesize[2] + x] = 64 + x + i * 5;
409 static void write_video_frame(AVFormatContext *oc, AVStream *st, int flush)
412 static struct SwsContext *sws_ctx;
413 AVCodecContext *c = st->codec;
416 if (c->pix_fmt != AV_PIX_FMT_YUV420P) {
417 /* as we only generate a YUV420P picture, we must convert it
418 * to the codec pixel format if needed */
420 sws_ctx = sws_getContext(c->width, c->height, AV_PIX_FMT_YUV420P,
421 c->width, c->height, c->pix_fmt,
422 sws_flags, NULL, NULL, NULL);
425 "Could not initialize the conversion context\n");
429 fill_yuv_image(&src_picture, frame_count, c->width, c->height);
431 (const uint8_t * const *)src_picture.data, src_picture.linesize,
432 0, c->height, dst_picture.data, dst_picture.linesize);
434 fill_yuv_image(&dst_picture, frame_count, c->width, c->height);
438 if (oc->oformat->flags & AVFMT_RAWPICTURE && !flush) {
439 /* Raw video case - directly store the picture in the packet */
441 av_init_packet(&pkt);
443 pkt.flags |= AV_PKT_FLAG_KEY;
444 pkt.stream_index = st->index;
445 pkt.data = dst_picture.data[0];
446 pkt.size = sizeof(AVPicture);
448 ret = av_interleaved_write_frame(oc, &pkt);
450 AVPacket pkt = { 0 };
452 av_init_packet(&pkt);
454 /* encode the image */
455 frame->pts = frame_count;
456 ret = avcodec_encode_video2(c, &pkt, flush ? NULL : frame, &got_packet);
458 fprintf(stderr, "Error encoding video frame: %s\n", av_err2str(ret));
461 /* If size is zero, it means the image was buffered. */
464 ret = write_frame(oc, &c->time_base, st, &pkt);
473 fprintf(stderr, "Error while writing video frame: %s\n", av_err2str(ret));
479 static void close_video(AVFormatContext *oc, AVStream *st)
481 avcodec_close(st->codec);
482 av_free(src_picture.data[0]);
483 av_free(dst_picture.data[0]);
484 av_frame_free(&frame);
487 /**************************************************************/
488 /* media file output */
490 int main(int argc, char **argv)
492 const char *filename;
495 AVStream *audio_st, *video_st;
496 AVCodec *audio_codec, *video_codec;
497 double audio_time, video_time;
500 /* Initialize libavcodec, and register all codecs and formats. */
504 printf("usage: %s output_file\n"
505 "API example program to output a media file with libavformat.\n"
506 "This program generates a synthetic audio and video stream, encodes and\n"
507 "muxes them into a file named output_file.\n"
508 "The output format is automatically guessed according to the file extension.\n"
509 "Raw images can also be output by using '%%d' in the filename.\n"
516 /* allocate the output media context */
517 avformat_alloc_output_context2(&oc, NULL, NULL, filename);
519 printf("Could not deduce output format from file extension: using MPEG.\n");
520 avformat_alloc_output_context2(&oc, NULL, "mpeg", filename);
527 /* Add the audio and video streams using the default format codecs
528 * and initialize the codecs. */
532 if (fmt->video_codec != AV_CODEC_ID_NONE)
533 video_st = add_stream(oc, &video_codec, fmt->video_codec);
534 if (fmt->audio_codec != AV_CODEC_ID_NONE)
535 audio_st = add_stream(oc, &audio_codec, fmt->audio_codec);
537 /* Now that all the parameters are set, we can open the audio and
538 * video codecs and allocate the necessary encode buffers. */
540 open_video(oc, video_codec, video_st);
542 open_audio(oc, audio_codec, audio_st);
544 av_dump_format(oc, 0, filename, 1);
546 /* open the output file, if needed */
547 if (!(fmt->flags & AVFMT_NOFILE)) {
548 ret = avio_open(&oc->pb, filename, AVIO_FLAG_WRITE);
550 fprintf(stderr, "Could not open '%s': %s\n", filename,
556 /* Write the stream header, if any. */
557 ret = avformat_write_header(oc, NULL);
559 fprintf(stderr, "Error occurred when opening output file: %s\n",
565 while ((video_st && !video_is_eof) || (audio_st && !audio_is_eof)) {
566 /* Compute current audio and video time. */
567 audio_time = (audio_st && !audio_is_eof) ? audio_st->pts.val * av_q2d(audio_st->time_base) : INFINITY;
568 video_time = (video_st && !video_is_eof) ? video_st->pts.val * av_q2d(video_st->time_base) : INFINITY;
571 (!audio_st || audio_time >= STREAM_DURATION) &&
572 (!video_st || video_time >= STREAM_DURATION)) {
576 /* write interleaved audio and video frames */
577 if (audio_st && !audio_is_eof && audio_time <= video_time) {
578 write_audio_frame(oc, audio_st, flush);
579 } else if (video_st && !video_is_eof && video_time < audio_time) {
580 write_video_frame(oc, video_st, flush);
584 /* Write the trailer, if any. The trailer must be written before you
585 * close the CodecContexts open when you wrote the header; otherwise
586 * av_write_trailer() may try to use memory that was freed on
587 * av_codec_close(). */
588 av_write_trailer(oc);
590 /* Close each codec. */
592 close_video(oc, video_st);
594 close_audio(oc, audio_st);
596 if (!(fmt->flags & AVFMT_NOFILE))
597 /* Close the output file. */
600 /* free the stream */
601 avformat_free_context(oc);