]> git.sesse.net Git - ffmpeg/blob - doc/examples/demuxing.c
Merge commit '66a1ccd7467ab1913cd8877114c6d4c2588bb12f'
[ffmpeg] / doc / examples / demuxing.c
1 /*
2  * Copyright (c) 2012 Stefano Sabatini
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 demuxing API use example.
26  *
27  * Show how to use the libavformat and libavcodec API to demux and
28  * decode audio and video data.
29  */
30
31 #include <libavutil/imgutils.h>
32 #include <libavutil/samplefmt.h>
33 #include <libavutil/timestamp.h>
34 #include <libavformat/avformat.h>
35
36 static AVFormatContext *fmt_ctx = NULL;
37 static AVCodecContext *video_dec_ctx = NULL, *audio_dec_ctx;
38 static AVStream *video_stream = NULL, *audio_stream = NULL;
39 static const char *src_filename = NULL;
40 static const char *video_dst_filename = NULL;
41 static const char *audio_dst_filename = NULL;
42 static FILE *video_dst_file = NULL;
43 static FILE *audio_dst_file = NULL;
44
45 static uint8_t *video_dst_data[4] = {NULL};
46 static int      video_dst_linesize[4];
47 static int video_dst_bufsize;
48
49 static uint8_t **audio_dst_data = NULL;
50 static int       audio_dst_linesize;
51 static int audio_dst_bufsize;
52
53 static int video_stream_idx = -1, audio_stream_idx = -1;
54 static AVFrame *frame = NULL;
55 static AVPacket pkt;
56 static int video_frame_count = 0;
57 static int audio_frame_count = 0;
58
59 static int decode_packet(int *got_frame, int cached)
60 {
61     int ret = 0;
62
63     if (pkt.stream_index == video_stream_idx) {
64         /* decode video frame */
65         ret = avcodec_decode_video2(video_dec_ctx, frame, got_frame, &pkt);
66         if (ret < 0) {
67             fprintf(stderr, "Error decoding video frame\n");
68             return ret;
69         }
70
71         if (*got_frame) {
72             printf("video_frame%s n:%d coded_n:%d pts:%s\n",
73                    cached ? "(cached)" : "",
74                    video_frame_count++, frame->coded_picture_number,
75                    av_ts2timestr(frame->pts, &video_dec_ctx->time_base));
76
77             /* copy decoded frame to destination buffer:
78              * this is required since rawvideo expects non aligned data */
79             av_image_copy(video_dst_data, video_dst_linesize,
80                           (const uint8_t **)(frame->data), frame->linesize,
81                           video_dec_ctx->pix_fmt, video_dec_ctx->width, video_dec_ctx->height);
82
83             /* write to rawvideo file */
84             fwrite(video_dst_data[0], 1, video_dst_bufsize, video_dst_file);
85         }
86     } else if (pkt.stream_index == audio_stream_idx) {
87         /* decode audio frame */
88         ret = avcodec_decode_audio4(audio_dec_ctx, frame, got_frame, &pkt);
89         if (ret < 0) {
90             fprintf(stderr, "Error decoding audio frame\n");
91             return ret;
92         }
93
94         if (*got_frame) {
95             printf("audio_frame%s n:%d nb_samples:%d pts:%s\n",
96                    cached ? "(cached)" : "",
97                    audio_frame_count++, frame->nb_samples,
98                    av_ts2timestr(frame->pts, &audio_dec_ctx->time_base));
99
100             ret = av_samples_alloc(audio_dst_data, &audio_dst_linesize, frame->channels,
101                                    frame->nb_samples, frame->format, 1);
102             if (ret < 0) {
103                 fprintf(stderr, "Could not allocate audio buffer\n");
104                 return AVERROR(ENOMEM);
105             }
106
107             /* TODO: extend return code of the av_samples_* functions so that this call is not needed */
108             audio_dst_bufsize =
109                 av_samples_get_buffer_size(NULL, frame->channels,
110                                            frame->nb_samples, frame->format, 1);
111
112             /* copy audio data to destination buffer:
113              * this is required since rawaudio expects non aligned data */
114             av_samples_copy(audio_dst_data, frame->data, 0, 0,
115                             frame->nb_samples, frame->channels, frame->format);
116
117             /* write to rawaudio file */
118             fwrite(audio_dst_data[0], 1, audio_dst_bufsize, audio_dst_file);
119             av_freep(&audio_dst_data[0]);
120         }
121     }
122
123     return ret;
124 }
125
126 static int open_codec_context(int *stream_idx,
127                               AVFormatContext *fmt_ctx, enum AVMediaType type)
128 {
129     int ret;
130     AVStream *st;
131     AVCodecContext *dec_ctx = NULL;
132     AVCodec *dec = NULL;
133
134     ret = av_find_best_stream(fmt_ctx, type, -1, -1, NULL, 0);
135     if (ret < 0) {
136         fprintf(stderr, "Could not find %s stream in input file '%s'\n",
137                 av_get_media_type_string(type), src_filename);
138         return ret;
139     } else {
140         *stream_idx = ret;
141         st = fmt_ctx->streams[*stream_idx];
142
143         /* find decoder for the stream */
144         dec_ctx = st->codec;
145         dec = avcodec_find_decoder(dec_ctx->codec_id);
146         if (!dec) {
147             fprintf(stderr, "Failed to find %s codec\n",
148                     av_get_media_type_string(type));
149             return ret;
150         }
151
152         if ((ret = avcodec_open2(dec_ctx, dec, NULL)) < 0) {
153             fprintf(stderr, "Failed to open %s codec\n",
154                     av_get_media_type_string(type));
155             return ret;
156         }
157     }
158
159     return 0;
160 }
161
162 static int get_format_from_sample_fmt(const char **fmt,
163                                       enum AVSampleFormat sample_fmt)
164 {
165     int i;
166     struct sample_fmt_entry {
167         enum AVSampleFormat sample_fmt; const char *fmt_be, *fmt_le;
168     } sample_fmt_entries[] = {
169         { AV_SAMPLE_FMT_U8,  "u8",    "u8"    },
170         { AV_SAMPLE_FMT_S16, "s16be", "s16le" },
171         { AV_SAMPLE_FMT_S32, "s32be", "s32le" },
172         { AV_SAMPLE_FMT_FLT, "f32be", "f32le" },
173         { AV_SAMPLE_FMT_DBL, "f64be", "f64le" },
174     };
175     *fmt = NULL;
176
177     for (i = 0; i < FF_ARRAY_ELEMS(sample_fmt_entries); i++) {
178         struct sample_fmt_entry *entry = &sample_fmt_entries[i];
179         if (sample_fmt == entry->sample_fmt) {
180             *fmt = AV_NE(entry->fmt_be, entry->fmt_le);
181             return 0;
182         }
183     }
184
185     fprintf(stderr,
186             "sample format %s is not supported as output format\n",
187             av_get_sample_fmt_name(sample_fmt));
188     return -1;
189 }
190
191 int main (int argc, char **argv)
192 {
193     int ret = 0, got_frame;
194
195     if (argc != 4) {
196         fprintf(stderr, "usage: %s input_file video_output_file audio_output_file\n"
197                 "API example program to show how to read frames from an input file.\n"
198                 "This program reads frames from a file, decodes them, and writes decoded\n"
199                 "video frames to a rawvideo file named video_output_file, and decoded\n"
200                 "audio frames to a rawaudio file named audio_output_file.\n"
201                 "\n", argv[0]);
202         exit(1);
203     }
204     src_filename = argv[1];
205     video_dst_filename = argv[2];
206     audio_dst_filename = argv[3];
207
208     /* register all formats and codecs */
209     av_register_all();
210
211     /* open input file, and allocated format context */
212     if (avformat_open_input(&fmt_ctx, src_filename, NULL, NULL) < 0) {
213         fprintf(stderr, "Could not open source file %s\n", src_filename);
214         exit(1);
215     }
216
217     /* retrieve stream information */
218     if (avformat_find_stream_info(fmt_ctx, NULL) < 0) {
219         fprintf(stderr, "Could not find stream information\n");
220         exit(1);
221     }
222
223     if (open_codec_context(&video_stream_idx, fmt_ctx, AVMEDIA_TYPE_VIDEO) >= 0) {
224         video_stream = fmt_ctx->streams[video_stream_idx];
225         video_dec_ctx = video_stream->codec;
226
227         video_dst_file = fopen(video_dst_filename, "wb");
228         if (!video_dst_file) {
229             fprintf(stderr, "Could not open destination file %s\n", video_dst_filename);
230             ret = 1;
231             goto end;
232         }
233
234         /* allocate image where the decoded image will be put */
235         ret = av_image_alloc(video_dst_data, video_dst_linesize,
236                              video_dec_ctx->width, video_dec_ctx->height,
237                              video_dec_ctx->pix_fmt, 1);
238         if (ret < 0) {
239             fprintf(stderr, "Could not allocate raw video buffer\n");
240             goto end;
241         }
242         video_dst_bufsize = ret;
243     }
244
245     /* dump input information to stderr */
246     av_dump_format(fmt_ctx, 0, src_filename, 0);
247
248     if (open_codec_context(&audio_stream_idx, fmt_ctx, AVMEDIA_TYPE_AUDIO) >= 0) {
249         int nb_planes;
250
251         audio_stream = fmt_ctx->streams[audio_stream_idx];
252         audio_dec_ctx = audio_stream->codec;
253         audio_dst_file = fopen(audio_dst_filename, "wb");
254         if (!audio_dst_file) {
255             fprintf(stderr, "Could not open destination file %s\n", video_dst_filename);
256             ret = 1;
257             goto end;
258         }
259
260         nb_planes = av_sample_fmt_is_planar(audio_dec_ctx->sample_fmt) ?
261             audio_dec_ctx->channels : 1;
262         audio_dst_data = av_mallocz(sizeof(uint8_t *) * nb_planes);
263         if (!audio_dst_data) {
264             fprintf(stderr, "Could not allocate audio data buffers\n");
265             ret = AVERROR(ENOMEM);
266             goto end;
267         }
268     }
269
270     if (!audio_stream && !video_stream) {
271         fprintf(stderr, "Could not find audio or video stream in the input, aborting\n");
272         ret = 1;
273         goto end;
274     }
275
276     frame = avcodec_alloc_frame();
277     if (!frame) {
278         fprintf(stderr, "Could not allocate frame\n");
279         ret = AVERROR(ENOMEM);
280         goto end;
281     }
282
283     /* initialize packet, set data to NULL, let the demuxer fill it */
284     av_init_packet(&pkt);
285     pkt.data = NULL;
286     pkt.size = 0;
287
288     if (video_stream)
289         printf("Demuxing video from file '%s' into '%s'\n", src_filename, video_dst_filename);
290     if (audio_stream)
291         printf("Demuxing video from file '%s' into '%s'\n", src_filename, audio_dst_filename);
292
293     /* read frames from the file */
294     while (av_read_frame(fmt_ctx, &pkt) >= 0)
295         decode_packet(&got_frame, 0);
296
297     /* flush cached frames */
298     pkt.data = NULL;
299     pkt.size = 0;
300     do {
301         decode_packet(&got_frame, 1);
302     } while (got_frame);
303
304     printf("Demuxing succeeded.\n");
305
306     if (video_stream) {
307         printf("Play the output video file with the command:\n"
308                "ffplay -f rawvideo -pix_fmt %s -video_size %dx%d %s\n",
309                av_get_pix_fmt_name(video_dec_ctx->pix_fmt), video_dec_ctx->width, video_dec_ctx->height,
310                video_dst_filename);
311     }
312
313     if (audio_stream) {
314         const char *fmt;
315
316         if ((ret = get_format_from_sample_fmt(&fmt, audio_dec_ctx->sample_fmt) < 0))
317             goto end;
318         printf("Play the output audio file with the command:\n"
319                "ffplay -f %s -ac %d -ar %d %s\n",
320                fmt, audio_dec_ctx->channels, audio_dec_ctx->sample_rate,
321                audio_dst_filename);
322     }
323
324 end:
325     if (video_dec_ctx)
326         avcodec_close(video_dec_ctx);
327     if (audio_dec_ctx)
328         avcodec_close(audio_dec_ctx);
329     avformat_close_input(&fmt_ctx);
330     if (video_dst_file)
331         fclose(video_dst_file);
332     if (audio_dst_file)
333         fclose(audio_dst_file);
334     av_free(frame);
335     av_free(video_dst_data[0]);
336     av_free(audio_dst_data);
337
338     return ret < 0;
339 }