]> git.sesse.net Git - ffmpeg/blob - doc/examples/muxing.c
Merge commit '2d09b36c0379fcda8f984bc8ad8816c8326fd7bd'
[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.
28  * The default codecs are used.
29  */
30
31 #include <stdlib.h>
32 #include <stdio.h>
33 #include <string.h>
34 #include <math.h>
35
36 #include <libavutil/mathematics.h>
37 #include <libavformat/avformat.h>
38 #include <libswscale/swscale.h>
39
40 /* 5 seconds stream duration */
41 #define STREAM_DURATION   200.0
42 #define STREAM_FRAME_RATE 25 /* 25 images/s */
43 #define STREAM_NB_FRAMES  ((int)(STREAM_DURATION * STREAM_FRAME_RATE))
44 #define STREAM_PIX_FMT    AV_PIX_FMT_YUV420P /* default pix_fmt */
45
46 static int sws_flags = SWS_BICUBIC;
47
48 /**************************************************************/
49 /* audio output */
50
51 static float t, tincr, tincr2;
52 static int16_t *samples;
53 static int audio_input_frame_size;
54
55 /* Add an output stream. */
56 static AVStream *add_stream(AVFormatContext *oc, AVCodec **codec,
57                             enum AVCodecID codec_id)
58 {
59     AVCodecContext *c;
60     AVStream *st;
61
62     /* find the encoder */
63     *codec = avcodec_find_encoder(codec_id);
64     if (!(*codec)) {
65         fprintf(stderr, "Could not find codec\n");
66         exit(1);
67     }
68
69     st = avformat_new_stream(oc, *codec);
70     if (!st) {
71         fprintf(stderr, "Could not allocate stream\n");
72         exit(1);
73     }
74     st->id = oc->nb_streams-1;
75     c = st->codec;
76
77     switch ((*codec)->type) {
78     case AVMEDIA_TYPE_AUDIO:
79         st->id = 1;
80         c->sample_fmt  = AV_SAMPLE_FMT_S16;
81         c->bit_rate    = 64000;
82         c->sample_rate = 44100;
83         c->channels    = 2;
84         break;
85
86     case AVMEDIA_TYPE_VIDEO:
87         avcodec_get_context_defaults3(c, *codec);
88         c->codec_id = codec_id;
89
90         c->bit_rate = 400000;
91         /* Resolution must be a multiple of two. */
92         c->width    = 352;
93         c->height   = 288;
94         /* timebase: This is the fundamental unit of time (in seconds) in terms
95          * of which frame timestamps are represented. For fixed-fps content,
96          * timebase should be 1/framerate and timestamp increments should be
97          * identical to 1. */
98         c->time_base.den = STREAM_FRAME_RATE;
99         c->time_base.num = 1;
100         c->gop_size      = 12; /* emit one intra frame every twelve frames at most */
101         c->pix_fmt       = STREAM_PIX_FMT;
102         if (c->codec_id == AV_CODEC_ID_MPEG2VIDEO) {
103             /* just for testing, we also add B frames */
104             c->max_b_frames = 2;
105         }
106         if (c->codec_id == AV_CODEC_ID_MPEG1VIDEO) {
107             /* Needed to avoid using macroblocks in which some coeffs overflow.
108              * This does not happen with normal video, it just happens here as
109              * the motion of the chroma plane does not match the luma plane. */
110             c->mb_decision = 2;
111         }
112     break;
113
114     default:
115         break;
116     }
117
118     /* Some formats want stream headers to be separate. */
119     if (oc->oformat->flags & AVFMT_GLOBALHEADER)
120         c->flags |= CODEC_FLAG_GLOBAL_HEADER;
121
122     return st;
123 }
124
125 /**************************************************************/
126 /* audio output */
127
128 static float t, tincr, tincr2;
129 static int16_t *samples;
130 static int audio_input_frame_size;
131
132 static void open_audio(AVFormatContext *oc, AVCodec *codec, AVStream *st)
133 {
134     AVCodecContext *c;
135
136     c = st->codec;
137
138     /* open it */
139     if (avcodec_open2(c, codec, NULL) < 0) {
140         fprintf(stderr, "Could not open audio codec\n");
141         exit(1);
142     }
143
144     /* init signal generator */
145     t     = 0;
146     tincr = 2 * M_PI * 110.0 / c->sample_rate;
147     /* increment frequency by 110 Hz per second */
148     tincr2 = 2 * M_PI * 110.0 / c->sample_rate / c->sample_rate;
149
150     if (c->codec->capabilities & CODEC_CAP_VARIABLE_FRAME_SIZE)
151         audio_input_frame_size = 10000;
152     else
153         audio_input_frame_size = c->frame_size;
154     samples = av_malloc(audio_input_frame_size *
155                         av_get_bytes_per_sample(c->sample_fmt) *
156                         c->channels);
157     if (!samples) {
158         fprintf(stderr, "Could not allocate audio samples buffer\n");
159         exit(1);
160     }
161 }
162
163 /* Prepare a 16 bit dummy audio frame of 'frame_size' samples and
164  * 'nb_channels' channels. */
165 static void get_audio_frame(int16_t *samples, int frame_size, int nb_channels)
166 {
167     int j, i, v;
168     int16_t *q;
169
170     q = samples;
171     for (j = 0; j < frame_size; j++) {
172         v = (int)(sin(t) * 10000);
173         for (i = 0; i < nb_channels; i++)
174             *q++ = v;
175         t     += tincr;
176         tincr += tincr2;
177     }
178 }
179
180 static void write_audio_frame(AVFormatContext *oc, AVStream *st)
181 {
182     AVCodecContext *c;
183     AVPacket pkt = { 0 }; // data and size must be 0;
184     AVFrame *frame = avcodec_alloc_frame();
185     int got_packet, ret;
186
187     av_init_packet(&pkt);
188     c = st->codec;
189
190     get_audio_frame(samples, audio_input_frame_size, c->channels);
191     frame->nb_samples = audio_input_frame_size;
192     avcodec_fill_audio_frame(frame, c->channels, c->sample_fmt,
193                              (uint8_t *)samples,
194                              audio_input_frame_size *
195                              av_get_bytes_per_sample(c->sample_fmt) *
196                              c->channels, 1);
197
198     ret = avcodec_encode_audio2(c, &pkt, frame, &got_packet);
199     if (ret < 0) {
200         fprintf(stderr, "Error encoding audio frame\n");
201         exit(1);
202     }
203
204     if (!got_packet)
205         return;
206
207     pkt.stream_index = st->index;
208
209     /* Write the compressed frame to the media file. */
210     if (av_interleaved_write_frame(oc, &pkt) != 0) {
211         fprintf(stderr, "Error while writing audio frame\n");
212         exit(1);
213     }
214     avcodec_free_frame(&frame);
215 }
216
217 static void close_audio(AVFormatContext *oc, AVStream *st)
218 {
219     avcodec_close(st->codec);
220
221     av_free(samples);
222 }
223
224 /**************************************************************/
225 /* video output */
226
227 static AVFrame *frame;
228 static AVPicture src_picture, dst_picture;
229 static int frame_count;
230
231 static void open_video(AVFormatContext *oc, AVCodec *codec, AVStream *st)
232 {
233     int ret;
234     AVCodecContext *c = st->codec;
235
236     /* open the codec */
237     if (avcodec_open2(c, codec, NULL) < 0) {
238         fprintf(stderr, "Could not open video codec\n");
239         exit(1);
240     }
241
242     /* allocate and init a re-usable frame */
243     frame = avcodec_alloc_frame();
244     if (!frame) {
245         fprintf(stderr, "Could not allocate video frame\n");
246         exit(1);
247     }
248
249     /* Allocate the encoded raw picture. */
250     ret = avpicture_alloc(&dst_picture, c->pix_fmt, c->width, c->height);
251     if (ret < 0) {
252         fprintf(stderr, "Could not allocate picture\n");
253         exit(1);
254     }
255
256     /* If the output format is not YUV420P, then a temporary YUV420P
257      * picture is needed too. It is then converted to the required
258      * output format. */
259     if (c->pix_fmt != AV_PIX_FMT_YUV420P) {
260         ret = avpicture_alloc(&src_picture, AV_PIX_FMT_YUV420P, c->width, c->height);
261         if (ret < 0) {
262             fprintf(stderr, "Could not allocate temporary picture\n");
263             exit(1);
264         }
265     }
266
267     /* copy data and linesize picture pointers to frame */
268     *((AVPicture *)frame) = dst_picture;
269 }
270
271 /* Prepare a dummy image. */
272 static void fill_yuv_image(AVPicture *pict, int frame_index,
273                            int width, int height)
274 {
275     int x, y, i;
276
277     i = frame_index;
278
279     /* Y */
280     for (y = 0; y < height; y++)
281         for (x = 0; x < width; x++)
282             pict->data[0][y * pict->linesize[0] + x] = x + y + i * 3;
283
284     /* Cb and Cr */
285     for (y = 0; y < height / 2; y++) {
286         for (x = 0; x < width / 2; x++) {
287             pict->data[1][y * pict->linesize[1] + x] = 128 + y + i * 2;
288             pict->data[2][y * pict->linesize[2] + x] = 64 + x + i * 5;
289         }
290     }
291 }
292
293 static void write_video_frame(AVFormatContext *oc, AVStream *st)
294 {
295     int ret;
296     static struct SwsContext *sws_ctx;
297     AVCodecContext *c = st->codec;
298
299     if (frame_count >= STREAM_NB_FRAMES) {
300         /* No more frames to compress. The codec has a latency of a few
301          * frames if using B-frames, so we get the last frames by
302          * passing the same picture again. */
303     } else {
304         if (c->pix_fmt != AV_PIX_FMT_YUV420P) {
305             /* as we only generate a YUV420P picture, we must convert it
306              * to the codec pixel format if needed */
307             if (!sws_ctx) {
308                 sws_ctx = sws_getContext(c->width, c->height, AV_PIX_FMT_YUV420P,
309                                          c->width, c->height, c->pix_fmt,
310                                          sws_flags, NULL, NULL, NULL);
311                 if (!sws_ctx) {
312                     fprintf(stderr,
313                             "Could not initialize the conversion context\n");
314                     exit(1);
315                 }
316             }
317             fill_yuv_image(&src_picture, frame_count, c->width, c->height);
318             sws_scale(sws_ctx,
319                       (const uint8_t * const *)src_picture.data, src_picture.linesize,
320                       0, c->height, dst_picture.data, dst_picture.linesize);
321         } else {
322             fill_yuv_image(&dst_picture, frame_count, c->width, c->height);
323         }
324     }
325
326     if (oc->oformat->flags & AVFMT_RAWPICTURE) {
327         /* Raw video case - directly store the picture in the packet */
328         AVPacket pkt;
329         av_init_packet(&pkt);
330
331         pkt.flags        |= AV_PKT_FLAG_KEY;
332         pkt.stream_index  = st->index;
333         pkt.data          = dst_picture.data[0];
334         pkt.size          = sizeof(AVPicture);
335
336         ret = av_interleaved_write_frame(oc, &pkt);
337     } else {
338         /* encode the image */
339         AVPacket pkt;
340         int got_output;
341
342         av_init_packet(&pkt);
343         pkt.data = NULL;    // packet data will be allocated by the encoder
344         pkt.size = 0;
345
346         ret = avcodec_encode_video2(c, &pkt, frame, &got_output);
347         if (ret < 0) {
348             fprintf(stderr, "Error encoding video frame\n");
349             exit(1);
350         }
351
352         /* If size is zero, it means the image was buffered. */
353         if (got_output) {
354             if (c->coded_frame->key_frame)
355                 pkt.flags |= AV_PKT_FLAG_KEY;
356
357             pkt.stream_index = st->index;
358
359             /* Write the compressed frame to the media file. */
360             ret = av_interleaved_write_frame(oc, &pkt);
361         } else {
362             ret = 0;
363         }
364     }
365     if (ret != 0) {
366         fprintf(stderr, "Error while writing video frame\n");
367         exit(1);
368     }
369     frame_count++;
370 }
371
372 static void close_video(AVFormatContext *oc, AVStream *st)
373 {
374     avcodec_close(st->codec);
375     av_free(src_picture.data[0]);
376     av_free(dst_picture.data[0]);
377     av_free(frame);
378 }
379
380 /**************************************************************/
381 /* media file output */
382
383 int main(int argc, char **argv)
384 {
385     const char *filename;
386     AVOutputFormat *fmt;
387     AVFormatContext *oc;
388     AVStream *audio_st, *video_st;
389     AVCodec *audio_codec, *video_codec;
390     double audio_pts, video_pts;
391     int i;
392
393     /* Initialize libavcodec, and register all codecs and formats. */
394     av_register_all();
395
396     if (argc != 2) {
397         printf("usage: %s output_file\n"
398                "API example program to output a media file with libavformat.\n"
399                "This program generates a synthetic audio and video stream, encodes and\n"
400                "muxes them into a file named output_file.\n"
401                "The output format is automatically guessed according to the file extension.\n"
402                "Raw images can also be output by using '%%d' in the filename.\n"
403                "\n", argv[0]);
404         return 1;
405     }
406
407     filename = argv[1];
408
409     /* allocate the output media context */
410     avformat_alloc_output_context2(&oc, NULL, NULL, filename);
411     if (!oc) {
412         printf("Could not deduce output format from file extension: using MPEG.\n");
413         avformat_alloc_output_context2(&oc, NULL, "mpeg", filename);
414     }
415     if (!oc) {
416         return 1;
417     }
418     fmt = oc->oformat;
419
420     /* Add the audio and video streams using the default format codecs
421      * and initialize the codecs. */
422     video_st = NULL;
423     audio_st = NULL;
424
425     if (fmt->video_codec != AV_CODEC_ID_NONE) {
426         video_st = add_stream(oc, &video_codec, fmt->video_codec);
427     }
428     if (fmt->audio_codec != AV_CODEC_ID_NONE) {
429         audio_st = add_stream(oc, &audio_codec, fmt->audio_codec);
430     }
431
432     /* Now that all the parameters are set, we can open the audio and
433      * video codecs and allocate the necessary encode buffers. */
434     if (video_st)
435         open_video(oc, video_codec, video_st);
436     if (audio_st)
437         open_audio(oc, audio_codec, audio_st);
438
439     av_dump_format(oc, 0, filename, 1);
440
441     /* open the output file, if needed */
442     if (!(fmt->flags & AVFMT_NOFILE)) {
443         if (avio_open(&oc->pb, filename, AVIO_FLAG_WRITE) < 0) {
444             fprintf(stderr, "Could not open '%s'\n", filename);
445             return 1;
446         }
447     }
448
449     /* Write the stream header, if any. */
450     if (avformat_write_header(oc, NULL) < 0) {
451         fprintf(stderr, "Error occurred when opening output file\n");
452         return 1;
453     }
454
455     if (frame)
456         frame->pts = 0;
457     for (;;) {
458         /* Compute current audio and video time. */
459         if (audio_st)
460             audio_pts = (double)audio_st->pts.val * audio_st->time_base.num / audio_st->time_base.den;
461         else
462             audio_pts = 0.0;
463
464         if (video_st)
465             video_pts = (double)video_st->pts.val * video_st->time_base.num /
466                         video_st->time_base.den;
467         else
468             video_pts = 0.0;
469
470         if ((!audio_st || audio_pts >= STREAM_DURATION) &&
471             (!video_st || video_pts >= STREAM_DURATION))
472             break;
473
474         /* write interleaved audio and video frames */
475         if (!video_st || (video_st && audio_st && audio_pts < video_pts)) {
476             write_audio_frame(oc, audio_st);
477         } else {
478             write_video_frame(oc, video_st);
479             frame->pts += av_rescale_q(1, video_st->codec->time_base, video_st->time_base);
480         }
481     }
482
483     /* Write the trailer, if any. The trailer must be written before you
484      * close the CodecContexts open when you wrote the header; otherwise
485      * av_write_trailer() may try to use memory that was freed on
486      * av_codec_close(). */
487     av_write_trailer(oc);
488
489     /* Close each codec. */
490     if (video_st)
491         close_video(oc, video_st);
492     if (audio_st)
493         close_audio(oc, audio_st);
494
495     /* Free the streams. */
496     for (i = 0; i < oc->nb_streams; i++) {
497         av_freep(&oc->streams[i]->codec);
498         av_freep(&oc->streams[i]);
499     }
500
501     if (!(fmt->flags & AVFMT_NOFILE))
502         /* Close the output file. */
503         avio_close(oc->pb);
504
505     /* free the stream */
506     av_free(oc);
507
508     return 0;
509 }