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.
28 * Output a media file in any supported libavformat format. The default
37 #include "libavutil/channel_layout.h"
38 #include "libavutil/mathematics.h"
39 #include "libavutil/opt.h"
40 #include "libavformat/avformat.h"
41 #include "libavresample/avresample.h"
42 #include "libswscale/swscale.h"
44 /* 5 seconds stream duration */
45 #define STREAM_DURATION 5.0
46 #define STREAM_FRAME_RATE 25 /* 25 images/s */
47 #define STREAM_NB_FRAMES ((int)(STREAM_DURATION * STREAM_FRAME_RATE))
48 #define STREAM_PIX_FMT AV_PIX_FMT_YUV420P /* default pix_fmt */
50 #define SCALE_FLAGS SWS_BICUBIC
52 // a wrapper around a single output AVStream
53 typedef struct OutputStream {
56 /* pts of the next frame that will be generated */
62 float t, tincr, tincr2;
64 struct SwsContext *sws_ctx;
65 AVAudioResampleContext *avr;
68 /**************************************************************/
72 * add an audio output stream
74 static void add_audio_stream(OutputStream *ost, AVFormatContext *oc,
75 enum AVCodecID codec_id)
81 /* find the audio encoder */
82 codec = avcodec_find_encoder(codec_id);
84 fprintf(stderr, "codec not found\n");
88 ost->st = avformat_new_stream(oc, codec);
90 fprintf(stderr, "Could not alloc stream\n");
96 /* put sample parameters */
97 c->sample_fmt = codec->sample_fmts ? codec->sample_fmts[0] : AV_SAMPLE_FMT_S16;
98 c->sample_rate = codec->supported_samplerates ? codec->supported_samplerates[0] : 44100;
99 c->channel_layout = codec->channel_layouts ? codec->channel_layouts[0] : AV_CH_LAYOUT_STEREO;
100 c->channels = av_get_channel_layout_nb_channels(c->channel_layout);
103 ost->st->time_base = (AVRational){ 1, c->sample_rate };
105 // some formats want stream headers to be separate
106 if (oc->oformat->flags & AVFMT_GLOBALHEADER)
107 c->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
109 /* initialize sample format conversion;
110 * to simplify the code, we always pass the data through lavr, even
111 * if the encoder supports the generated format directly -- the price is
112 * some extra data copying;
114 ost->avr = avresample_alloc_context();
116 fprintf(stderr, "Error allocating the resampling context\n");
120 av_opt_set_int(ost->avr, "in_sample_fmt", AV_SAMPLE_FMT_S16, 0);
121 av_opt_set_int(ost->avr, "in_sample_rate", 44100, 0);
122 av_opt_set_int(ost->avr, "in_channel_layout", AV_CH_LAYOUT_STEREO, 0);
123 av_opt_set_int(ost->avr, "out_sample_fmt", c->sample_fmt, 0);
124 av_opt_set_int(ost->avr, "out_sample_rate", c->sample_rate, 0);
125 av_opt_set_int(ost->avr, "out_channel_layout", c->channel_layout, 0);
127 ret = avresample_open(ost->avr);
129 fprintf(stderr, "Error opening the resampling context\n");
134 static AVFrame *alloc_audio_frame(enum AVSampleFormat sample_fmt,
135 uint64_t channel_layout,
136 int sample_rate, int nb_samples)
138 AVFrame *frame = av_frame_alloc();
142 fprintf(stderr, "Error allocating an audio frame\n");
146 frame->format = sample_fmt;
147 frame->channel_layout = channel_layout;
148 frame->sample_rate = sample_rate;
149 frame->nb_samples = nb_samples;
152 ret = av_frame_get_buffer(frame, 0);
154 fprintf(stderr, "Error allocating an audio buffer\n");
162 static void open_audio(AVFormatContext *oc, OutputStream *ost)
170 if (avcodec_open2(c, NULL, NULL) < 0) {
171 fprintf(stderr, "could not open codec\n");
175 /* init signal generator */
177 ost->tincr = 2 * M_PI * 110.0 / c->sample_rate;
178 /* increment frequency by 110 Hz per second */
179 ost->tincr2 = 2 * M_PI * 110.0 / c->sample_rate / c->sample_rate;
181 if (c->codec->capabilities & AV_CODEC_CAP_VARIABLE_FRAME_SIZE)
184 nb_samples = c->frame_size;
186 ost->frame = alloc_audio_frame(c->sample_fmt, c->channel_layout,
187 c->sample_rate, nb_samples);
188 ost->tmp_frame = alloc_audio_frame(AV_SAMPLE_FMT_S16, AV_CH_LAYOUT_STEREO,
192 /* Prepare a 16 bit dummy audio frame of 'frame_size' samples and
193 * 'nb_channels' channels. */
194 static AVFrame *get_audio_frame(OutputStream *ost)
196 AVFrame *frame = ost->tmp_frame;
198 int16_t *q = (int16_t*)frame->data[0];
200 /* check if we want to generate more frames */
201 if (av_compare_ts(ost->next_pts, ost->st->codec->time_base,
202 STREAM_DURATION, (AVRational){ 1, 1 }) >= 0)
206 for (j = 0; j < frame->nb_samples; j++) {
207 v = (int)(sin(ost->t) * 10000);
208 for (i = 0; i < ost->st->codec->channels; i++)
210 ost->t += ost->tincr;
211 ost->tincr += ost->tincr2;
217 /* if a frame is provided, send it to the encoder, otherwise flush the encoder;
218 * return 1 when encoding is finished, 0 otherwise
220 static int encode_audio_frame(AVFormatContext *oc, OutputStream *ost,
223 AVPacket pkt = { 0 }; // data and size must be 0;
226 av_init_packet(&pkt);
227 avcodec_encode_audio2(ost->st->codec, &pkt, frame, &got_packet);
230 pkt.stream_index = ost->st->index;
232 av_packet_rescale_ts(&pkt, ost->st->codec->time_base, ost->st->time_base);
234 /* Write the compressed frame to the media file. */
235 if (av_interleaved_write_frame(oc, &pkt) != 0) {
236 fprintf(stderr, "Error while writing audio frame\n");
241 return (frame || got_packet) ? 0 : 1;
245 * encode one audio frame and send it to the muxer
246 * return 1 when encoding is finished, 0 otherwise
248 static int process_audio_stream(AVFormatContext *oc, OutputStream *ost)
254 frame = get_audio_frame(ost);
255 got_output |= !!frame;
257 /* feed the data to lavr */
259 ret = avresample_convert(ost->avr, NULL, 0, 0,
260 frame->extended_data, frame->linesize[0],
263 fprintf(stderr, "Error feeding audio data to the resampler\n");
268 while ((frame && avresample_available(ost->avr) >= ost->frame->nb_samples) ||
269 (!frame && avresample_get_out_samples(ost->avr, 0))) {
270 /* when we pass a frame to the encoder, it may keep a reference to it
272 * make sure we do not overwrite it here
274 ret = av_frame_make_writable(ost->frame);
278 /* the difference between the two avresample calls here is that the
279 * first one just reads the already converted data that is buffered in
280 * the lavr output buffer, while the second one also flushes the
283 ret = avresample_read(ost->avr, ost->frame->extended_data,
284 ost->frame->nb_samples);
286 ret = avresample_convert(ost->avr, ost->frame->extended_data,
287 ost->frame->linesize[0], ost->frame->nb_samples,
292 fprintf(stderr, "Error while resampling\n");
294 } else if (frame && ret != ost->frame->nb_samples) {
295 fprintf(stderr, "Too few samples returned from lavr\n");
299 ost->frame->nb_samples = ret;
301 ost->frame->pts = ost->next_pts;
302 ost->next_pts += ost->frame->nb_samples;
304 got_output |= encode_audio_frame(oc, ost, ret ? ost->frame : NULL);
310 /**************************************************************/
313 /* Add a video output stream. */
314 static void add_video_stream(OutputStream *ost, AVFormatContext *oc,
315 enum AVCodecID codec_id)
320 /* find the video encoder */
321 codec = avcodec_find_encoder(codec_id);
323 fprintf(stderr, "codec not found\n");
327 ost->st = avformat_new_stream(oc, codec);
329 fprintf(stderr, "Could not alloc stream\n");
335 /* Put sample parameters. */
336 c->bit_rate = 400000;
337 /* Resolution must be a multiple of two. */
340 /* timebase: This is the fundamental unit of time (in seconds) in terms
341 * of which frame timestamps are represented. For fixed-fps content,
342 * timebase should be 1/framerate and timestamp increments should be
344 ost->st->time_base = (AVRational){ 1, STREAM_FRAME_RATE };
345 c->time_base = ost->st->time_base;
347 c->gop_size = 12; /* emit one intra frame every twelve frames at most */
348 c->pix_fmt = STREAM_PIX_FMT;
349 if (c->codec_id == AV_CODEC_ID_MPEG2VIDEO) {
350 /* just for testing, we also add B frames */
353 if (c->codec_id == AV_CODEC_ID_MPEG1VIDEO) {
354 /* Needed to avoid using macroblocks in which some coeffs overflow.
355 * This does not happen with normal video, it just happens here as
356 * the motion of the chroma plane does not match the luma plane. */
359 /* Some formats want stream headers to be separate. */
360 if (oc->oformat->flags & AVFMT_GLOBALHEADER)
361 c->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
364 static AVFrame *alloc_picture(enum AVPixelFormat pix_fmt, int width, int height)
369 picture = av_frame_alloc();
373 picture->format = pix_fmt;
374 picture->width = width;
375 picture->height = height;
377 /* allocate the buffers for the frame data */
378 ret = av_frame_get_buffer(picture, 32);
380 fprintf(stderr, "Could not allocate frame data.\n");
387 static void open_video(AVFormatContext *oc, OutputStream *ost)
394 if (avcodec_open2(c, NULL, NULL) < 0) {
395 fprintf(stderr, "could not open codec\n");
399 /* Allocate the encoded raw picture. */
400 ost->frame = alloc_picture(c->pix_fmt, c->width, c->height);
402 fprintf(stderr, "Could not allocate picture\n");
406 /* If the output format is not YUV420P, then a temporary YUV420P
407 * picture is needed too. It is then converted to the required
409 ost->tmp_frame = NULL;
410 if (c->pix_fmt != AV_PIX_FMT_YUV420P) {
411 ost->tmp_frame = alloc_picture(AV_PIX_FMT_YUV420P, c->width, c->height);
412 if (!ost->tmp_frame) {
413 fprintf(stderr, "Could not allocate temporary picture\n");
419 /* Prepare a dummy image. */
420 static void fill_yuv_image(AVFrame *pict, int frame_index,
421 int width, int height)
425 /* when we pass a frame to the encoder, it may keep a reference to it
427 * make sure we do not overwrite it here
429 ret = av_frame_make_writable(pict);
436 for (y = 0; y < height; y++)
437 for (x = 0; x < width; x++)
438 pict->data[0][y * pict->linesize[0] + x] = x + y + i * 3;
441 for (y = 0; y < height / 2; y++) {
442 for (x = 0; x < width / 2; x++) {
443 pict->data[1][y * pict->linesize[1] + x] = 128 + y + i * 2;
444 pict->data[2][y * pict->linesize[2] + x] = 64 + x + i * 5;
449 static AVFrame *get_video_frame(OutputStream *ost)
451 AVCodecContext *c = ost->st->codec;
453 /* check if we want to generate more frames */
454 if (av_compare_ts(ost->next_pts, ost->st->codec->time_base,
455 STREAM_DURATION, (AVRational){ 1, 1 }) >= 0)
458 if (c->pix_fmt != AV_PIX_FMT_YUV420P) {
459 /* as we only generate a YUV420P picture, we must convert it
460 * to the codec pixel format if needed */
462 ost->sws_ctx = sws_getContext(c->width, c->height,
466 SCALE_FLAGS, NULL, NULL, NULL);
469 "Cannot initialize the conversion context\n");
473 fill_yuv_image(ost->tmp_frame, ost->next_pts, c->width, c->height);
474 sws_scale(ost->sws_ctx, ost->tmp_frame->data, ost->tmp_frame->linesize,
475 0, c->height, ost->frame->data, ost->frame->linesize);
477 fill_yuv_image(ost->frame, ost->next_pts, c->width, c->height);
480 ost->frame->pts = ost->next_pts++;
486 * encode one video frame and send it to the muxer
487 * return 1 when encoding is finished, 0 otherwise
489 static int write_video_frame(AVFormatContext *oc, OutputStream *ost)
498 frame = get_video_frame(ost);
500 if (oc->oformat->flags & AVFMT_RAWPICTURE) {
501 /* a hack to avoid data copy with some raw video muxers */
503 av_init_packet(&pkt);
508 pkt.flags |= AV_PKT_FLAG_KEY;
509 pkt.stream_index = ost->st->index;
510 pkt.data = (uint8_t *)frame;
511 pkt.size = sizeof(AVPicture);
513 pkt.pts = pkt.dts = frame->pts;
514 av_packet_rescale_ts(&pkt, c->time_base, ost->st->time_base);
516 ret = av_interleaved_write_frame(oc, &pkt);
518 AVPacket pkt = { 0 };
519 av_init_packet(&pkt);
521 /* encode the image */
522 ret = avcodec_encode_video2(c, &pkt, frame, &got_packet);
524 fprintf(stderr, "Error encoding a video frame\n");
529 av_packet_rescale_ts(&pkt, c->time_base, ost->st->time_base);
530 pkt.stream_index = ost->st->index;
532 /* Write the compressed frame to the media file. */
533 ret = av_interleaved_write_frame(oc, &pkt);
537 fprintf(stderr, "Error while writing video frame\n");
541 return (frame || got_packet) ? 0 : 1;
544 static void close_stream(AVFormatContext *oc, OutputStream *ost)
546 avcodec_close(ost->st->codec);
547 av_frame_free(&ost->frame);
548 av_frame_free(&ost->tmp_frame);
549 sws_freeContext(ost->sws_ctx);
550 avresample_free(&ost->avr);
553 /**************************************************************/
554 /* media file output */
556 int main(int argc, char **argv)
558 OutputStream video_st = { 0 }, audio_st = { 0 };
559 const char *filename;
562 int have_video = 0, have_audio = 0;
563 int encode_video = 0, encode_audio = 0;
565 /* Initialize libavcodec, and register all codecs and formats. */
569 printf("usage: %s output_file\n"
570 "API example program to output a media file with libavformat.\n"
571 "The output format is automatically guessed according to the file extension.\n"
572 "Raw images can also be output by using '%%d' in the filename\n"
579 /* Autodetect the output format from the name. default is MPEG. */
580 fmt = av_guess_format(NULL, filename, NULL);
582 printf("Could not deduce output format from file extension: using MPEG.\n");
583 fmt = av_guess_format("mpeg", NULL, NULL);
586 fprintf(stderr, "Could not find suitable output format\n");
590 /* Allocate the output media context. */
591 oc = avformat_alloc_context();
593 fprintf(stderr, "Memory error\n");
597 snprintf(oc->filename, sizeof(oc->filename), "%s", filename);
599 /* Add the audio and video streams using the default format codecs
600 * and initialize the codecs. */
601 if (fmt->video_codec != AV_CODEC_ID_NONE) {
602 add_video_stream(&video_st, oc, fmt->video_codec);
606 if (fmt->audio_codec != AV_CODEC_ID_NONE) {
607 add_audio_stream(&audio_st, oc, fmt->audio_codec);
612 /* Now that all the parameters are set, we can open the audio and
613 * video codecs and allocate the necessary encode buffers. */
615 open_video(oc, &video_st);
617 open_audio(oc, &audio_st);
619 av_dump_format(oc, 0, filename, 1);
621 /* open the output file, if needed */
622 if (!(fmt->flags & AVFMT_NOFILE)) {
623 if (avio_open(&oc->pb, filename, AVIO_FLAG_WRITE) < 0) {
624 fprintf(stderr, "Could not open '%s'\n", filename);
629 /* Write the stream header, if any. */
630 avformat_write_header(oc, NULL);
632 while (encode_video || encode_audio) {
633 /* select the stream to encode */
635 (!encode_audio || av_compare_ts(video_st.next_pts, video_st.st->codec->time_base,
636 audio_st.next_pts, audio_st.st->codec->time_base) <= 0)) {
637 encode_video = !write_video_frame(oc, &video_st);
639 encode_audio = !process_audio_stream(oc, &audio_st);
643 /* Write the trailer, if any. The trailer must be written before you
644 * close the CodecContexts open when you wrote the header; otherwise
645 * av_write_trailer() may try to use memory that was freed on
646 * av_codec_close(). */
647 av_write_trailer(oc);
649 /* Close each codec. */
651 close_stream(oc, &video_st);
653 close_stream(oc, &audio_st);
655 if (!(fmt->flags & AVFMT_NOFILE))
656 /* Close the output file. */
659 /* free the stream */
660 avformat_free_context(oc);