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