FFmpeg
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros Groups Pages
demuxing.c
Go to the documentation of this file.
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  * @example doc/examples/demuxing.c
30  */
31 
32 #include <libavutil/imgutils.h>
33 #include <libavutil/samplefmt.h>
34 #include <libavutil/timestamp.h>
35 #include <libavformat/avformat.h>
36 
37 static AVFormatContext *fmt_ctx = NULL;
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;
45 
46 static uint8_t *video_dst_data[4] = {NULL};
47 static int video_dst_linesize[4];
48 static int video_dst_bufsize;
49 
50 static int video_stream_idx = -1, audio_stream_idx = -1;
51 static AVFrame *frame = NULL;
52 static AVPacket pkt;
53 static int video_frame_count = 0;
54 static int audio_frame_count = 0;
55 
56 static int decode_packet(int *got_frame, int cached)
57 {
58  int ret = 0;
59  int decoded = pkt.size;
60 
61  *got_frame = 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)" : "",
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 */
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 */
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  /* Some audio decoders decode only part of the packet, and have to be
94  * called again with the remainder of the packet data.
95  * Sample: fate-suite/lossless-audio/luckynight-partial.shn
96  * Also, some decoders might over-read the packet. */
97  decoded = FFMIN(ret, pkt.size);
98 
99  if (*got_frame) {
100  size_t unpadded_linesize = frame->nb_samples * av_get_bytes_per_sample(frame->format);
101  printf("audio_frame%s n:%d nb_samples:%d pts:%s\n",
102  cached ? "(cached)" : "",
103  audio_frame_count++, frame->nb_samples,
105 
106  /* Write the raw audio data samples of the first plane. This works
107  * fine for packed formats (e.g. AV_SAMPLE_FMT_S16). However,
108  * most audio decoders output planar audio, which uses a separate
109  * plane of audio samples for each channel (e.g. AV_SAMPLE_FMT_S16P).
110  * In other words, this code will write only the first audio channel
111  * in these cases.
112  * You should use libswresample or libavfilter to convert the frame
113  * to packed data. */
114  fwrite(frame->extended_data[0], 1, unpadded_linesize, audio_dst_file);
115  }
116  }
117 
118  return decoded;
119 }
120 
121 static int open_codec_context(int *stream_idx,
122  AVFormatContext *fmt_ctx, enum AVMediaType type)
123 {
124  int ret;
125  AVStream *st;
126  AVCodecContext *dec_ctx = NULL;
127  AVCodec *dec = NULL;
128 
129  ret = av_find_best_stream(fmt_ctx, type, -1, -1, NULL, 0);
130  if (ret < 0) {
131  fprintf(stderr, "Could not find %s stream in input file '%s'\n",
133  return ret;
134  } else {
135  *stream_idx = ret;
136  st = fmt_ctx->streams[*stream_idx];
137 
138  /* find decoder for the stream */
139  dec_ctx = st->codec;
140  dec = avcodec_find_decoder(dec_ctx->codec_id);
141  if (!dec) {
142  fprintf(stderr, "Failed to find %s codec\n",
144  return ret;
145  }
146 
147  if ((ret = avcodec_open2(dec_ctx, dec, NULL)) < 0) {
148  fprintf(stderr, "Failed to open %s codec\n",
150  return ret;
151  }
152  }
153 
154  return 0;
155 }
156 
157 static int get_format_from_sample_fmt(const char **fmt,
158  enum AVSampleFormat sample_fmt)
159 {
160  int i;
161  struct sample_fmt_entry {
162  enum AVSampleFormat sample_fmt; const char *fmt_be, *fmt_le;
163  } sample_fmt_entries[] = {
164  { AV_SAMPLE_FMT_U8, "u8", "u8" },
165  { AV_SAMPLE_FMT_S16, "s16be", "s16le" },
166  { AV_SAMPLE_FMT_S32, "s32be", "s32le" },
167  { AV_SAMPLE_FMT_FLT, "f32be", "f32le" },
168  { AV_SAMPLE_FMT_DBL, "f64be", "f64le" },
169  };
170  *fmt = NULL;
171 
172  for (i = 0; i < FF_ARRAY_ELEMS(sample_fmt_entries); i++) {
173  struct sample_fmt_entry *entry = &sample_fmt_entries[i];
174  if (sample_fmt == entry->sample_fmt) {
175  *fmt = AV_NE(entry->fmt_be, entry->fmt_le);
176  return 0;
177  }
178  }
179 
180  fprintf(stderr,
181  "sample format %s is not supported as output format\n",
182  av_get_sample_fmt_name(sample_fmt));
183  return -1;
184 }
185 
186 int main (int argc, char **argv)
187 {
188  int ret = 0, got_frame;
189 
190  if (argc != 4) {
191  fprintf(stderr, "usage: %s input_file video_output_file audio_output_file\n"
192  "API example program to show how to read frames from an input file.\n"
193  "This program reads frames from a file, decodes them, and writes decoded\n"
194  "video frames to a rawvideo file named video_output_file, and decoded\n"
195  "audio frames to a rawaudio file named audio_output_file.\n"
196  "\n", argv[0]);
197  exit(1);
198  }
199  src_filename = argv[1];
200  video_dst_filename = argv[2];
201  audio_dst_filename = argv[3];
202 
203  /* register all formats and codecs */
204  av_register_all();
205 
206  /* open input file, and allocate format context */
207  if (avformat_open_input(&fmt_ctx, src_filename, NULL, NULL) < 0) {
208  fprintf(stderr, "Could not open source file %s\n", src_filename);
209  exit(1);
210  }
211 
212  /* retrieve stream information */
213  if (avformat_find_stream_info(fmt_ctx, NULL) < 0) {
214  fprintf(stderr, "Could not find stream information\n");
215  exit(1);
216  }
217 
219  video_stream = fmt_ctx->streams[video_stream_idx];
220  video_dec_ctx = video_stream->codec;
221 
222  video_dst_file = fopen(video_dst_filename, "wb");
223  if (!video_dst_file) {
224  fprintf(stderr, "Could not open destination file %s\n", video_dst_filename);
225  ret = 1;
226  goto end;
227  }
228 
229  /* allocate image where the decoded image will be put */
231  video_dec_ctx->width, video_dec_ctx->height,
232  video_dec_ctx->pix_fmt, 1);
233  if (ret < 0) {
234  fprintf(stderr, "Could not allocate raw video buffer\n");
235  goto end;
236  }
238  }
239 
243  audio_dst_file = fopen(audio_dst_filename, "wb");
244  if (!audio_dst_file) {
245  fprintf(stderr, "Could not open destination file %s\n", video_dst_filename);
246  ret = 1;
247  goto end;
248  }
249  }
250 
251  /* dump input information to stderr */
252  av_dump_format(fmt_ctx, 0, src_filename, 0);
253 
254  if (!audio_stream && !video_stream) {
255  fprintf(stderr, "Could not find audio or video stream in the input, aborting\n");
256  ret = 1;
257  goto end;
258  }
259 
260  frame = avcodec_alloc_frame();
261  if (!frame) {
262  fprintf(stderr, "Could not allocate frame\n");
263  ret = AVERROR(ENOMEM);
264  goto end;
265  }
266 
267  /* initialize packet, set data to NULL, let the demuxer fill it */
268  av_init_packet(&pkt);
269  pkt.data = NULL;
270  pkt.size = 0;
271 
272  if (video_stream)
273  printf("Demuxing video from file '%s' into '%s'\n", src_filename, video_dst_filename);
274  if (audio_stream)
275  printf("Demuxing audio from file '%s' into '%s'\n", src_filename, audio_dst_filename);
276 
277  /* read frames from the file */
278  while (av_read_frame(fmt_ctx, &pkt) >= 0) {
279  AVPacket orig_pkt = pkt;
280  do {
281  ret = decode_packet(&got_frame, 0);
282  if (ret < 0)
283  break;
284  pkt.data += ret;
285  pkt.size -= ret;
286  } while (pkt.size > 0);
287  av_free_packet(&orig_pkt);
288  }
289 
290  /* flush cached frames */
291  pkt.data = NULL;
292  pkt.size = 0;
293  do {
294  decode_packet(&got_frame, 1);
295  } while (got_frame);
296 
297  printf("Demuxing succeeded.\n");
298 
299  if (video_stream) {
300  printf("Play the output video file with the command:\n"
301  "ffplay -f rawvideo -pix_fmt %s -video_size %dx%d %s\n",
302  av_get_pix_fmt_name(video_dec_ctx->pix_fmt), video_dec_ctx->width, video_dec_ctx->height,
304  }
305 
306  if (audio_stream) {
308  int n_channels = audio_dec_ctx->channels;
309  const char *fmt;
310 
311  if (av_sample_fmt_is_planar(sfmt)) {
312  const char *packed = av_get_sample_fmt_name(sfmt);
313  printf("Warning: the sample format the decoder produced is planar "
314  "(%s). This example will output the first channel only.\n",
315  packed ? packed : "?");
316  sfmt = av_get_packed_sample_fmt(sfmt);
317  n_channels = 1;
318  }
319 
320  if ((ret = get_format_from_sample_fmt(&fmt, sfmt)) < 0)
321  goto end;
322 
323  printf("Play the output audio file with the command:\n"
324  "ffplay -f %s -ac %d -ar %d %s\n",
325  fmt, n_channels, audio_dec_ctx->sample_rate,
327  }
328 
329 end:
330  if (video_dec_ctx)
331  avcodec_close(video_dec_ctx);
332  if (audio_dec_ctx)
334  avformat_close_input(&fmt_ctx);
335  if (video_dst_file)
336  fclose(video_dst_file);
337  if (audio_dst_file)
338  fclose(audio_dst_file);
339  av_free(frame);
341 
342  return ret < 0;
343 }