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