]> git.sesse.net Git - ffmpeg/blob - doc/examples/muxing.c
Merge commit 'f2f2e7627f0c878d13275af5d166ec5932665e28'
[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/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>
43
44 static int audio_is_eof, video_is_eof;
45
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 */
49
50 static int sws_flags = SWS_BICUBIC;
51
52 static void log_packet(const AVFormatContext *fmt_ctx, const AVPacket *pkt)
53 {
54     AVRational *time_base = &fmt_ctx->streams[pkt->stream_index]->time_base;
55
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),
60            pkt->stream_index);
61 }
62
63 static int write_frame(AVFormatContext *fmt_ctx, const AVRational *time_base, AVStream *st, AVPacket *pkt)
64 {
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;
68
69     /* Write the compressed frame to the media file. */
70     log_packet(fmt_ctx, pkt);
71     return av_interleaved_write_frame(fmt_ctx, pkt);
72 }
73
74 /* Add an output stream. */
75 static AVStream *add_stream(AVFormatContext *oc, AVCodec **codec,
76                             enum AVCodecID codec_id)
77 {
78     AVCodecContext *c;
79     AVStream *st;
80
81     /* find the encoder */
82     *codec = avcodec_find_encoder(codec_id);
83     if (!(*codec)) {
84         fprintf(stderr, "Could not find encoder for '%s'\n",
85                 avcodec_get_name(codec_id));
86         exit(1);
87     }
88
89     st = avformat_new_stream(oc, *codec);
90     if (!st) {
91         fprintf(stderr, "Could not allocate stream\n");
92         exit(1);
93     }
94     st->id = oc->nb_streams-1;
95     c = st->codec;
96
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;
101         c->bit_rate    = 64000;
102         c->sample_rate = 44100;
103         c->channels    = 2;
104         break;
105
106     case AVMEDIA_TYPE_VIDEO:
107         c->codec_id = codec_id;
108
109         c->bit_rate = 400000;
110         /* Resolution must be a multiple of two. */
111         c->width    = 352;
112         c->height   = 288;
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
116          * identical to 1. */
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 */
123             c->max_b_frames = 2;
124         }
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. */
129             c->mb_decision = 2;
130         }
131     break;
132
133     default:
134         break;
135     }
136
137     /* Some formats want stream headers to be separate. */
138     if (oc->oformat->flags & AVFMT_GLOBALHEADER)
139         c->flags |= CODEC_FLAG_GLOBAL_HEADER;
140
141     return st;
142 }
143
144 /**************************************************************/
145 /* audio output */
146
147 static float t, tincr, tincr2;
148
149 AVFrame *audio_frame;
150 static uint8_t **src_samples_data;
151 static int       src_samples_linesize;
152 static int       src_nb_samples;
153
154 static int max_dst_nb_samples;
155 uint8_t **dst_samples_data;
156 int       dst_samples_linesize;
157 int       dst_samples_size;
158 int samples_count;
159
160 struct SwrContext *swr_ctx = NULL;
161
162 static void open_audio(AVFormatContext *oc, AVCodec *codec, AVStream *st)
163 {
164     AVCodecContext *c;
165     int ret;
166
167     c = st->codec;
168
169     /* allocate and init a re-usable frame */
170     audio_frame = av_frame_alloc();
171     if (!audio_frame) {
172         fprintf(stderr, "Could not allocate audio frame\n");
173         exit(1);
174     }
175
176     /* open it */
177     ret = avcodec_open2(c, codec, NULL);
178     if (ret < 0) {
179         fprintf(stderr, "Could not open audio codec: %s\n", av_err2str(ret));
180         exit(1);
181     }
182
183     /* init signal generator */
184     t     = 0;
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;
188
189     src_nb_samples = c->codec->capabilities & CODEC_CAP_VARIABLE_FRAME_SIZE ?
190         10000 : c->frame_size;
191
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);
194     if (ret < 0) {
195         fprintf(stderr, "Could not allocate source samples\n");
196         exit(1);
197     }
198
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;
203
204     /* create resampler context */
205     if (c->sample_fmt != AV_SAMPLE_FMT_S16) {
206         swr_ctx = swr_alloc();
207         if (!swr_ctx) {
208             fprintf(stderr, "Could not allocate resampler context\n");
209             exit(1);
210         }
211
212         /* set options */
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);
219
220         /* initialize the resampling context */
221         if ((ret = swr_init(swr_ctx)) < 0) {
222             fprintf(stderr, "Failed to initialize the resampling context\n");
223             exit(1);
224         }
225
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);
228         if (ret < 0) {
229             fprintf(stderr, "Could not allocate destination samples\n");
230             exit(1);
231         }
232     } else {
233         dst_samples_data = src_samples_data;
234     }
235     dst_samples_size = av_samples_get_buffer_size(NULL, c->channels, max_dst_nb_samples,
236                                                   c->sample_fmt, 0);
237 }
238
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)
242 {
243     int j, i, v;
244     int16_t *q;
245
246     q = samples;
247     for (j = 0; j < frame_size; j++) {
248         v = (int)(sin(t) * 10000);
249         for (i = 0; i < nb_channels; i++)
250             *q++ = v;
251         t     += tincr;
252         tincr += tincr2;
253     }
254 }
255
256 static void write_audio_frame(AVFormatContext *oc, AVStream *st, int flush)
257 {
258     AVCodecContext *c;
259     AVPacket pkt = { 0 }; // data and size must be 0;
260     int got_packet, ret, dst_nb_samples;
261
262     av_init_packet(&pkt);
263     c = st->codec;
264
265     if (!flush) {
266         get_audio_frame((int16_t *)src_samples_data[0], src_nb_samples, c->channels);
267
268         /* convert samples from native format to destination codec format, using the resampler */
269         if (swr_ctx) {
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);
277                 if (ret < 0)
278                     exit(1);
279                 max_dst_nb_samples = dst_nb_samples;
280                 dst_samples_size = av_samples_get_buffer_size(NULL, c->channels, dst_nb_samples,
281                                                               c->sample_fmt, 0);
282             }
283
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);
288             if (ret < 0) {
289                 fprintf(stderr, "Error while converting\n");
290                 exit(1);
291             }
292         } else {
293             dst_nb_samples = src_nb_samples;
294         }
295
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;
301     }
302
303     ret = avcodec_encode_audio2(c, &pkt, flush ? NULL : audio_frame, &got_packet);
304     if (ret < 0) {
305         fprintf(stderr, "Error encoding audio frame: %s\n", av_err2str(ret));
306         exit(1);
307     }
308
309     if (!got_packet) {
310         if (flush)
311             audio_is_eof = 1;
312         return;
313     }
314
315     ret = write_frame(oc, &c->time_base, st, &pkt);
316     if (ret < 0) {
317         fprintf(stderr, "Error while writing audio frame: %s\n",
318                 av_err2str(ret));
319         exit(1);
320     }
321 }
322
323 static void close_audio(AVFormatContext *oc, AVStream *st)
324 {
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);
329     }
330     av_free(src_samples_data[0]);
331     av_free(src_samples_data);
332     av_frame_free(&audio_frame);
333 }
334
335 /**************************************************************/
336 /* video output */
337
338 static AVFrame *frame;
339 static AVPicture src_picture, dst_picture;
340 static int frame_count;
341
342 static void open_video(AVFormatContext *oc, AVCodec *codec, AVStream *st)
343 {
344     int ret;
345     AVCodecContext *c = st->codec;
346
347     /* open the codec */
348     ret = avcodec_open2(c, codec, NULL);
349     if (ret < 0) {
350         fprintf(stderr, "Could not open video codec: %s\n", av_err2str(ret));
351         exit(1);
352     }
353
354     /* allocate and init a re-usable frame */
355     frame = av_frame_alloc();
356     if (!frame) {
357         fprintf(stderr, "Could not allocate video frame\n");
358         exit(1);
359     }
360     frame->format = c->pix_fmt;
361     frame->width = c->width;
362     frame->height = c->height;
363
364     /* Allocate the encoded raw picture. */
365     ret = avpicture_alloc(&dst_picture, c->pix_fmt, c->width, c->height);
366     if (ret < 0) {
367         fprintf(stderr, "Could not allocate picture: %s\n", av_err2str(ret));
368         exit(1);
369     }
370
371     /* If the output format is not YUV420P, then a temporary YUV420P
372      * picture is needed too. It is then converted to the required
373      * output format. */
374     if (c->pix_fmt != AV_PIX_FMT_YUV420P) {
375         ret = avpicture_alloc(&src_picture, AV_PIX_FMT_YUV420P, c->width, c->height);
376         if (ret < 0) {
377             fprintf(stderr, "Could not allocate temporary picture: %s\n",
378                     av_err2str(ret));
379             exit(1);
380         }
381     }
382
383     /* copy data and linesize picture pointers to frame */
384     *((AVPicture *)frame) = dst_picture;
385 }
386
387 /* Prepare a dummy image. */
388 static void fill_yuv_image(AVPicture *pict, int frame_index,
389                            int width, int height)
390 {
391     int x, y, i;
392
393     i = frame_index;
394
395     /* Y */
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;
399
400     /* Cb and Cr */
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;
405         }
406     }
407 }
408
409 static void write_video_frame(AVFormatContext *oc, AVStream *st, int flush)
410 {
411     int ret;
412     static struct SwsContext *sws_ctx;
413     AVCodecContext *c = st->codec;
414
415     if (!flush) {
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 */
419             if (!sws_ctx) {
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);
423                 if (!sws_ctx) {
424                     fprintf(stderr,
425                             "Could not initialize the conversion context\n");
426                     exit(1);
427                 }
428             }
429             fill_yuv_image(&src_picture, frame_count, c->width, c->height);
430             sws_scale(sws_ctx,
431                       (const uint8_t * const *)src_picture.data, src_picture.linesize,
432                       0, c->height, dst_picture.data, dst_picture.linesize);
433         } else {
434             fill_yuv_image(&dst_picture, frame_count, c->width, c->height);
435         }
436     }
437
438     if (oc->oformat->flags & AVFMT_RAWPICTURE && !flush) {
439         /* Raw video case - directly store the picture in the packet */
440         AVPacket pkt;
441         av_init_packet(&pkt);
442
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);
447
448         ret = av_interleaved_write_frame(oc, &pkt);
449     } else {
450         AVPacket pkt = { 0 };
451         int got_packet;
452         av_init_packet(&pkt);
453
454         /* encode the image */
455         frame->pts = frame_count;
456         ret = avcodec_encode_video2(c, &pkt, flush ? NULL : frame, &got_packet);
457         if (ret < 0) {
458             fprintf(stderr, "Error encoding video frame: %s\n", av_err2str(ret));
459             exit(1);
460         }
461         /* If size is zero, it means the image was buffered. */
462
463         if (got_packet) {
464             ret = write_frame(oc, &c->time_base, st, &pkt);
465         } else {
466             if (flush)
467                 video_is_eof = 1;
468             ret = 0;
469         }
470     }
471
472     if (ret < 0) {
473         fprintf(stderr, "Error while writing video frame: %s\n", av_err2str(ret));
474         exit(1);
475     }
476     frame_count++;
477 }
478
479 static void close_video(AVFormatContext *oc, AVStream *st)
480 {
481     avcodec_close(st->codec);
482     av_free(src_picture.data[0]);
483     av_free(dst_picture.data[0]);
484     av_frame_free(&frame);
485 }
486
487 /**************************************************************/
488 /* media file output */
489
490 int main(int argc, char **argv)
491 {
492     const char *filename;
493     AVOutputFormat *fmt;
494     AVFormatContext *oc;
495     AVStream *audio_st, *video_st;
496     AVCodec *audio_codec, *video_codec;
497     double audio_time, video_time;
498     int flush, ret;
499
500     /* Initialize libavcodec, and register all codecs and formats. */
501     av_register_all();
502
503     if (argc != 2) {
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"
510                "\n", argv[0]);
511         return 1;
512     }
513
514     filename = argv[1];
515
516     /* allocate the output media context */
517     avformat_alloc_output_context2(&oc, NULL, NULL, filename);
518     if (!oc) {
519         printf("Could not deduce output format from file extension: using MPEG.\n");
520         avformat_alloc_output_context2(&oc, NULL, "mpeg", filename);
521     }
522     if (!oc)
523         return 1;
524
525     fmt = oc->oformat;
526
527     /* Add the audio and video streams using the default format codecs
528      * and initialize the codecs. */
529     video_st = NULL;
530     audio_st = NULL;
531
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);
536
537     /* Now that all the parameters are set, we can open the audio and
538      * video codecs and allocate the necessary encode buffers. */
539     if (video_st)
540         open_video(oc, video_codec, video_st);
541     if (audio_st)
542         open_audio(oc, audio_codec, audio_st);
543
544     av_dump_format(oc, 0, filename, 1);
545
546     /* open the output file, if needed */
547     if (!(fmt->flags & AVFMT_NOFILE)) {
548         ret = avio_open(&oc->pb, filename, AVIO_FLAG_WRITE);
549         if (ret < 0) {
550             fprintf(stderr, "Could not open '%s': %s\n", filename,
551                     av_err2str(ret));
552             return 1;
553         }
554     }
555
556     /* Write the stream header, if any. */
557     ret = avformat_write_header(oc, NULL);
558     if (ret < 0) {
559         fprintf(stderr, "Error occurred when opening output file: %s\n",
560                 av_err2str(ret));
561         return 1;
562     }
563
564     flush = 0;
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;
569
570         if (!flush &&
571             (!audio_st || audio_time >= STREAM_DURATION) &&
572             (!video_st || video_time >= STREAM_DURATION)) {
573             flush = 1;
574         }
575
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);
581         }
582     }
583
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);
589
590     /* Close each codec. */
591     if (video_st)
592         close_video(oc, video_st);
593     if (audio_st)
594         close_audio(oc, audio_st);
595
596     if (!(fmt->flags & AVFMT_NOFILE))
597         /* Close the output file. */
598         avio_close(oc->pb);
599
600     /* free the stream */
601     avformat_free_context(oc);
602
603     return 0;
604 }