]> git.sesse.net Git - ffmpeg/blob - output_example.c
some fixes (still buggy though)
[ffmpeg] / output_example.c
1 /*
2  * Libavformat API example: Output a media file in any supported
3  * libavformat format. The default codecs are used.
4  * 
5  * Copyright (c) 2003 Fabrice Bellard
6  * 
7  * Permission is hereby granted, free of charge, to any person obtaining a copy
8  * of this software and associated documentation files (the "Software"), to deal
9  * in the Software without restriction, including without limitation the rights
10  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11  * copies of the Software, and to permit persons to whom the Software is
12  * furnished to do so, subject to the following conditions:
13  * 
14  * The above copyright notice and this permission notice shall be included in
15  * all copies or substantial portions of the Software.
16  * 
17  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
20  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
23  * THE SOFTWARE.  
24  */
25 #include <stdlib.h>
26 #include <stdio.h>
27 #include <math.h>
28
29 #ifndef M_PI
30 #define M_PI 3.1415926535897931
31 #endif
32
33 #include "avformat.h"
34
35 /* 5 seconds stream duration */
36 #define STREAM_DURATION 5.0
37
38
39 /**************************************************************/
40 /* audio output */
41
42 float t, tincr, tincr2;
43 int16_t *samples;
44 uint8_t *audio_outbuf;
45 int audio_outbuf_size;
46 int audio_input_frame_size;
47
48 /* 
49  * add an audio output stream
50  */
51 AVStream *add_audio_stream(AVFormatContext *oc, int codec_id)
52 {
53     AVCodecContext *c;
54     AVStream *st;
55
56     st = av_new_stream(oc, 1);
57     if (!st) {
58         fprintf(stderr, "Could not alloc stream\n");
59         exit(1);
60     }
61
62     c = &st->codec;
63     c->codec_id = codec_id;
64     c->codec_type = CODEC_TYPE_AUDIO;
65
66     /* put sample parameters */
67     c->bit_rate = 64000;
68     c->sample_rate = 44100;
69     c->channels = 2;
70     return st;
71 }
72
73 void open_audio(AVFormatContext *oc, AVStream *st)
74 {
75     AVCodecContext *c;
76     AVCodec *codec;
77
78     c = &st->codec;
79
80     /* find the audio encoder */
81     codec = avcodec_find_encoder(c->codec_id);
82     if (!codec) {
83         fprintf(stderr, "codec not found\n");
84         exit(1);
85     }
86
87     /* open it */
88     if (avcodec_open(c, codec) < 0) {
89         fprintf(stderr, "could not open codec\n");
90         exit(1);
91     }
92
93     /* init signal generator */
94     t = 0;
95     tincr = 2 * M_PI * 110.0 / c->sample_rate;
96     /* increment frequency by 110 Hz per second */
97     tincr2 = 2 * M_PI * 110.0 / c->sample_rate / c->sample_rate;
98
99     audio_outbuf_size = 10000;
100     audio_outbuf = malloc(audio_outbuf_size);
101
102     /* ugly hack for PCM codecs (will be removed ASAP with new PCM
103        support to compute the input frame size in samples */
104     if (c->frame_size <= 1) {
105         audio_input_frame_size = audio_outbuf_size / c->channels;
106         switch(st->codec.codec_id) {
107         case CODEC_ID_PCM_S16LE:
108         case CODEC_ID_PCM_S16BE:
109         case CODEC_ID_PCM_U16LE:
110         case CODEC_ID_PCM_U16BE:
111             audio_input_frame_size >>= 1;
112             break;
113         default:
114             break;
115         }
116     } else {
117         audio_input_frame_size = c->frame_size;
118     }
119     samples = malloc(audio_input_frame_size * 2 * c->channels);
120 }
121
122 /* prepare a 16 bit dummy audio frame of 'frame_size' samples and
123    'nb_channels' channels */
124 void get_audio_frame(int16_t *samples, int frame_size, int nb_channels)
125 {
126     int j, i, v;
127     int16_t *q;
128
129     q = samples;
130     for(j=0;j<frame_size;j++) {
131         v = (int)(sin(t) * 10000);
132         for(i = 0; i < nb_channels; i++)
133             *q++ = v;
134         t += tincr;
135         tincr += tincr2;
136     }
137 }
138
139 void write_audio_frame(AVFormatContext *oc, AVStream *st)
140 {
141     int out_size;
142     AVCodecContext *c;
143
144
145     c = &st->codec;
146
147     get_audio_frame(samples, audio_input_frame_size, c->channels);
148
149     out_size = avcodec_encode_audio(c, audio_outbuf, audio_outbuf_size, samples);
150
151     /* write the compressed frame in the media file */
152     if (av_write_frame(oc, st->index, audio_outbuf, out_size) != 0) {
153         fprintf(stderr, "Error while writing audio frame\n");
154         exit(1);
155     }
156 }
157
158 void close_audio(AVFormatContext *oc, AVStream *st)
159 {
160     avcodec_close(&st->codec);
161     
162     av_free(samples);
163     av_free(audio_outbuf);
164 }
165
166 /**************************************************************/
167 /* video output */
168
169 AVFrame *picture, *tmp_picture;
170 uint8_t *video_outbuf;
171 int frame_count, video_outbuf_size;
172
173 /* add a video output stream */
174 AVStream *add_video_stream(AVFormatContext *oc, int codec_id)
175 {
176     AVCodecContext *c;
177     AVStream *st;
178
179     st = av_new_stream(oc, 0);
180     if (!st) {
181         fprintf(stderr, "Could not alloc stream\n");
182         exit(1);
183     }
184     
185     c = &st->codec;
186     c->codec_id = codec_id;
187     c->codec_type = CODEC_TYPE_VIDEO;
188
189     /* put sample parameters */
190     c->bit_rate = 400000;
191     /* resolution must be a multiple of two */
192     c->width = 352;  
193     c->height = 288;
194     /* frames per second */
195     c->frame_rate = 25;  
196     c->frame_rate_base= 1;
197     c->gop_size = 12; /* emit one intra frame every twelve frames */
198
199     return st;
200 }
201
202 AVFrame *alloc_picture(int pix_fmt, int width, int height)
203 {
204     AVFrame *picture;
205     uint8_t *picture_buf;
206     int size;
207     
208     picture = avcodec_alloc_frame();
209     if (!picture)
210         return NULL;
211     size = avpicture_get_size(pix_fmt, width, height);
212     picture_buf = malloc(size);
213     if (!picture_buf) {
214         av_free(picture);
215         return NULL;
216     }
217     avpicture_fill((AVPicture *)picture, picture_buf, 
218                    pix_fmt, width, height);
219     return picture;
220 }
221     
222 void open_video(AVFormatContext *oc, AVStream *st)
223 {
224     AVCodec *codec;
225     AVCodecContext *c;
226
227     c = &st->codec;
228
229     /* find the video encoder */
230     codec = avcodec_find_encoder(c->codec_id);
231     if (!codec) {
232         fprintf(stderr, "codec not found\n");
233         exit(1);
234     }
235
236     /* open the codec */
237     if (avcodec_open(c, codec) < 0) {
238         fprintf(stderr, "could not open codec\n");
239         exit(1);
240     }
241
242     video_outbuf = NULL;
243     if (!(oc->oformat->flags & AVFMT_RAWPICTURE)) {
244         /* allocate output buffer */
245         /* XXX: API change will be done */
246         video_outbuf_size = 200000;
247         video_outbuf = malloc(video_outbuf_size);
248     }
249
250     /* allocate the encoded raw picture */
251     picture = alloc_picture(c->pix_fmt, c->width, c->height);
252     if (!picture) {
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     tmp_picture = NULL;
261     if (c->pix_fmt != PIX_FMT_YUV420P) {
262         tmp_picture = alloc_picture(PIX_FMT_YUV420P, c->width, c->height);
263         if (!tmp_picture) {
264             fprintf(stderr, "Could not allocate temporary picture\n");
265             exit(1);
266         }
267     }
268 }
269
270 /* prepare a dummy image */
271 void fill_yuv_image(AVFrame *pict, int frame_index, int width, int height)
272 {
273     int x, y, i;
274
275     i = frame_index;
276
277     /* Y */
278     for(y=0;y<height;y++) {
279         for(x=0;x<width;x++) {
280             pict->data[0][y * pict->linesize[0] + x] = x + y + i * 3;
281         }
282     }
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 void write_video_frame(AVFormatContext *oc, AVStream *st)
294 {
295     int out_size, ret;
296     AVCodecContext *c;
297
298     c = &st->codec;
299     
300     if (c->pix_fmt != PIX_FMT_YUV420P) {
301         /* as we only generate a YUV420P picture, we must convert it
302            to the codec pixel format if needed */
303         fill_yuv_image(tmp_picture, frame_count, c->width, c->height);
304         img_convert((AVPicture *)picture, c->pix_fmt, 
305                     (AVPicture *)tmp_picture, PIX_FMT_YUV420P,
306                     c->width, c->height);
307     } else {
308         fill_yuv_image(picture, frame_count, c->width, c->height);
309     }
310
311     
312     if (oc->oformat->flags & AVFMT_RAWPICTURE) {
313         /* raw video case. The API will change slightly in the near
314            futur for that */
315         ret = av_write_frame(oc, st->index, 
316                        (uint8_t *)picture, sizeof(AVPicture));
317     } else {
318         /* encode the image */
319         out_size = avcodec_encode_video(c, video_outbuf, video_outbuf_size, picture);
320         
321         /* write the compressed frame in the media file */
322         ret = av_write_frame(oc, st->index, video_outbuf, out_size);
323     }
324     if (ret != 0) {
325         fprintf(stderr, "Error while writing video frame\n");
326         exit(1);
327     }
328     frame_count++;
329 }
330
331 void close_video(AVFormatContext *oc, AVStream *st)
332 {
333     avcodec_close(&st->codec);
334     av_free(picture->data[0]);
335     av_free(picture);
336     if (tmp_picture) {
337         av_free(tmp_picture->data[0]);
338         av_free(tmp_picture);
339     }
340     av_free(video_outbuf);
341 }
342
343 /**************************************************************/
344 /* media file output */
345
346 int main(int argc, char **argv)
347 {
348     const char *filename;
349     AVOutputFormat *fmt;
350     AVFormatContext *oc;
351     AVStream *audio_st, *video_st;
352     double audio_pts, video_pts;
353     int i;
354
355     /* initialize libavcodec, and register all codecs and formats */
356     av_register_all();
357     
358     if (argc != 2) {
359         printf("usage: %s output_file\n"
360                "API example program to output a media file with libavformat.\n"
361                "The output format is automatically guessed according to the file extension.\n"
362                "Raw images can also be output by using '%%d' in the filename\n"
363                "\n", argv[0]);
364         exit(1);
365     }
366     
367     filename = argv[1];
368
369     /* auto detect the output format from the name. default is
370        mpeg. */
371     fmt = guess_format(NULL, filename, NULL);
372     if (!fmt) {
373         printf("Could not deduce output format from file extension: using MPEG.\n");
374         fmt = guess_format("mpeg", NULL, NULL);
375     }
376     if (!fmt) {
377         fprintf(stderr, "Could not find suitable output format\n");
378         exit(1);
379     }
380     
381     /* allocate the output media context */
382     oc = av_mallocz(sizeof(AVFormatContext));
383     if (!oc) {
384         fprintf(stderr, "Memory error\n");
385         exit(1);
386     }
387     oc->oformat = fmt;
388     snprintf(oc->filename, sizeof(oc->filename), "%s", filename);
389
390     /* add the audio and video streams using the default format codecs
391        and initialize the codecs */
392     video_st = NULL;
393     audio_st = NULL;
394     if (fmt->video_codec != CODEC_ID_NONE) {
395         video_st = add_video_stream(oc, fmt->video_codec);
396     }
397     if (fmt->audio_codec != CODEC_ID_NONE) {
398         audio_st = add_audio_stream(oc, fmt->audio_codec);
399     }
400
401     /* set the output parameters (must be done even if no
402        parameters). */
403     if (av_set_parameters(oc, NULL) < 0) {
404         fprintf(stderr, "Invalid output format parameters\n");
405         exit(1);
406     }
407
408     dump_format(oc, 0, filename, 1);
409
410     /* now that all the parameters are set, we can open the audio and
411        video codecs and allocate the necessary encode buffers */
412     if (video_st)
413         open_video(oc, video_st);
414     if (audio_st)
415         open_audio(oc, audio_st);
416
417     /* open the output file, if needed */
418     if (!(fmt->flags & AVFMT_NOFILE)) {
419         if (url_fopen(&oc->pb, filename, URL_WRONLY) < 0) {
420             fprintf(stderr, "Could not open '%s'\n", filename);
421             exit(1);
422         }
423     }
424     
425     /* write the stream header, if any */
426     av_write_header(oc);
427     
428     for(;;) {
429         /* compute current audio and video time */
430         if (audio_st)
431             audio_pts = (double)audio_st->pts.val * oc->pts_num / oc->pts_den;
432         else
433             audio_pts = 0.0;
434         
435         if (video_st)
436             video_pts = (double)video_st->pts.val * oc->pts_num / oc->pts_den;
437         else
438             video_pts = 0.0;
439
440         if ((!audio_st || audio_pts >= STREAM_DURATION) && 
441             (!video_st || video_pts >= STREAM_DURATION))
442             break;
443         
444         /* write interleaved audio and video frames */
445         if (!video_st || (video_st && audio_st && audio_pts < video_pts)) {
446             write_audio_frame(oc, audio_st);
447         } else {
448             write_video_frame(oc, video_st);
449         }
450     }
451
452     /* close each codec */
453     if (video_st)
454         close_video(oc, video_st);
455     if (audio_st)
456         close_audio(oc, audio_st);
457
458     /* write the trailer, if any */
459     av_write_trailer(oc);
460     
461     /* free the streams */
462     for(i = 0; i < oc->nb_streams; i++) {
463         av_freep(&oc->streams[i]);
464     }
465
466     if (!(fmt->flags & AVFMT_NOFILE)) {
467         /* close the output file */
468         url_fclose(&oc->pb);
469     }
470
471     /* free the stream */
472     av_free(oc);
473
474     return 0;
475 }