]> git.sesse.net Git - ffmpeg/blob - doc/examples/muxing.c
Merge commit 'ac85f631c9a9cc59aaca1c8dd6894fb1f701c594'
[ffmpeg] / doc / examples / muxing.c
1 /*
2  * Copyright (c) 2003 Fabrice Bellard
3  *
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:
10  *
11  * The above copyright notice and this permission notice shall be included in
12  * all copies or substantial portions of the Software.
13  *
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
20  * THE SOFTWARE.
21  */
22
23 /**
24  * @file
25  * libavformat API example.
26  *
27  * Output a media file in any supported libavformat format. The default
28  * codecs are used.
29  * @example muxing.c
30  */
31
32 #include <stdlib.h>
33 #include <stdio.h>
34 #include <string.h>
35 #include <math.h>
36
37 #include <libavutil/channel_layout.h>
38 #include <libavutil/opt.h>
39 #include <libavutil/mathematics.h>
40 #include <libavutil/timestamp.h>
41 #include <libavformat/avformat.h>
42 #include <libswscale/swscale.h>
43 #include <libswresample/swresample.h>
44
45 static int audio_is_eof, video_is_eof;
46
47 #define STREAM_DURATION   10.0
48 #define STREAM_FRAME_RATE 25 /* 25 images/s */
49 #define STREAM_PIX_FMT    AV_PIX_FMT_YUV420P /* default pix_fmt */
50
51 static int sws_flags = SWS_BICUBIC;
52
53 // a wrapper around a single output AVStream
54 typedef struct OutputStream {
55     AVStream *st;
56
57     AVFrame *frame;
58     AVFrame *tmp_frame;
59 } OutputStream;
60
61 static void log_packet(const AVFormatContext *fmt_ctx, const AVPacket *pkt)
62 {
63     AVRational *time_base = &fmt_ctx->streams[pkt->stream_index]->time_base;
64
65     printf("pts:%s pts_time:%s dts:%s dts_time:%s duration:%s duration_time:%s stream_index:%d\n",
66            av_ts2str(pkt->pts), av_ts2timestr(pkt->pts, time_base),
67            av_ts2str(pkt->dts), av_ts2timestr(pkt->dts, time_base),
68            av_ts2str(pkt->duration), av_ts2timestr(pkt->duration, time_base),
69            pkt->stream_index);
70 }
71
72 static int write_frame(AVFormatContext *fmt_ctx, const AVRational *time_base, AVStream *st, AVPacket *pkt)
73 {
74     /* rescale output packet timestamp values from codec to stream timebase */
75     av_packet_rescale_ts(pkt, *time_base, st->time_base);
76     pkt->stream_index = st->index;
77
78     /* Write the compressed frame to the media file. */
79     log_packet(fmt_ctx, pkt);
80     return av_interleaved_write_frame(fmt_ctx, pkt);
81 }
82
83 /* Add an output stream. */
84 static AVStream *add_stream(OutputStream *ost, AVFormatContext *oc,
85                             AVCodec **codec,
86                             enum AVCodecID codec_id)
87 {
88     AVCodecContext *c;
89
90     /* find the encoder */
91     *codec = avcodec_find_encoder(codec_id);
92     if (!(*codec)) {
93         fprintf(stderr, "Could not find encoder for '%s'\n",
94                 avcodec_get_name(codec_id));
95         exit(1);
96     }
97
98     ost->st = avformat_new_stream(oc, *codec);
99     if (!ost->st) {
100         fprintf(stderr, "Could not allocate stream\n");
101         exit(1);
102     }
103     ost->st->id = oc->nb_streams-1;
104     c = ost->st->codec;
105
106     switch ((*codec)->type) {
107     case AVMEDIA_TYPE_AUDIO:
108         c->sample_fmt  = (*codec)->sample_fmts ?
109             (*codec)->sample_fmts[0] : AV_SAMPLE_FMT_FLTP;
110         c->bit_rate    = 64000;
111         c->sample_rate = 44100;
112         c->channels    = 2;
113         c->channel_layout = AV_CH_LAYOUT_STEREO;
114         break;
115
116     case AVMEDIA_TYPE_VIDEO:
117         c->codec_id = codec_id;
118
119         c->bit_rate = 400000;
120         /* Resolution must be a multiple of two. */
121         c->width    = 352;
122         c->height   = 288;
123         /* timebase: This is the fundamental unit of time (in seconds) in terms
124          * of which frame timestamps are represented. For fixed-fps content,
125          * timebase should be 1/framerate and timestamp increments should be
126          * identical to 1. */
127         c->time_base.den = STREAM_FRAME_RATE;
128         c->time_base.num = 1;
129         c->gop_size      = 12; /* emit one intra frame every twelve frames at most */
130         c->pix_fmt       = STREAM_PIX_FMT;
131         if (c->codec_id == AV_CODEC_ID_MPEG2VIDEO) {
132             /* just for testing, we also add B frames */
133             c->max_b_frames = 2;
134         }
135         if (c->codec_id == AV_CODEC_ID_MPEG1VIDEO) {
136             /* Needed to avoid using macroblocks in which some coeffs overflow.
137              * This does not happen with normal video, it just happens here as
138              * the motion of the chroma plane does not match the luma plane. */
139             c->mb_decision = 2;
140         }
141     break;
142
143     default:
144         break;
145     }
146
147     /* Some formats want stream headers to be separate. */
148     if (oc->oformat->flags & AVFMT_GLOBALHEADER)
149         c->flags |= CODEC_FLAG_GLOBAL_HEADER;
150
151     return ost->st;
152 }
153
154 /**************************************************************/
155 /* audio output */
156
157 static float t, tincr, tincr2;
158
159 AVFrame *audio_frame;
160 static uint8_t **src_samples_data;
161 static int       src_samples_linesize;
162 static int       src_nb_samples;
163
164 static int max_dst_nb_samples;
165 uint8_t **dst_samples_data;
166 int       dst_samples_linesize;
167 int       dst_samples_size;
168 int samples_count;
169
170 struct SwrContext *swr_ctx = NULL;
171
172 static void open_audio(AVFormatContext *oc, AVCodec *codec, AVStream *st)
173 {
174     AVCodecContext *c;
175     int ret;
176
177     c = st->codec;
178
179     /* allocate and init a re-usable frame */
180     audio_frame = av_frame_alloc();
181     if (!audio_frame) {
182         fprintf(stderr, "Could not allocate audio frame\n");
183         exit(1);
184     }
185
186     /* open it */
187     ret = avcodec_open2(c, codec, NULL);
188     if (ret < 0) {
189         fprintf(stderr, "Could not open audio codec: %s\n", av_err2str(ret));
190         exit(1);
191     }
192
193     /* init signal generator */
194     t     = 0;
195     tincr = 2 * M_PI * 110.0 / c->sample_rate;
196     /* increment frequency by 110 Hz per second */
197     tincr2 = 2 * M_PI * 110.0 / c->sample_rate / c->sample_rate;
198
199     src_nb_samples = c->codec->capabilities & CODEC_CAP_VARIABLE_FRAME_SIZE ?
200         10000 : c->frame_size;
201
202     ret = av_samples_alloc_array_and_samples(&src_samples_data, &src_samples_linesize, c->channels,
203                                              src_nb_samples, AV_SAMPLE_FMT_S16, 0);
204     if (ret < 0) {
205         fprintf(stderr, "Could not allocate source samples\n");
206         exit(1);
207     }
208
209     /* compute the number of converted samples: buffering is avoided
210      * ensuring that the output buffer will contain at least all the
211      * converted input samples */
212     max_dst_nb_samples = src_nb_samples;
213
214     /* create resampler context */
215     if (c->sample_fmt != AV_SAMPLE_FMT_S16) {
216         swr_ctx = swr_alloc();
217         if (!swr_ctx) {
218             fprintf(stderr, "Could not allocate resampler context\n");
219             exit(1);
220         }
221
222         /* set options */
223         av_opt_set_int       (swr_ctx, "in_channel_count",   c->channels,       0);
224         av_opt_set_int       (swr_ctx, "in_sample_rate",     c->sample_rate,    0);
225         av_opt_set_sample_fmt(swr_ctx, "in_sample_fmt",      AV_SAMPLE_FMT_S16, 0);
226         av_opt_set_int       (swr_ctx, "out_channel_count",  c->channels,       0);
227         av_opt_set_int       (swr_ctx, "out_sample_rate",    c->sample_rate,    0);
228         av_opt_set_sample_fmt(swr_ctx, "out_sample_fmt",     c->sample_fmt,     0);
229
230         /* initialize the resampling context */
231         if ((ret = swr_init(swr_ctx)) < 0) {
232             fprintf(stderr, "Failed to initialize the resampling context\n");
233             exit(1);
234         }
235
236         ret = av_samples_alloc_array_and_samples(&dst_samples_data, &dst_samples_linesize, c->channels,
237                                                  max_dst_nb_samples, c->sample_fmt, 0);
238         if (ret < 0) {
239             fprintf(stderr, "Could not allocate destination samples\n");
240             exit(1);
241         }
242     } else {
243         dst_samples_data = src_samples_data;
244     }
245     dst_samples_size = av_samples_get_buffer_size(NULL, c->channels, max_dst_nb_samples,
246                                                   c->sample_fmt, 0);
247 }
248
249 /* Prepare a 16 bit dummy audio frame of 'frame_size' samples and
250  * 'nb_channels' channels. */
251 static void get_audio_frame(int16_t *samples, int frame_size, int nb_channels)
252 {
253     int j, i, v;
254     int16_t *q;
255
256     q = samples;
257     for (j = 0; j < frame_size; j++) {
258         v = (int)(sin(t) * 10000);
259         for (i = 0; i < nb_channels; i++)
260             *q++ = v;
261         t     += tincr;
262         tincr += tincr2;
263     }
264 }
265
266 static void write_audio_frame(AVFormatContext *oc, AVStream *st, int flush)
267 {
268     AVCodecContext *c;
269     AVPacket pkt = { 0 }; // data and size must be 0;
270     int got_packet, ret, dst_nb_samples;
271
272     av_init_packet(&pkt);
273     c = st->codec;
274
275     if (!flush) {
276         get_audio_frame((int16_t *)src_samples_data[0], src_nb_samples, c->channels);
277
278         /* convert samples from native format to destination codec format, using the resampler */
279         if (swr_ctx) {
280             /* compute destination number of samples */
281             dst_nb_samples = av_rescale_rnd(swr_get_delay(swr_ctx, c->sample_rate) + src_nb_samples,
282                                             c->sample_rate, c->sample_rate, AV_ROUND_UP);
283             if (dst_nb_samples > max_dst_nb_samples) {
284                 av_free(dst_samples_data[0]);
285                 ret = av_samples_alloc(dst_samples_data, &dst_samples_linesize, c->channels,
286                                        dst_nb_samples, c->sample_fmt, 0);
287                 if (ret < 0)
288                     exit(1);
289                 max_dst_nb_samples = dst_nb_samples;
290                 dst_samples_size = av_samples_get_buffer_size(NULL, c->channels, dst_nb_samples,
291                                                               c->sample_fmt, 0);
292             }
293
294             /* convert to destination format */
295             ret = swr_convert(swr_ctx,
296                               dst_samples_data, dst_nb_samples,
297                               (const uint8_t **)src_samples_data, src_nb_samples);
298             if (ret < 0) {
299                 fprintf(stderr, "Error while converting\n");
300                 exit(1);
301             }
302         } else {
303             dst_nb_samples = src_nb_samples;
304         }
305
306         audio_frame->nb_samples = dst_nb_samples;
307         audio_frame->pts = av_rescale_q(samples_count, (AVRational){1, c->sample_rate}, c->time_base);
308         avcodec_fill_audio_frame(audio_frame, c->channels, c->sample_fmt,
309                                  dst_samples_data[0], dst_samples_size, 0);
310         samples_count += dst_nb_samples;
311     }
312
313     ret = avcodec_encode_audio2(c, &pkt, flush ? NULL : audio_frame, &got_packet);
314     if (ret < 0) {
315         fprintf(stderr, "Error encoding audio frame: %s\n", av_err2str(ret));
316         exit(1);
317     }
318
319     if (!got_packet) {
320         if (flush)
321             audio_is_eof = 1;
322         return;
323     }
324
325     ret = write_frame(oc, &c->time_base, st, &pkt);
326     if (ret < 0) {
327         fprintf(stderr, "Error while writing audio frame: %s\n",
328                 av_err2str(ret));
329         exit(1);
330     }
331 }
332
333 static void close_audio(AVFormatContext *oc, AVStream *st)
334 {
335     avcodec_close(st->codec);
336     if (dst_samples_data != src_samples_data) {
337         av_free(dst_samples_data[0]);
338         av_free(dst_samples_data);
339     }
340     av_free(src_samples_data[0]);
341     av_free(src_samples_data);
342     av_frame_free(&audio_frame);
343 }
344
345 /**************************************************************/
346 /* video output */
347
348 static int frame_count;
349
350 static AVFrame *alloc_picture(enum AVPixelFormat pix_fmt, int width, int height)
351 {
352     AVFrame *picture;
353     int ret;
354
355     picture = av_frame_alloc();
356     if (!picture)
357         return NULL;
358
359     picture->format = pix_fmt;
360     picture->width  = width;
361     picture->height = height;
362
363     /* allocate the buffers for the frame data */
364     ret = av_frame_get_buffer(picture, 32);
365     if (ret < 0) {
366         fprintf(stderr, "Could not allocate frame data.\n");
367         exit(1);
368     }
369
370     return picture;
371 }
372
373 static void open_video(AVFormatContext *oc, AVCodec *codec, OutputStream *ost)
374 {
375     int ret;
376     AVCodecContext *c = ost->st->codec;
377
378     /* open the codec */
379     ret = avcodec_open2(c, codec, NULL);
380     if (ret < 0) {
381         fprintf(stderr, "Could not open video codec: %s\n", av_err2str(ret));
382         exit(1);
383     }
384
385     /* allocate and init a re-usable frame */
386     ost->frame = alloc_picture(c->pix_fmt, c->width, c->height);
387     if (!ost->frame) {
388         fprintf(stderr, "Could not allocate video frame\n");
389         exit(1);
390     }
391
392     /* If the output format is not YUV420P, then a temporary YUV420P
393      * picture is needed too. It is then converted to the required
394      * output format. */
395     ost->tmp_frame = NULL;
396     if (c->pix_fmt != AV_PIX_FMT_YUV420P) {
397         ost->tmp_frame = alloc_picture(AV_PIX_FMT_YUV420P, c->width, c->height);
398         if (!ost->tmp_frame) {
399             fprintf(stderr, "Could not allocate temporary picture\n");
400             exit(1);
401         }
402     }
403 }
404
405 /* Prepare a dummy image. */
406 static void fill_yuv_image(AVFrame *pict, int frame_index,
407                            int width, int height)
408 {
409     int x, y, i, ret;
410
411     /* when we pass a frame to the encoder, it may keep a reference to it
412      * internally;
413      * make sure we do not overwrite it here
414      */
415     ret = av_frame_make_writable(pict);
416     if (ret < 0)
417         exit(1);
418
419     i = frame_index;
420
421     /* Y */
422     for (y = 0; y < height; y++)
423         for (x = 0; x < width; x++)
424             pict->data[0][y * pict->linesize[0] + x] = x + y + i * 3;
425
426     /* Cb and Cr */
427     for (y = 0; y < height / 2; y++) {
428         for (x = 0; x < width / 2; x++) {
429             pict->data[1][y * pict->linesize[1] + x] = 128 + y + i * 2;
430             pict->data[2][y * pict->linesize[2] + x] = 64 + x + i * 5;
431         }
432     }
433 }
434
435 static void write_video_frame(AVFormatContext *oc, OutputStream *ost, int flush)
436 {
437     int ret;
438     static struct SwsContext *sws_ctx;
439     AVCodecContext *c = ost->st->codec;
440
441     if (!flush) {
442         if (c->pix_fmt != AV_PIX_FMT_YUV420P) {
443             /* as we only generate a YUV420P picture, we must convert it
444              * to the codec pixel format if needed */
445             if (!sws_ctx) {
446                 sws_ctx = sws_getContext(c->width, c->height, AV_PIX_FMT_YUV420P,
447                                          c->width, c->height, c->pix_fmt,
448                                          sws_flags, NULL, NULL, NULL);
449                 if (!sws_ctx) {
450                     fprintf(stderr,
451                             "Could not initialize the conversion context\n");
452                     exit(1);
453                 }
454             }
455             fill_yuv_image(ost->tmp_frame, frame_count, c->width, c->height);
456             sws_scale(sws_ctx,
457                       (const uint8_t * const *)ost->tmp_frame->data, ost->tmp_frame->linesize,
458                       0, c->height, ost->frame->data, ost->frame->linesize);
459         } else {
460             fill_yuv_image(ost->frame, frame_count, c->width, c->height);
461         }
462     }
463
464     if (oc->oformat->flags & AVFMT_RAWPICTURE && !flush) {
465         /* Raw video case - directly store the picture in the packet */
466         AVPacket pkt;
467         av_init_packet(&pkt);
468
469         pkt.flags        |= AV_PKT_FLAG_KEY;
470         pkt.stream_index  = ost->st->index;
471         pkt.data          = (uint8_t *)ost->frame;
472         pkt.size          = sizeof(AVPicture);
473
474         ret = av_interleaved_write_frame(oc, &pkt);
475     } else {
476         AVPacket pkt = { 0 };
477         int got_packet;
478         av_init_packet(&pkt);
479
480         /* encode the image */
481         ost->frame->pts = frame_count;
482         ret = avcodec_encode_video2(c, &pkt, flush ? NULL : ost->frame, &got_packet);
483         if (ret < 0) {
484             fprintf(stderr, "Error encoding video frame: %s\n", av_err2str(ret));
485             exit(1);
486         }
487         /* If size is zero, it means the image was buffered. */
488
489         if (got_packet) {
490             ret = write_frame(oc, &c->time_base, ost->st, &pkt);
491         } else {
492             if (flush)
493                 video_is_eof = 1;
494             ret = 0;
495         }
496     }
497
498     if (ret < 0) {
499         fprintf(stderr, "Error while writing video frame: %s\n", av_err2str(ret));
500         exit(1);
501     }
502     frame_count++;
503 }
504
505 static void close_video(AVFormatContext *oc, OutputStream *ost)
506 {
507     avcodec_close(ost->st->codec);
508     av_frame_free(&ost->frame);
509     av_frame_free(&ost->tmp_frame);
510 }
511
512 /**************************************************************/
513 /* media file output */
514
515 int main(int argc, char **argv)
516 {
517     OutputStream video_st;
518     const char *filename;
519     AVOutputFormat *fmt;
520     AVFormatContext *oc;
521     AVStream *audio_st;
522     AVCodec *audio_codec, *video_codec;
523     double audio_time, video_time;
524     int flush, ret;
525     int have_video = 0;
526
527     /* Initialize libavcodec, and register all codecs and formats. */
528     av_register_all();
529
530     if (argc != 2) {
531         printf("usage: %s output_file\n"
532                "API example program to output a media file with libavformat.\n"
533                "This program generates a synthetic audio and video stream, encodes and\n"
534                "muxes them into a file named output_file.\n"
535                "The output format is automatically guessed according to the file extension.\n"
536                "Raw images can also be output by using '%%d' in the filename.\n"
537                "\n", argv[0]);
538         return 1;
539     }
540
541     filename = argv[1];
542
543     /* allocate the output media context */
544     avformat_alloc_output_context2(&oc, NULL, NULL, filename);
545     if (!oc) {
546         printf("Could not deduce output format from file extension: using MPEG.\n");
547         avformat_alloc_output_context2(&oc, NULL, "mpeg", filename);
548     }
549     if (!oc)
550         return 1;
551
552     fmt = oc->oformat;
553
554     /* Add the audio and video streams using the default format codecs
555      * and initialize the codecs. */
556     audio_st = NULL;
557
558     if (fmt->video_codec != AV_CODEC_ID_NONE) {
559         add_stream(&video_st, oc, &video_codec, fmt->video_codec);
560         have_video = 1;
561     }
562     if (fmt->audio_codec != AV_CODEC_ID_NONE) {
563         OutputStream dummy;
564         audio_st = add_stream(&dummy, oc, &audio_codec, fmt->audio_codec);
565     }
566
567     /* Now that all the parameters are set, we can open the audio and
568      * video codecs and allocate the necessary encode buffers. */
569     if (have_video)
570         open_video(oc, video_codec, &video_st);
571
572     if (audio_st)
573         open_audio(oc, audio_codec, audio_st);
574
575     av_dump_format(oc, 0, filename, 1);
576
577     /* open the output file, if needed */
578     if (!(fmt->flags & AVFMT_NOFILE)) {
579         ret = avio_open(&oc->pb, filename, AVIO_FLAG_WRITE);
580         if (ret < 0) {
581             fprintf(stderr, "Could not open '%s': %s\n", filename,
582                     av_err2str(ret));
583             return 1;
584         }
585     }
586
587     /* Write the stream header, if any. */
588     ret = avformat_write_header(oc, NULL);
589     if (ret < 0) {
590         fprintf(stderr, "Error occurred when opening output file: %s\n",
591                 av_err2str(ret));
592         return 1;
593     }
594
595     flush = 0;
596     while ((have_video && !video_is_eof) || (audio_st && !audio_is_eof)) {
597         /* Compute current audio and video time. */
598         audio_time = (audio_st && !audio_is_eof) ? audio_st->pts.val * av_q2d(audio_st->time_base) : INFINITY;
599         video_time = (have_video && !video_is_eof) ? video_st.st->pts.val * av_q2d(video_st.st->time_base) : INFINITY;
600
601         if (!flush &&
602             (!audio_st || audio_time >= STREAM_DURATION) &&
603             (!have_video || video_time >= STREAM_DURATION)) {
604             flush = 1;
605         }
606
607         /* write interleaved audio and video frames */
608         if (audio_st && !audio_is_eof && audio_time <= video_time) {
609             write_audio_frame(oc, audio_st, flush);
610         } else if (have_video && !video_is_eof && video_time < audio_time) {
611             write_video_frame(oc, &video_st, flush);
612         }
613     }
614
615     /* Write the trailer, if any. The trailer must be written before you
616      * close the CodecContexts open when you wrote the header; otherwise
617      * av_write_trailer() may try to use memory that was freed on
618      * av_codec_close(). */
619     av_write_trailer(oc);
620
621     /* Close each codec. */
622     if (have_video)
623         close_video(oc, &video_st);
624     if (audio_st)
625         close_audio(oc, audio_st);
626
627     if (!(fmt->flags & AVFMT_NOFILE))
628         /* Close the output file. */
629         avio_close(oc->pb);
630
631     /* free the stream */
632     avformat_free_context(oc);
633
634     return 0;
635 }