FFmpeg
decode_video.c
Go to the documentation of this file.
1 /*
2  * Copyright (c) 2001 Fabrice Bellard
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  * video decoding with libavcodec API example
26  *
27  * @example decode_video.c
28  */
29 
30 #include <stdio.h>
31 #include <stdlib.h>
32 #include <string.h>
33 
34 #include <libavcodec/avcodec.h>
35 
36 #define INBUF_SIZE 4096
37 
38 static void pgm_save(unsigned char *buf, int wrap, int xsize, int ysize,
39  char *filename)
40 {
41  FILE *f;
42  int i;
43 
44  f = fopen(filename,"w");
45  fprintf(f, "P5\n%d %d\n%d\n", xsize, ysize, 255);
46  for (i = 0; i < ysize; i++)
47  fwrite(buf + i * wrap, 1, xsize, f);
48  fclose(f);
49 }
50 
52  const char *filename)
53 {
54  char buf[1024];
55  int ret;
56 
57  ret = avcodec_send_packet(dec_ctx, pkt);
58  if (ret < 0) {
59  fprintf(stderr, "Error sending a packet for decoding\n");
60  exit(1);
61  }
62 
63  while (ret >= 0) {
64  ret = avcodec_receive_frame(dec_ctx, frame);
65  if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF)
66  return;
67  else if (ret < 0) {
68  fprintf(stderr, "Error during decoding\n");
69  exit(1);
70  }
71 
72  printf("saving frame %3d\n", dec_ctx->frame_number);
73  fflush(stdout);
74 
75  /* the picture is allocated by the decoder. no need to
76  free it */
77  snprintf(buf, sizeof(buf), "%s-%d", filename, dec_ctx->frame_number);
78  pgm_save(frame->data[0], frame->linesize[0],
79  frame->width, frame->height, buf);
80  }
81 }
82 
83 int main(int argc, char **argv)
84 {
85  const char *filename, *outfilename;
86  const AVCodec *codec;
87  AVCodecParserContext *parser;
89  FILE *f;
90  AVFrame *frame;
92  uint8_t *data;
93  size_t data_size;
94  int ret;
95  AVPacket *pkt;
96 
97  if (argc <= 2) {
98  fprintf(stderr, "Usage: %s <input file> <output file>\n", argv[0]);
99  exit(0);
100  }
101  filename = argv[1];
102  outfilename = argv[2];
103 
104  pkt = av_packet_alloc();
105  if (!pkt)
106  exit(1);
107 
108  /* set end of buffer to 0 (this ensures that no overreading happens for damaged MPEG streams) */
109  memset(inbuf + INBUF_SIZE, 0, AV_INPUT_BUFFER_PADDING_SIZE);
110 
111  /* find the MPEG-1 video decoder */
113  if (!codec) {
114  fprintf(stderr, "Codec not found\n");
115  exit(1);
116  }
117 
118  parser = av_parser_init(codec->id);
119  if (!parser) {
120  fprintf(stderr, "parser not found\n");
121  exit(1);
122  }
123 
124  c = avcodec_alloc_context3(codec);
125  if (!c) {
126  fprintf(stderr, "Could not allocate video codec context\n");
127  exit(1);
128  }
129 
130  /* For some codecs, such as msmpeg4 and mpeg4, width and height
131  MUST be initialized there because this information is not
132  available in the bitstream. */
133 
134  /* open it */
135  if (avcodec_open2(c, codec, NULL) < 0) {
136  fprintf(stderr, "Could not open codec\n");
137  exit(1);
138  }
139 
140  f = fopen(filename, "rb");
141  if (!f) {
142  fprintf(stderr, "Could not open %s\n", filename);
143  exit(1);
144  }
145 
146  frame = av_frame_alloc();
147  if (!frame) {
148  fprintf(stderr, "Could not allocate video frame\n");
149  exit(1);
150  }
151 
152  while (!feof(f)) {
153  /* read raw data from the input file */
154  data_size = fread(inbuf, 1, INBUF_SIZE, f);
155  if (!data_size)
156  break;
157 
158  /* use the parser to split the data into frames */
159  data = inbuf;
160  while (data_size > 0) {
161  ret = av_parser_parse2(parser, c, &pkt->data, &pkt->size,
162  data, data_size, AV_NOPTS_VALUE, AV_NOPTS_VALUE, 0);
163  if (ret < 0) {
164  fprintf(stderr, "Error while parsing\n");
165  exit(1);
166  }
167  data += ret;
168  data_size -= ret;
169 
170  if (pkt->size)
171  decode(c, frame, pkt, outfilename);
172  }
173  }
174 
175  /* flush the decoder */
176  decode(c, frame, NULL, outfilename);
177 
178  fclose(f);
179 
180  av_parser_close(parser);
182  av_frame_free(&frame);
183  av_packet_free(&pkt);
184 
185  return 0;
186 }
#define NULL
Definition: coverity.c:32
#define INBUF_SIZE
Definition: decode_video.c:36
This structure describes decoded (raw) audio or video data.
Definition: frame.h:268
ptrdiff_t const GLvoid * data
Definition: opengl_enc.c:100
static void pgm_save(unsigned char *buf, int wrap, int xsize, int ysize, char *filename)
Definition: decode_video.c:38
int size
Definition: avcodec.h:1478
int main(int argc, char **argv)
Definition: decode_video.c:83
static AVPacket pkt
AVCodec.
Definition: avcodec.h:3477
void av_packet_free(AVPacket **pkt)
Free the packet, if the packet is reference counted, it will be unreferenced first.
Definition: avpacket.c:62
uint8_t
AVFrame * av_frame_alloc(void)
Allocate an AVFrame and set its fields to default values.
Definition: frame.c:189
#define f(width, name)
Definition: cbs_vp9.c:255
Undefined Behavior In the C some operations are like signed integer dereferencing freed accessing outside allocated Undefined Behavior must not occur in a C it is not safe even if the output of undefined operations is unused The unsafety may seem nit picking but Optimizing compilers have in fact optimized code on the assumption that no undefined Behavior occurs Optimizing code based on wrong assumptions can and has in some cases lead to effects beyond the output of computations The signed integer overflow problem in speed critical code Code which is highly optimized and works with signed integers sometimes has the problem that often the output of the computation does not c
Definition: undefined.txt:32
uint8_t * data
Definition: avcodec.h:1477
#define AVERROR_EOF
End of file.
Definition: error.h:55
enum AVCodecID id
Definition: avcodec.h:3491
#define i(width, name, range_min, range_max)
Definition: cbs_h2645.c:260
int width
Definition: frame.h:326
void av_frame_free(AVFrame **frame)
Free the frame and any dynamically allocated objects in it, e.g.
Definition: frame.c:202
int avcodec_receive_frame(AVCodecContext *avctx, AVFrame *frame)
Return decoded output data from a decoder.
Definition: decode.c:740
#define wrap(func)
Definition: neontest.h:65
static void decode(AVCodecContext *dec_ctx, AVFrame *frame, AVPacket *pkt, const char *filename)
Definition: decode_video.c:51
AVCodecContext * avcodec_alloc_context3(const AVCodec *codec)
Allocate an AVCodecContext and set its fields to default values.
Definition: options.c:156
int av_parser_parse2(AVCodecParserContext *s, AVCodecContext *avctx, uint8_t **poutbuf, int *poutbuf_size, const uint8_t *buf, int buf_size, int64_t pts, int64_t dts, int64_t pos)
Parse a packet.
Definition: parser.c:120
void av_parser_close(AVCodecParserContext *s)
Definition: parser.c:224
these buffered frames must be flushed immediately if a new input produces new the filter must not call request_frame to get more It must just process the frame or queue it The task of requesting more frames is left to the filter s request_frame method or the application If a filter has several the filter must be ready for frames arriving randomly on any input any filter with several inputs will most likely require some kind of queuing mechanism It is perfectly acceptable to have a limited queue and to drop frames when the inputs are too unbalanced request_frame For filters that do not use the this method is called when a frame is wanted on an output For a it should directly call filter_frame on the corresponding output For a if there are queued frames already one of these frames should be pushed If the filter should request a frame on one of its repeatedly until at least one frame has been pushed Return or at least make progress towards producing a frame
int avcodec_send_packet(AVCodecContext *avctx, const AVPacket *avpkt)
Supply raw packet data as input to a decoder.
Definition: decode.c:677
AVCodecParserContext * av_parser_init(int codec_id)
Definition: parser.c:34
Libavcodec external API header.
void avcodec_free_context(AVCodecContext **avctx)
Free the codec context and everything associated with it and write NULL to the provided pointer...
Definition: options.c:171
int linesize[AV_NUM_DATA_POINTERS]
For video, size in bytes of each picture line.
Definition: frame.h:299
main external API structure.
Definition: avcodec.h:1565
AVCodec * avcodec_find_decoder(enum AVCodecID id)
Find a registered decoder with a matching codec ID.
Definition: allcodecs.c:890
void * buf
Definition: avisynth_c.h:766
int avcodec_open2(AVCodecContext *avctx, const AVCodec *codec, AVDictionary **options)
Initialize the AVCodecContext to use the given AVCodec.
Definition: utils.c:542
#define snprintf
Definition: snprintf.h:34
uint8_t * data[AV_NUM_DATA_POINTERS]
pointer to the picture/channel planes.
Definition: frame.h:282
static AVCodecContext * dec_ctx
#define AV_INPUT_BUFFER_PADDING_SIZE
Required number of additionally allocated bytes at the end of the input bitstream for decoding...
Definition: avcodec.h:790
printf("static const uint8_t my_array[100] = {\n")
AVPacket * av_packet_alloc(void)
Allocate an AVPacket and set its fields to default values.
Definition: avpacket.c:51
int frame_number
Frame counter, set by libavcodec.
Definition: avcodec.h:2252
int height
Definition: frame.h:326
Filter the word “frame” indicates either a video frame or a group of audio as stored in an AVFrame structure Format for each input and each output the list of supported formats For video that means pixel format For audio that means channel sample they are references to shared objects When the negotiation mechanism computes the intersection of the formats supported at each end of a all references to both lists are replaced with a reference to the intersection And when a single format is eventually chosen for a link amongst the remaining all references to the list are updated That means that if a filter requires that its input and output have the same format amongst a supported all it has to do is use a reference to the same list of formats query_formats can leave some formats unset and return AVERROR(EAGAIN) to cause the negotiation mechanism toagain later.That can be used by filters with complex requirements to use the format negotiated on one link to set the formats supported on another.Frame references ownership and permissions
This structure stores compressed data.
Definition: avcodec.h:1454
#define AV_NOPTS_VALUE
Undefined timestamp value.
Definition: avutil.h:248