2 * Copyright (c) 2012 Stefano Sabatini
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:
11 * The above copyright notice and this permission notice shall be included in
12 * all copies or substantial portions of the Software.
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
25 * libavformat demuxing API use example.
27 * Show how to use the libavformat and libavcodec API to demux and
28 * decode audio and video data.
29 * @example doc/examples/demuxing.c
32 #include <libavutil/imgutils.h>
33 #include <libavutil/samplefmt.h>
34 #include <libavutil/timestamp.h>
35 #include <libavformat/avformat.h>
37 static AVFormatContext *fmt_ctx = NULL;
38 static AVCodecContext *video_dec_ctx = NULL, *audio_dec_ctx;
39 static AVStream *video_stream = NULL, *audio_stream = NULL;
40 static const char *src_filename = NULL;
41 static const char *video_dst_filename = NULL;
42 static const char *audio_dst_filename = NULL;
43 static FILE *video_dst_file = NULL;
44 static FILE *audio_dst_file = NULL;
46 static uint8_t *video_dst_data[4] = {NULL};
47 static int video_dst_linesize[4];
48 static int video_dst_bufsize;
50 static uint8_t **audio_dst_data = NULL;
51 static int audio_dst_linesize;
52 static int audio_dst_bufsize;
54 static int video_stream_idx = -1, audio_stream_idx = -1;
55 static AVFrame *frame = NULL;
57 static int video_frame_count = 0;
58 static int audio_frame_count = 0;
60 static int decode_packet(int *got_frame, int cached)
64 if (pkt.stream_index == video_stream_idx) {
65 /* decode video frame */
66 ret = avcodec_decode_video2(video_dec_ctx, frame, got_frame, &pkt);
68 fprintf(stderr, "Error decoding video frame\n");
73 printf("video_frame%s n:%d coded_n:%d pts:%s\n",
74 cached ? "(cached)" : "",
75 video_frame_count++, frame->coded_picture_number,
76 av_ts2timestr(frame->pts, &video_dec_ctx->time_base));
78 /* copy decoded frame to destination buffer:
79 * this is required since rawvideo expects non aligned data */
80 av_image_copy(video_dst_data, video_dst_linesize,
81 (const uint8_t **)(frame->data), frame->linesize,
82 video_dec_ctx->pix_fmt, video_dec_ctx->width, video_dec_ctx->height);
84 /* write to rawvideo file */
85 fwrite(video_dst_data[0], 1, video_dst_bufsize, video_dst_file);
87 } else if (pkt.stream_index == audio_stream_idx) {
88 /* decode audio frame */
89 ret = avcodec_decode_audio4(audio_dec_ctx, frame, got_frame, &pkt);
91 fprintf(stderr, "Error decoding audio frame\n");
96 printf("audio_frame%s n:%d nb_samples:%d pts:%s\n",
97 cached ? "(cached)" : "",
98 audio_frame_count++, frame->nb_samples,
99 av_ts2timestr(frame->pts, &audio_dec_ctx->time_base));
101 ret = av_samples_alloc(audio_dst_data, &audio_dst_linesize, frame->channels,
102 frame->nb_samples, frame->format, 1);
104 fprintf(stderr, "Could not allocate audio buffer\n");
105 return AVERROR(ENOMEM);
108 /* TODO: extend return code of the av_samples_* functions so that this call is not needed */
110 av_samples_get_buffer_size(NULL, frame->channels,
111 frame->nb_samples, frame->format, 1);
113 /* copy audio data to destination buffer:
114 * this is required since rawaudio expects non aligned data */
115 av_samples_copy(audio_dst_data, frame->data, 0, 0,
116 frame->nb_samples, frame->channels, frame->format);
118 /* write to rawaudio file */
119 fwrite(audio_dst_data[0], 1, audio_dst_bufsize, audio_dst_file);
120 av_freep(&audio_dst_data[0]);
127 static int open_codec_context(int *stream_idx,
128 AVFormatContext *fmt_ctx, enum AVMediaType type)
132 AVCodecContext *dec_ctx = NULL;
135 ret = av_find_best_stream(fmt_ctx, type, -1, -1, NULL, 0);
137 fprintf(stderr, "Could not find %s stream in input file '%s'\n",
138 av_get_media_type_string(type), src_filename);
142 st = fmt_ctx->streams[*stream_idx];
144 /* find decoder for the stream */
146 dec = avcodec_find_decoder(dec_ctx->codec_id);
148 fprintf(stderr, "Failed to find %s codec\n",
149 av_get_media_type_string(type));
153 if ((ret = avcodec_open2(dec_ctx, dec, NULL)) < 0) {
154 fprintf(stderr, "Failed to open %s codec\n",
155 av_get_media_type_string(type));
163 static int get_format_from_sample_fmt(const char **fmt,
164 enum AVSampleFormat sample_fmt)
167 struct sample_fmt_entry {
168 enum AVSampleFormat sample_fmt; const char *fmt_be, *fmt_le;
169 } sample_fmt_entries[] = {
170 { AV_SAMPLE_FMT_U8, "u8", "u8" },
171 { AV_SAMPLE_FMT_S16, "s16be", "s16le" },
172 { AV_SAMPLE_FMT_S32, "s32be", "s32le" },
173 { AV_SAMPLE_FMT_FLT, "f32be", "f32le" },
174 { AV_SAMPLE_FMT_DBL, "f64be", "f64le" },
178 for (i = 0; i < FF_ARRAY_ELEMS(sample_fmt_entries); i++) {
179 struct sample_fmt_entry *entry = &sample_fmt_entries[i];
180 if (sample_fmt == entry->sample_fmt) {
181 *fmt = AV_NE(entry->fmt_be, entry->fmt_le);
187 "sample format %s is not supported as output format\n",
188 av_get_sample_fmt_name(sample_fmt));
192 int main (int argc, char **argv)
194 int ret = 0, got_frame;
197 fprintf(stderr, "usage: %s input_file video_output_file audio_output_file\n"
198 "API example program to show how to read frames from an input file.\n"
199 "This program reads frames from a file, decodes them, and writes decoded\n"
200 "video frames to a rawvideo file named video_output_file, and decoded\n"
201 "audio frames to a rawaudio file named audio_output_file.\n"
205 src_filename = argv[1];
206 video_dst_filename = argv[2];
207 audio_dst_filename = argv[3];
209 /* register all formats and codecs */
212 /* open input file, and allocated format context */
213 if (avformat_open_input(&fmt_ctx, src_filename, NULL, NULL) < 0) {
214 fprintf(stderr, "Could not open source file %s\n", src_filename);
218 /* retrieve stream information */
219 if (avformat_find_stream_info(fmt_ctx, NULL) < 0) {
220 fprintf(stderr, "Could not find stream information\n");
224 if (open_codec_context(&video_stream_idx, fmt_ctx, AVMEDIA_TYPE_VIDEO) >= 0) {
225 video_stream = fmt_ctx->streams[video_stream_idx];
226 video_dec_ctx = video_stream->codec;
228 video_dst_file = fopen(video_dst_filename, "wb");
229 if (!video_dst_file) {
230 fprintf(stderr, "Could not open destination file %s\n", video_dst_filename);
235 /* allocate image where the decoded image will be put */
236 ret = av_image_alloc(video_dst_data, video_dst_linesize,
237 video_dec_ctx->width, video_dec_ctx->height,
238 video_dec_ctx->pix_fmt, 1);
240 fprintf(stderr, "Could not allocate raw video buffer\n");
243 video_dst_bufsize = ret;
246 /* dump input information to stderr */
247 av_dump_format(fmt_ctx, 0, src_filename, 0);
249 if (open_codec_context(&audio_stream_idx, fmt_ctx, AVMEDIA_TYPE_AUDIO) >= 0) {
252 audio_stream = fmt_ctx->streams[audio_stream_idx];
253 audio_dec_ctx = audio_stream->codec;
254 audio_dst_file = fopen(audio_dst_filename, "wb");
255 if (!audio_dst_file) {
256 fprintf(stderr, "Could not open destination file %s\n", video_dst_filename);
261 nb_planes = av_sample_fmt_is_planar(audio_dec_ctx->sample_fmt) ?
262 audio_dec_ctx->channels : 1;
263 audio_dst_data = av_mallocz(sizeof(uint8_t *) * nb_planes);
264 if (!audio_dst_data) {
265 fprintf(stderr, "Could not allocate audio data buffers\n");
266 ret = AVERROR(ENOMEM);
271 if (!audio_stream && !video_stream) {
272 fprintf(stderr, "Could not find audio or video stream in the input, aborting\n");
277 frame = avcodec_alloc_frame();
279 fprintf(stderr, "Could not allocate frame\n");
280 ret = AVERROR(ENOMEM);
284 /* initialize packet, set data to NULL, let the demuxer fill it */
285 av_init_packet(&pkt);
290 printf("Demuxing video from file '%s' into '%s'\n", src_filename, video_dst_filename);
292 printf("Demuxing video from file '%s' into '%s'\n", src_filename, audio_dst_filename);
294 /* read frames from the file */
295 while (av_read_frame(fmt_ctx, &pkt) >= 0)
296 decode_packet(&got_frame, 0);
298 /* flush cached frames */
302 decode_packet(&got_frame, 1);
305 printf("Demuxing succeeded.\n");
308 printf("Play the output video file with the command:\n"
309 "ffplay -f rawvideo -pix_fmt %s -video_size %dx%d %s\n",
310 av_get_pix_fmt_name(video_dec_ctx->pix_fmt), video_dec_ctx->width, video_dec_ctx->height,
317 if ((ret = get_format_from_sample_fmt(&fmt, audio_dec_ctx->sample_fmt) < 0))
319 printf("Play the output audio file with the command:\n"
320 "ffplay -f %s -ac %d -ar %d %s\n",
321 fmt, audio_dec_ctx->channels, audio_dec_ctx->sample_rate,
327 avcodec_close(video_dec_ctx);
329 avcodec_close(audio_dec_ctx);
330 avformat_close_input(&fmt_ctx);
332 fclose(video_dst_file);
334 fclose(audio_dst_file);
336 av_free(video_dst_data[0]);
337 av_free(audio_dst_data);