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