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