FFmpeg  2.1.1
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  if (pkt.stream_index == video_stream_idx) {
62  /* decode video frame */
63  ret = avcodec_decode_video2(video_dec_ctx, frame, got_frame, &pkt);
64  if (ret < 0) {
65  fprintf(stderr, "Error decoding video frame\n");
66  return ret;
67  }
68 
69  if (*got_frame) {
70  printf("video_frame%s n:%d coded_n:%d pts:%s\n",
71  cached ? "(cached)" : "",
73  av_ts2timestr(frame->pts, &video_dec_ctx->time_base));
74 
75  /* copy decoded frame to destination buffer:
76  * this is required since rawvideo expects non aligned data */
78  (const uint8_t **)(frame->data), frame->linesize,
79  video_dec_ctx->pix_fmt, video_dec_ctx->width, video_dec_ctx->height);
80 
81  /* write to rawvideo file */
83  }
84  } else if (pkt.stream_index == audio_stream_idx) {
85  /* decode audio frame */
86  ret = avcodec_decode_audio4(audio_dec_ctx, frame, got_frame, &pkt);
87  if (ret < 0) {
88  fprintf(stderr, "Error decoding audio frame\n");
89  return ret;
90  }
91  /* Some audio decoders decode only part of the packet, and have to be
92  * called again with the remainder of the packet data.
93  * Sample: fate-suite/lossless-audio/luckynight-partial.shn
94  * Also, some decoders might over-read the packet. */
95  decoded = FFMIN(ret, pkt.size);
96 
97  if (*got_frame) {
98  size_t unpadded_linesize = frame->nb_samples * av_get_bytes_per_sample(frame->format);
99  printf("audio_frame%s n:%d nb_samples:%d pts:%s\n",
100  cached ? "(cached)" : "",
101  audio_frame_count++, frame->nb_samples,
103 
104  /* Write the raw audio data samples of the first plane. This works
105  * fine for packed formats (e.g. AV_SAMPLE_FMT_S16). However,
106  * most audio decoders output planar audio, which uses a separate
107  * plane of audio samples for each channel (e.g. AV_SAMPLE_FMT_S16P).
108  * In other words, this code will write only the first audio channel
109  * in these cases.
110  * You should use libswresample or libavfilter to convert the frame
111  * to packed data. */
112  fwrite(frame->extended_data[0], 1, unpadded_linesize, audio_dst_file);
113  }
114  }
115 
116  return decoded;
117 }
118 
119 static int open_codec_context(int *stream_idx,
120  AVFormatContext *fmt_ctx, enum AVMediaType type)
121 {
122  int ret;
123  AVStream *st;
124  AVCodecContext *dec_ctx = NULL;
125  AVCodec *dec = NULL;
126 
127  ret = av_find_best_stream(fmt_ctx, type, -1, -1, NULL, 0);
128  if (ret < 0) {
129  fprintf(stderr, "Could not find %s stream in input file '%s'\n",
131  return ret;
132  } else {
133  *stream_idx = ret;
134  st = fmt_ctx->streams[*stream_idx];
135 
136  /* find decoder for the stream */
137  dec_ctx = st->codec;
138  dec = avcodec_find_decoder(dec_ctx->codec_id);
139  if (!dec) {
140  fprintf(stderr, "Failed to find %s codec\n",
142  return ret;
143  }
144 
145  if ((ret = avcodec_open2(dec_ctx, dec, NULL)) < 0) {
146  fprintf(stderr, "Failed to open %s codec\n",
148  return ret;
149  }
150  }
151 
152  return 0;
153 }
154 
155 static int get_format_from_sample_fmt(const char **fmt,
156  enum AVSampleFormat sample_fmt)
157 {
158  int i;
159  struct sample_fmt_entry {
160  enum AVSampleFormat sample_fmt; const char *fmt_be, *fmt_le;
161  } sample_fmt_entries[] = {
162  { AV_SAMPLE_FMT_U8, "u8", "u8" },
163  { AV_SAMPLE_FMT_S16, "s16be", "s16le" },
164  { AV_SAMPLE_FMT_S32, "s32be", "s32le" },
165  { AV_SAMPLE_FMT_FLT, "f32be", "f32le" },
166  { AV_SAMPLE_FMT_DBL, "f64be", "f64le" },
167  };
168  *fmt = NULL;
169 
170  for (i = 0; i < FF_ARRAY_ELEMS(sample_fmt_entries); i++) {
171  struct sample_fmt_entry *entry = &sample_fmt_entries[i];
172  if (sample_fmt == entry->sample_fmt) {
173  *fmt = AV_NE(entry->fmt_be, entry->fmt_le);
174  return 0;
175  }
176  }
177 
178  fprintf(stderr,
179  "sample format %s is not supported as output format\n",
180  av_get_sample_fmt_name(sample_fmt));
181  return -1;
182 }
183 
184 int main (int argc, char **argv)
185 {
186  int ret = 0, got_frame;
187 
188  if (argc != 4) {
189  fprintf(stderr, "usage: %s input_file video_output_file audio_output_file\n"
190  "API example program to show how to read frames from an input file.\n"
191  "This program reads frames from a file, decodes them, and writes decoded\n"
192  "video frames to a rawvideo file named video_output_file, and decoded\n"
193  "audio frames to a rawaudio file named audio_output_file.\n"
194  "\n", argv[0]);
195  exit(1);
196  }
197  src_filename = argv[1];
198  video_dst_filename = argv[2];
199  audio_dst_filename = argv[3];
200 
201  /* register all formats and codecs */
202  av_register_all();
203 
204  /* open input file, and allocate format context */
205  if (avformat_open_input(&fmt_ctx, src_filename, NULL, NULL) < 0) {
206  fprintf(stderr, "Could not open source file %s\n", src_filename);
207  exit(1);
208  }
209 
210  /* retrieve stream information */
211  if (avformat_find_stream_info(fmt_ctx, NULL) < 0) {
212  fprintf(stderr, "Could not find stream information\n");
213  exit(1);
214  }
215 
217  video_stream = fmt_ctx->streams[video_stream_idx];
218  video_dec_ctx = video_stream->codec;
219 
220  video_dst_file = fopen(video_dst_filename, "wb");
221  if (!video_dst_file) {
222  fprintf(stderr, "Could not open destination file %s\n", video_dst_filename);
223  ret = 1;
224  goto end;
225  }
226 
227  /* allocate image where the decoded image will be put */
229  video_dec_ctx->width, video_dec_ctx->height,
230  video_dec_ctx->pix_fmt, 1);
231  if (ret < 0) {
232  fprintf(stderr, "Could not allocate raw video buffer\n");
233  goto end;
234  }
236  }
237 
241  audio_dst_file = fopen(audio_dst_filename, "wb");
242  if (!audio_dst_file) {
243  fprintf(stderr, "Could not open destination file %s\n", video_dst_filename);
244  ret = 1;
245  goto end;
246  }
247  }
248 
249  /* dump input information to stderr */
250  av_dump_format(fmt_ctx, 0, src_filename, 0);
251 
252  if (!audio_stream && !video_stream) {
253  fprintf(stderr, "Could not find audio or video stream in the input, aborting\n");
254  ret = 1;
255  goto end;
256  }
257 
258  frame = avcodec_alloc_frame();
259  if (!frame) {
260  fprintf(stderr, "Could not allocate frame\n");
261  ret = AVERROR(ENOMEM);
262  goto end;
263  }
264 
265  /* initialize packet, set data to NULL, let the demuxer fill it */
266  av_init_packet(&pkt);
267  pkt.data = NULL;
268  pkt.size = 0;
269 
270  if (video_stream)
271  printf("Demuxing video from file '%s' into '%s'\n", src_filename, video_dst_filename);
272  if (audio_stream)
273  printf("Demuxing audio from file '%s' into '%s'\n", src_filename, audio_dst_filename);
274 
275  /* read frames from the file */
276  while (av_read_frame(fmt_ctx, &pkt) >= 0) {
277  AVPacket orig_pkt = pkt;
278  do {
279  ret = decode_packet(&got_frame, 0);
280  if (ret < 0)
281  break;
282  pkt.data += ret;
283  pkt.size -= ret;
284  } while (pkt.size > 0);
285  av_free_packet(&orig_pkt);
286  }
287 
288  /* flush cached frames */
289  pkt.data = NULL;
290  pkt.size = 0;
291  do {
292  decode_packet(&got_frame, 1);
293  } while (got_frame);
294 
295  printf("Demuxing succeeded.\n");
296 
297  if (video_stream) {
298  printf("Play the output video file with the command:\n"
299  "ffplay -f rawvideo -pix_fmt %s -video_size %dx%d %s\n",
300  av_get_pix_fmt_name(video_dec_ctx->pix_fmt), video_dec_ctx->width, video_dec_ctx->height,
302  }
303 
304  if (audio_stream) {
306  int n_channels = audio_dec_ctx->channels;
307  const char *fmt;
308 
309  if (av_sample_fmt_is_planar(sfmt)) {
310  const char *packed = av_get_sample_fmt_name(sfmt);
311  printf("Warning: the sample format the decoder produced is planar "
312  "(%s). This example will output the first channel only.\n",
313  packed ? packed : "?");
314  sfmt = av_get_packed_sample_fmt(sfmt);
315  n_channels = 1;
316  }
317 
318  if ((ret = get_format_from_sample_fmt(&fmt, sfmt)) < 0)
319  goto end;
320 
321  printf("Play the output audio file with the command:\n"
322  "ffplay -f %s -ac %d -ar %d %s\n",
323  fmt, n_channels, audio_dec_ctx->sample_rate,
325  }
326 
327 end:
328  if (video_dec_ctx)
329  avcodec_close(video_dec_ctx);
330  if (audio_dec_ctx)
332  avformat_close_input(&fmt_ctx);
333  if (video_dst_file)
334  fclose(video_dst_file);
335  if (audio_dst_file)
336  fclose(audio_dst_file);
337  av_free(frame);
339 
340  return ret < 0;
341 }
void av_free_packet(AVPacket *pkt)
Free a packet.
Definition: avpacket.c:279
This structure describes decoded (raw) audio or video data.
Definition: frame.h:96
const char * av_get_sample_fmt_name(enum AVSampleFormat sample_fmt)
Return the name of sample_fmt, or NULL if sample_fmt is not recognized.
Definition: samplefmt.c:47
const char * fmt
Definition: avisynth_c.h:669
#define av_ts2timestr(ts, tb)
Convenience macro, the return value should be used only directly in function arguments but never stan...
Definition: timestamp.h:72
int avformat_open_input(AVFormatContext **ps, const char *filename, AVInputFormat *fmt, AVDictionary **options)
Open an input stream and read the header.
Definition: utils.c:487
int av_image_alloc(uint8_t *pointers[4], int linesizes[4], int w, int h, enum AVPixelFormat pix_fmt, int align)
Allocate an image with size w and h and pixel format pix_fmt, and fill pointers and linesizes accordi...
Definition: imgutils.c:190
AVFrame * avcodec_alloc_frame(void)
Allocate an AVFrame and set its fields to default values.
Definition: utils.c:1071
AVCodecContext * codec
Codec context associated with this stream.
Definition: avformat.h:686
int size
Definition: avcodec.h:1064
uint8_t ** extended_data
pointers to the data planes/channels.
Definition: frame.h:140
const char * av_get_pix_fmt_name(enum AVPixelFormat pix_fmt)
Return the short name for a pixel format, NULL in case pix_fmt is unknown.
Definition: pixdesc.c:1860
enum AVPixelFormat pix_fmt
Pixel format, see AV_PIX_FMT_xxx.
Definition: avcodec.h:1342
static uint8_t * video_dst_data[4]
Definition: demuxing.c:46
AVCodec.
Definition: avcodec.h:2922
unsigned 8 bits
Definition: samplefmt.h:51
AVRational time_base
This is the fundamental unit of time (in seconds) in terms of which frame timestamps are represented...
Definition: avcodec.h:1265
Format I/O context.
Definition: avformat.h:968
enum AVSampleFormat sample_fmt
audio sample format
Definition: avcodec.h:1881
uint8_t
static av_cold int end(AVCodecContext *avctx)
Definition: avrndec.c:67
static int open_codec_context(int *stream_idx, AVFormatContext *fmt_ctx, enum AVMediaType type)
Definition: demuxing.c:119
int64_t pts
Presentation timestamp in time_base units (time when frame should be shown to user).
Definition: frame.h:182
signed 32 bits
Definition: samplefmt.h:53
signed 16 bits
Definition: samplefmt.h:52
static AVFrame * frame
Definition: demuxing.c:51
void av_dump_format(AVFormatContext *ic, int index, const char *url, int is_output)
Definition: utils.c:3585
int av_find_best_stream(AVFormatContext *ic, enum AVMediaType type, int wanted_stream_nb, int related_stream, AVCodec **decoder_ret, int flags)
Find the &quot;best&quot; stream in the file.
Definition: utils.c:3169
int avcodec_close(AVCodecContext *avctx)
Close a given AVCodecContext and free all the data associated with it (but not the AVCodecContext its...
Definition: utils.c:2505
void av_free(void *ptr)
Free a memory block which has been allocated with av_malloc(z)() or av_realloc(). ...
Definition: mem.c:219
int avcodec_decode_video2(AVCodecContext *avctx, AVFrame *picture, int *got_picture_ptr, const AVPacket *avpkt)
Decode the video frame of size avpkt-&gt;size from avpkt-&gt;data into picture.
Definition: utils.c:2029
static FILE * audio_dst_file
Definition: demuxing.c:44
static int video_dst_linesize[4]
Definition: demuxing.c:47
static AVStream * audio_stream
Definition: demuxing.c:39
void av_image_copy(uint8_t *dst_data[4], int dst_linesizes[4], const uint8_t *src_data[4], const int src_linesizes[4], enum AVPixelFormat pix_fmt, int width, int height)
Copy image in src_data to dst_data.
Definition: imgutils.c:257
const char * av_get_media_type_string(enum AVMediaType media_type)
Return a string describing the media_type enum, NULL if media_type is unknown.
Definition: utils.c:70
#define FF_ARRAY_ELEMS(a)
Definition: avcodec.h:929
ret
Definition: avfilter.c:961
int width
picture width / height.
Definition: avcodec.h:1314
AVStream ** streams
Definition: avformat.h:1016
#define FFMIN(a, b)
Definition: avcodec.h:925
int avcodec_decode_audio4(AVCodecContext *avctx, AVFrame *frame, int *got_frame_ptr, const AVPacket *avpkt)
Decode the audio frame of size avpkt-&gt;size from avpkt-&gt;data into frame.
Definition: utils.c:2164
static int audio_frame_count
Definition: demuxing.c:54
Stream structure.
Definition: avformat.h:667
AVCodec * avcodec_find_decoder(enum AVCodecID id)
Find a registered decoder with a matching codec ID.
Definition: utils.c:2607
int format
format of the frame, -1 if unknown or unset Values correspond to enum AVPixelFormat for video frames...
Definition: frame.h:157
AVSampleFormat
Audio Sample Formats.
Definition: samplefmt.h:49
int coded_picture_number
picture number in bitstream order
Definition: frame.h:199
enum AVCodecID codec_id
Definition: avcodec.h:1157
int sample_rate
samples per second
Definition: avcodec.h:1873
static int audio_stream_idx
Definition: demuxing.c:50
main external API structure.
Definition: avcodec.h:1146
static int video_stream_idx
Definition: demuxing.c:50
enum AVSampleFormat av_get_packed_sample_fmt(enum AVSampleFormat sample_fmt)
Get the packed alternative form of the given sample format.
Definition: samplefmt.c:73
static AVFormatContext * fmt_ctx
Definition: demuxing.c:37
static AVCodecContext * audio_dec_ctx
Definition: demuxing.c:38
uint8_t * data
Definition: avcodec.h:1063
AVMediaType
Definition: avutil.h:180
#define AV_NE(be, le)
Definition: avcodec.h:908
int linesize[AV_NUM_DATA_POINTERS]
For video, size in bytes of each picture line.
Definition: frame.h:124
int avcodec_open2(AVCodecContext *avctx, const AVCodec *codec, AVDictionary **options)
Initialize the AVCodecContext to use the given AVCodec.
Definition: utils.c:1157
#define type
int av_read_frame(AVFormatContext *s, AVPacket *pkt)
Return the next frame of a stream.
Definition: utils.c:1432
static const char * audio_dst_filename
Definition: demuxing.c:42
static AVCodecContext * video_dec_ctx
Definition: demuxing.c:38
static const char * video_dst_filename
Definition: demuxing.c:41
static int decode_packet(int *got_frame, int cached)
Definition: demuxing.c:56
static AVStream * video_stream
Definition: demuxing.c:39
static FILE * video_dst_file
Definition: demuxing.c:43
int avformat_find_stream_info(AVFormatContext *ic, AVDictionary **options)
Read packets of a media file to get stream information.
Definition: utils.c:2710
int av_sample_fmt_is_planar(enum AVSampleFormat sample_fmt)
Check if the sample format is planar.
Definition: samplefmt.c:118
void av_init_packet(AVPacket *pkt)
Initialize optional fields of a packet with default values.
Definition: avpacket.c:49
static AVCodecContext * dec_ctx
void avformat_close_input(AVFormatContext **s)
Close an opened input AVFormatContext.
Definition: utils.c:3309
static const char * src_filename
Definition: demuxing.c:40
int channels
number of audio channels
Definition: avcodec.h:1874
static int get_format_from_sample_fmt(const char **fmt, enum AVSampleFormat sample_fmt)
Definition: demuxing.c:155
#define AVERROR(e)
static AVPacket pkt
Definition: demuxing.c:52
int main(int argc, char **argv)
Definition: main.c:22
static int video_frame_count
Definition: demuxing.c:53
int stream_index
Definition: avcodec.h:1065
int av_get_bytes_per_sample(enum AVSampleFormat sample_fmt)
Return number of bytes per sample.
Definition: samplefmt.c:104
This structure stores compressed data.
Definition: avcodec.h:1040
void av_register_all(void)
Initialize libavformat and register all the muxers, demuxers and protocols.
Definition: allformats.c:52
static int video_dst_bufsize
Definition: demuxing.c:48
int nb_samples
number of audio samples (per channel) described by this frame
Definition: frame.h:150
uint8_t * data[AV_NUM_DATA_POINTERS]
pointer to the picture/channel planes.
Definition: frame.h:107