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 pkt->pts = av_rescale_q_rnd(pkt->pts, *time_base, st->time_base, AV_ROUND_NEAR_INF|AV_ROUND_PASS_MINMAX);
67 pkt->dts = av_rescale_q_rnd(pkt->dts, *time_base, st->time_base, AV_ROUND_NEAR_INF|AV_ROUND_PASS_MINMAX);
68 pkt->duration = av_rescale_q(pkt->duration, *time_base, st->time_base);
69 pkt->stream_index = st->index;
71 /* Write the compressed frame to the media file. */
72 log_packet(fmt_ctx, pkt);
73 return av_interleaved_write_frame(fmt_ctx, pkt);
76 /* Add an output stream. */
77 static AVStream *add_stream(AVFormatContext *oc, AVCodec **codec,
78 enum AVCodecID codec_id)
83 /* find the encoder */
84 *codec = avcodec_find_encoder(codec_id);
86 fprintf(stderr, "Could not find encoder for '%s'\n",
87 avcodec_get_name(codec_id));
91 st = avformat_new_stream(oc, *codec);
93 fprintf(stderr, "Could not allocate stream\n");
96 st->id = oc->nb_streams-1;
99 switch ((*codec)->type) {
100 case AVMEDIA_TYPE_AUDIO:
101 c->sample_fmt = (*codec)->sample_fmts ?
102 (*codec)->sample_fmts[0] : AV_SAMPLE_FMT_FLTP;
104 c->sample_rate = 44100;
108 case AVMEDIA_TYPE_VIDEO:
109 c->codec_id = codec_id;
111 c->bit_rate = 400000;
112 /* Resolution must be a multiple of two. */
115 /* timebase: This is the fundamental unit of time (in seconds) in terms
116 * of which frame timestamps are represented. For fixed-fps content,
117 * timebase should be 1/framerate and timestamp increments should be
119 c->time_base.den = STREAM_FRAME_RATE;
120 c->time_base.num = 1;
121 c->gop_size = 12; /* emit one intra frame every twelve frames at most */
122 c->pix_fmt = STREAM_PIX_FMT;
123 if (c->codec_id == AV_CODEC_ID_MPEG2VIDEO) {
124 /* just for testing, we also add B frames */
127 if (c->codec_id == AV_CODEC_ID_MPEG1VIDEO) {
128 /* Needed to avoid using macroblocks in which some coeffs overflow.
129 * This does not happen with normal video, it just happens here as
130 * the motion of the chroma plane does not match the luma plane. */
139 /* Some formats want stream headers to be separate. */
140 if (oc->oformat->flags & AVFMT_GLOBALHEADER)
141 c->flags |= CODEC_FLAG_GLOBAL_HEADER;
146 /**************************************************************/
149 static float t, tincr, tincr2;
151 AVFrame *audio_frame;
152 static uint8_t **src_samples_data;
153 static int src_samples_linesize;
154 static int src_nb_samples;
156 static int max_dst_nb_samples;
157 uint8_t **dst_samples_data;
158 int dst_samples_linesize;
159 int dst_samples_size;
162 struct SwrContext *swr_ctx = NULL;
164 static void open_audio(AVFormatContext *oc, AVCodec *codec, AVStream *st)
171 /* allocate and init a re-usable frame */
172 audio_frame = av_frame_alloc();
174 fprintf(stderr, "Could not allocate audio frame\n");
179 ret = avcodec_open2(c, codec, NULL);
181 fprintf(stderr, "Could not open audio codec: %s\n", av_err2str(ret));
185 /* init signal generator */
187 tincr = 2 * M_PI * 110.0 / c->sample_rate;
188 /* increment frequency by 110 Hz per second */
189 tincr2 = 2 * M_PI * 110.0 / c->sample_rate / c->sample_rate;
191 src_nb_samples = c->codec->capabilities & CODEC_CAP_VARIABLE_FRAME_SIZE ?
192 10000 : c->frame_size;
194 ret = av_samples_alloc_array_and_samples(&src_samples_data, &src_samples_linesize, c->channels,
195 src_nb_samples, AV_SAMPLE_FMT_S16, 0);
197 fprintf(stderr, "Could not allocate source samples\n");
201 /* compute the number of converted samples: buffering is avoided
202 * ensuring that the output buffer will contain at least all the
203 * converted input samples */
204 max_dst_nb_samples = src_nb_samples;
206 /* create resampler context */
207 if (c->sample_fmt != AV_SAMPLE_FMT_S16) {
208 swr_ctx = swr_alloc();
210 fprintf(stderr, "Could not allocate resampler context\n");
215 av_opt_set_int (swr_ctx, "in_channel_count", c->channels, 0);
216 av_opt_set_int (swr_ctx, "in_sample_rate", c->sample_rate, 0);
217 av_opt_set_sample_fmt(swr_ctx, "in_sample_fmt", AV_SAMPLE_FMT_S16, 0);
218 av_opt_set_int (swr_ctx, "out_channel_count", c->channels, 0);
219 av_opt_set_int (swr_ctx, "out_sample_rate", c->sample_rate, 0);
220 av_opt_set_sample_fmt(swr_ctx, "out_sample_fmt", c->sample_fmt, 0);
222 /* initialize the resampling context */
223 if ((ret = swr_init(swr_ctx)) < 0) {
224 fprintf(stderr, "Failed to initialize the resampling context\n");
228 ret = av_samples_alloc_array_and_samples(&dst_samples_data, &dst_samples_linesize, c->channels,
229 max_dst_nb_samples, c->sample_fmt, 0);
231 fprintf(stderr, "Could not allocate destination samples\n");
235 dst_samples_data = src_samples_data;
237 dst_samples_size = av_samples_get_buffer_size(NULL, c->channels, max_dst_nb_samples,
241 /* Prepare a 16 bit dummy audio frame of 'frame_size' samples and
242 * 'nb_channels' channels. */
243 static void get_audio_frame(int16_t *samples, int frame_size, int nb_channels)
249 for (j = 0; j < frame_size; j++) {
250 v = (int)(sin(t) * 10000);
251 for (i = 0; i < nb_channels; i++)
258 static void write_audio_frame(AVFormatContext *oc, AVStream *st, int flush)
261 AVPacket pkt = { 0 }; // data and size must be 0;
262 int got_packet, ret, dst_nb_samples;
264 av_init_packet(&pkt);
268 get_audio_frame((int16_t *)src_samples_data[0], src_nb_samples, c->channels);
270 /* convert samples from native format to destination codec format, using the resampler */
272 /* compute destination number of samples */
273 dst_nb_samples = av_rescale_rnd(swr_get_delay(swr_ctx, c->sample_rate) + src_nb_samples,
274 c->sample_rate, c->sample_rate, AV_ROUND_UP);
275 if (dst_nb_samples > max_dst_nb_samples) {
276 av_free(dst_samples_data[0]);
277 ret = av_samples_alloc(dst_samples_data, &dst_samples_linesize, c->channels,
278 dst_nb_samples, c->sample_fmt, 0);
281 max_dst_nb_samples = dst_nb_samples;
282 dst_samples_size = av_samples_get_buffer_size(NULL, c->channels, dst_nb_samples,
286 /* convert to destination format */
287 ret = swr_convert(swr_ctx,
288 dst_samples_data, dst_nb_samples,
289 (const uint8_t **)src_samples_data, src_nb_samples);
291 fprintf(stderr, "Error while converting\n");
295 dst_nb_samples = src_nb_samples;
298 audio_frame->nb_samples = dst_nb_samples;
299 audio_frame->pts = av_rescale_q(samples_count, (AVRational){1, c->sample_rate}, c->time_base);
300 avcodec_fill_audio_frame(audio_frame, c->channels, c->sample_fmt,
301 dst_samples_data[0], dst_samples_size, 0);
302 samples_count += dst_nb_samples;
305 ret = avcodec_encode_audio2(c, &pkt, flush ? NULL : audio_frame, &got_packet);
307 fprintf(stderr, "Error encoding audio frame: %s\n", av_err2str(ret));
317 ret = write_frame(oc, &c->time_base, st, &pkt);
319 fprintf(stderr, "Error while writing audio frame: %s\n",
325 static void close_audio(AVFormatContext *oc, AVStream *st)
327 avcodec_close(st->codec);
328 if (dst_samples_data != src_samples_data) {
329 av_free(dst_samples_data[0]);
330 av_free(dst_samples_data);
332 av_free(src_samples_data[0]);
333 av_free(src_samples_data);
334 av_frame_free(&audio_frame);
337 /**************************************************************/
340 static AVFrame *frame;
341 static AVPicture src_picture, dst_picture;
342 static int frame_count;
344 static void open_video(AVFormatContext *oc, AVCodec *codec, AVStream *st)
347 AVCodecContext *c = st->codec;
350 ret = avcodec_open2(c, codec, NULL);
352 fprintf(stderr, "Could not open video codec: %s\n", av_err2str(ret));
356 /* allocate and init a re-usable frame */
357 frame = av_frame_alloc();
359 fprintf(stderr, "Could not allocate video frame\n");
362 frame->format = c->pix_fmt;
363 frame->width = c->width;
364 frame->height = c->height;
366 /* Allocate the encoded raw picture. */
367 ret = avpicture_alloc(&dst_picture, c->pix_fmt, c->width, c->height);
369 fprintf(stderr, "Could not allocate picture: %s\n", av_err2str(ret));
373 /* If the output format is not YUV420P, then a temporary YUV420P
374 * picture is needed too. It is then converted to the required
376 if (c->pix_fmt != AV_PIX_FMT_YUV420P) {
377 ret = avpicture_alloc(&src_picture, AV_PIX_FMT_YUV420P, c->width, c->height);
379 fprintf(stderr, "Could not allocate temporary picture: %s\n",
385 /* copy data and linesize picture pointers to frame */
386 *((AVPicture *)frame) = dst_picture;
389 /* Prepare a dummy image. */
390 static void fill_yuv_image(AVPicture *pict, int frame_index,
391 int width, int height)
398 for (y = 0; y < height; y++)
399 for (x = 0; x < width; x++)
400 pict->data[0][y * pict->linesize[0] + x] = x + y + i * 3;
403 for (y = 0; y < height / 2; y++) {
404 for (x = 0; x < width / 2; x++) {
405 pict->data[1][y * pict->linesize[1] + x] = 128 + y + i * 2;
406 pict->data[2][y * pict->linesize[2] + x] = 64 + x + i * 5;
411 static void write_video_frame(AVFormatContext *oc, AVStream *st, int flush)
414 static struct SwsContext *sws_ctx;
415 AVCodecContext *c = st->codec;
418 if (c->pix_fmt != AV_PIX_FMT_YUV420P) {
419 /* as we only generate a YUV420P picture, we must convert it
420 * to the codec pixel format if needed */
422 sws_ctx = sws_getContext(c->width, c->height, AV_PIX_FMT_YUV420P,
423 c->width, c->height, c->pix_fmt,
424 sws_flags, NULL, NULL, NULL);
427 "Could not initialize the conversion context\n");
431 fill_yuv_image(&src_picture, frame_count, c->width, c->height);
433 (const uint8_t * const *)src_picture.data, src_picture.linesize,
434 0, c->height, dst_picture.data, dst_picture.linesize);
436 fill_yuv_image(&dst_picture, frame_count, c->width, c->height);
440 if (oc->oformat->flags & AVFMT_RAWPICTURE && !flush) {
441 /* Raw video case - directly store the picture in the packet */
443 av_init_packet(&pkt);
445 pkt.flags |= AV_PKT_FLAG_KEY;
446 pkt.stream_index = st->index;
447 pkt.data = dst_picture.data[0];
448 pkt.size = sizeof(AVPicture);
450 ret = av_interleaved_write_frame(oc, &pkt);
452 AVPacket pkt = { 0 };
454 av_init_packet(&pkt);
456 /* encode the image */
457 frame->pts = frame_count;
458 ret = avcodec_encode_video2(c, &pkt, flush ? NULL : frame, &got_packet);
460 fprintf(stderr, "Error encoding video frame: %s\n", av_err2str(ret));
463 /* If size is zero, it means the image was buffered. */
466 ret = write_frame(oc, &c->time_base, st, &pkt);
475 fprintf(stderr, "Error while writing video frame: %s\n", av_err2str(ret));
481 static void close_video(AVFormatContext *oc, AVStream *st)
483 avcodec_close(st->codec);
484 av_free(src_picture.data[0]);
485 av_free(dst_picture.data[0]);
486 av_frame_free(&frame);
489 /**************************************************************/
490 /* media file output */
492 int main(int argc, char **argv)
494 const char *filename;
497 AVStream *audio_st, *video_st;
498 AVCodec *audio_codec, *video_codec;
499 double audio_time, video_time;
502 /* Initialize libavcodec, and register all codecs and formats. */
506 printf("usage: %s output_file\n"
507 "API example program to output a media file with libavformat.\n"
508 "This program generates a synthetic audio and video stream, encodes and\n"
509 "muxes them into a file named output_file.\n"
510 "The output format is automatically guessed according to the file extension.\n"
511 "Raw images can also be output by using '%%d' in the filename.\n"
518 /* allocate the output media context */
519 avformat_alloc_output_context2(&oc, NULL, NULL, filename);
521 printf("Could not deduce output format from file extension: using MPEG.\n");
522 avformat_alloc_output_context2(&oc, NULL, "mpeg", filename);
529 /* Add the audio and video streams using the default format codecs
530 * and initialize the codecs. */
534 if (fmt->video_codec != AV_CODEC_ID_NONE)
535 video_st = add_stream(oc, &video_codec, fmt->video_codec);
536 if (fmt->audio_codec != AV_CODEC_ID_NONE)
537 audio_st = add_stream(oc, &audio_codec, fmt->audio_codec);
539 /* Now that all the parameters are set, we can open the audio and
540 * video codecs and allocate the necessary encode buffers. */
542 open_video(oc, video_codec, video_st);
544 open_audio(oc, audio_codec, audio_st);
546 av_dump_format(oc, 0, filename, 1);
548 /* open the output file, if needed */
549 if (!(fmt->flags & AVFMT_NOFILE)) {
550 ret = avio_open(&oc->pb, filename, AVIO_FLAG_WRITE);
552 fprintf(stderr, "Could not open '%s': %s\n", filename,
558 /* Write the stream header, if any. */
559 ret = avformat_write_header(oc, NULL);
561 fprintf(stderr, "Error occurred when opening output file: %s\n",
567 while ((video_st && !video_is_eof) || (audio_st && !audio_is_eof)) {
568 /* Compute current audio and video time. */
569 audio_time = (audio_st && !audio_is_eof) ? audio_st->pts.val * av_q2d(audio_st->time_base) : INFINITY;
570 video_time = (video_st && !video_is_eof) ? video_st->pts.val * av_q2d(video_st->time_base) : INFINITY;
573 (!audio_st || audio_time >= STREAM_DURATION) &&
574 (!video_st || video_time >= STREAM_DURATION)) {
578 /* write interleaved audio and video frames */
579 if (audio_st && !audio_is_eof && audio_time <= video_time) {
580 write_audio_frame(oc, audio_st, flush);
581 } else if (video_st && !video_is_eof && video_time < audio_time) {
582 write_video_frame(oc, video_st, flush);
586 /* Write the trailer, if any. The trailer must be written before you
587 * close the CodecContexts open when you wrote the header; otherwise
588 * av_write_trailer() may try to use memory that was freed on
589 * av_codec_close(). */
590 av_write_trailer(oc);
592 /* Close each codec. */
594 close_video(oc, video_st);
596 close_audio(oc, audio_st);
598 if (!(fmt->flags & AVFMT_NOFILE))
599 /* Close the output file. */
602 /* free the stream */
603 avformat_free_context(oc);