FFmpeg
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros Groups Pages
hw_decode.c
Go to the documentation of this file.
1 /*
2  * Copyright (c) 2017 Jun Zhao
3  * Copyright (c) 2017 Kaixuan Liu
4  *
5  * HW Acceleration API (video decoding) decode sample
6  *
7  * This file is part of FFmpeg.
8  *
9  * FFmpeg is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU Lesser General Public
11  * License as published by the Free Software Foundation; either
12  * version 2.1 of the License, or (at your option) any later version.
13  *
14  * FFmpeg is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17  * Lesser General Public License for more details.
18  *
19  * You should have received a copy of the GNU Lesser General Public
20  * License along with FFmpeg; if not, write to the Free Software
21  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
22  */
23 
24 /**
25  * @file
26  * HW-Accelerated decoding example.
27  *
28  * @example hw_decode.c
29  * This example shows how to do HW-accelerated decoding with output
30  * frames from the HW video surfaces.
31  */
32 
33 #include <stdio.h>
34 
35 #include <libavcodec/avcodec.h>
36 #include <libavformat/avformat.h>
37 #include <libavutil/pixdesc.h>
38 #include <libavutil/hwcontext.h>
39 #include <libavutil/opt.h>
40 #include <libavutil/avassert.h>
41 #include <libavutil/imgutils.h>
42 
45 static FILE *output_file = NULL;
46 
48 {
49  int err = 0;
50 
51  if ((err = av_hwdevice_ctx_create(&hw_device_ctx, type,
52  NULL, NULL, 0)) < 0) {
53  fprintf(stderr, "Failed to create specified HW device.\n");
54  return err;
55  }
56  ctx->hw_device_ctx = av_buffer_ref(hw_device_ctx);
57 
58  return err;
59 }
60 
62  const enum AVPixelFormat *pix_fmts)
63 {
64  const enum AVPixelFormat *p;
65 
66  for (p = pix_fmts; *p != -1; p++) {
67  if (*p == hw_pix_fmt)
68  return *p;
69  }
70 
71  fprintf(stderr, "Failed to get HW surface format.\n");
72  return AV_PIX_FMT_NONE;
73 }
74 
75 static int decode_write(AVCodecContext *avctx, AVPacket *packet)
76 {
77  AVFrame *frame = NULL, *sw_frame = NULL;
78  AVFrame *tmp_frame = NULL;
79  uint8_t *buffer = NULL;
80  int size;
81  int ret = 0;
82 
83  ret = avcodec_send_packet(avctx, packet);
84  if (ret < 0) {
85  fprintf(stderr, "Error during decoding\n");
86  return ret;
87  }
88 
89  while (ret >= 0) {
90  if (!(frame = av_frame_alloc()) || !(sw_frame = av_frame_alloc())) {
91  fprintf(stderr, "Can not alloc frame\n");
92  ret = AVERROR(ENOMEM);
93  goto fail;
94  }
95 
96  ret = avcodec_receive_frame(avctx, frame);
97  if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF) {
98  av_frame_free(&frame);
99  av_frame_free(&sw_frame);
100  return 0;
101  } else if (ret < 0) {
102  fprintf(stderr, "Error while decoding\n");
103  goto fail;
104  }
105 
106  if (frame->format == hw_pix_fmt) {
107  /* retrieve data from GPU to CPU */
108  if ((ret = av_hwframe_transfer_data(sw_frame, frame, 0)) < 0) {
109  fprintf(stderr, "Error transferring the data to system memory\n");
110  goto fail;
111  }
112  tmp_frame = sw_frame;
113  } else
114  tmp_frame = frame;
115 
116  size = av_image_get_buffer_size(tmp_frame->format, tmp_frame->width,
117  tmp_frame->height, 1);
118  buffer = av_malloc(size);
119  if (!buffer) {
120  fprintf(stderr, "Can not alloc buffer\n");
121  ret = AVERROR(ENOMEM);
122  goto fail;
123  }
124  ret = av_image_copy_to_buffer(buffer, size,
125  (const uint8_t * const *)tmp_frame->data,
126  (const int *)tmp_frame->linesize, tmp_frame->format,
127  tmp_frame->width, tmp_frame->height, 1);
128  if (ret < 0) {
129  fprintf(stderr, "Can not copy image to buffer\n");
130  goto fail;
131  }
132 
133  if ((ret = fwrite(buffer, 1, size, output_file)) < 0) {
134  fprintf(stderr, "Failed to dump raw data.\n");
135  goto fail;
136  }
137 
138  fail:
139  av_frame_free(&frame);
140  av_frame_free(&sw_frame);
141  if (buffer)
142  av_freep(&buffer);
143  if (ret < 0)
144  return ret;
145  }
146 
147  return 0;
148 }
149 
150 int main(int argc, char *argv[])
151 {
152  AVFormatContext *input_ctx = NULL;
153  int video_stream, ret;
154  AVStream *video = NULL;
155  AVCodecContext *decoder_ctx = NULL;
156  AVCodec *decoder = NULL;
157  AVPacket packet;
158  enum AVHWDeviceType type;
159  int i;
160 
161  if (argc < 4) {
162  fprintf(stderr, "Usage: %s <device type> <input file> <output file>\n", argv[0]);
163  return -1;
164  }
165 
166  av_register_all();
167 
168  type = av_hwdevice_find_type_by_name(argv[1]);
169  if (type == AV_HWDEVICE_TYPE_NONE) {
170  fprintf(stderr, "Device type %s is not supported.\n", argv[1]);
171  fprintf(stderr, "Available device types:");
172  while((type = av_hwdevice_iterate_types(type)) != AV_HWDEVICE_TYPE_NONE)
173  fprintf(stderr, " %s", av_hwdevice_get_type_name(type));
174  fprintf(stderr, "\n");
175  return -1;
176  }
177 
178  /* open the input file */
179  if (avformat_open_input(&input_ctx, argv[2], NULL, NULL) != 0) {
180  fprintf(stderr, "Cannot open input file '%s'\n", argv[2]);
181  return -1;
182  }
183 
184  if (avformat_find_stream_info(input_ctx, NULL) < 0) {
185  fprintf(stderr, "Cannot find input stream information.\n");
186  return -1;
187  }
188 
189  /* find the video stream information */
190  ret = av_find_best_stream(input_ctx, AVMEDIA_TYPE_VIDEO, -1, -1, &decoder, 0);
191  if (ret < 0) {
192  fprintf(stderr, "Cannot find a video stream in the input file\n");
193  return -1;
194  }
195  video_stream = ret;
196 
197  for (i = 0;; i++) {
198  const AVCodecHWConfig *config = avcodec_get_hw_config(decoder, i);
199  if (!config) {
200  fprintf(stderr, "Decoder %s does not support device type %s.\n",
201  decoder->name, av_hwdevice_get_type_name(type));
202  return -1;
203  }
205  config->device_type == type) {
206  hw_pix_fmt = config->pix_fmt;
207  break;
208  }
209  }
210 
211  if (!(decoder_ctx = avcodec_alloc_context3(decoder)))
212  return AVERROR(ENOMEM);
213 
214  video = input_ctx->streams[video_stream];
215  if (avcodec_parameters_to_context(decoder_ctx, video->codecpar) < 0)
216  return -1;
217 
218  decoder_ctx->get_format = get_hw_format;
219  av_opt_set_int(decoder_ctx, "refcounted_frames", 1, 0);
220 
221  if (hw_decoder_init(decoder_ctx, type) < 0)
222  return -1;
223 
224  if ((ret = avcodec_open2(decoder_ctx, decoder, NULL)) < 0) {
225  fprintf(stderr, "Failed to open codec for stream #%u\n", video_stream);
226  return -1;
227  }
228 
229  /* open the file to dump raw data */
230  output_file = fopen(argv[3], "w+");
231 
232  /* actual decoding and dump the raw data */
233  while (ret >= 0) {
234  if ((ret = av_read_frame(input_ctx, &packet)) < 0)
235  break;
236 
237  if (video_stream == packet.stream_index)
238  ret = decode_write(decoder_ctx, &packet);
239 
240  av_packet_unref(&packet);
241  }
242 
243  /* flush the decoder */
244  packet.data = NULL;
245  packet.size = 0;
246  ret = decode_write(decoder_ctx, &packet);
247  av_packet_unref(&packet);
248 
249  if (output_file)
250  fclose(output_file);
251  avcodec_free_context(&decoder_ctx);
252  avformat_close_input(&input_ctx);
253  av_buffer_unref(&hw_device_ctx);
254 
255  return 0;
256 }
#define NULL
Definition: coverity.c:32
void av_buffer_unref(AVBufferRef **buf)
Free a given reference and automatically free the buffer if there are no more references to it...
Definition: buffer.c:125
This structure describes decoded (raw) audio or video data.
Definition: frame.h:201
int av_image_copy_to_buffer(uint8_t *dst, int dst_size, const uint8_t *const src_data[4], const int src_linesize[4], enum AVPixelFormat pix_fmt, int width, int height, int align)
Copy image data from an image into a buffer.
Definition: imgutils.c:452
static enum AVPixelFormat get_hw_format(AVCodecContext *ctx, const enum AVPixelFormat *pix_fmts)
Definition: hw_decode.c:61
misc image utilities
enum AVHWDeviceType av_hwdevice_find_type_by_name(const char *name)
Look up an AVHWDeviceType by name.
Definition: hwcontext.c:74
static FFServerConfig config
Definition: ffserver.c:193
int size
Definition: avcodec.h:1401
static AVStream * video_stream
AVCodec.
Definition: avcodec.h:3351
Format I/O context.
Definition: avformat.h:1325
uint8_t
#define av_malloc(s)
AVFrame * av_frame_alloc(void)
Allocate an AVFrame and set its fields to default values.
Definition: frame.c:150
AVOptions.
enum AVPixelFormat pix_fmt
A hardware pixel format which the codec can use.
Definition: avcodec.h:3329
AVStream ** streams
A list of all streams in the file.
Definition: avformat.h:1393
int avcodec_parameters_to_context(AVCodecContext *codec, const AVCodecParameters *par)
Fill the codec context based on the values from the supplied codec parameters.
Definition: utils.c:2306
static AVFrame * frame
int av_hwdevice_ctx_create(AVBufferRef **pdevice_ref, enum AVHWDeviceType type, const char *device, AVDictionary *opts, int flags)
Open a device of the specified type and create an AVHWDeviceContext for it.
Definition: hwcontext.c:565
uint8_t * data
Definition: avcodec.h:1400
#define AVERROR_EOF
End of file.
Definition: error.h:55
ptrdiff_t size
Definition: opengl_enc.c:101
int av_find_best_stream(AVFormatContext *ic, enum AVMediaType type, int wanted_stream_nb, int related_stream, AVCodec **decoder_ret, int flags)
Find the "best" stream in the file.
Definition: utils.c:4115
int av_image_get_buffer_size(enum AVPixelFormat pix_fmt, int width, int height, int align)
Return the size in bytes of the amount of data required to store an image with the given parameters...
Definition: imgutils.c:430
int width
Definition: frame.h:259
static AVBufferRef * hw_device_ctx
Definition: hw_decode.c:43
#define AVERROR(e)
Definition: error.h:43
void av_frame_free(AVFrame **frame)
Free the frame and any dynamically allocated objects in it, e.g.
Definition: frame.c:163
int methods
Bit set of AV_CODEC_HW_CONFIG_METHOD_* flags, describing the possible setup methods which can be used...
Definition: avcodec.h:3334
int avcodec_receive_frame(AVCodecContext *avctx, AVFrame *frame)
Return decoded output data from a decoder.
Definition: decode.c:709
int main(int argc, char *argv[])
Definition: hw_decode.c:150
int av_opt_set_int(void *obj, const char *name, int64_t val, int search_flags)
Definition: opt.c:558
simple assert() macros that are a bit more flexible than ISO C assert().
const char * name
Name of the codec implementation.
Definition: avcodec.h:3358
#define fail()
Definition: checkasm.h:112
int av_hwframe_transfer_data(AVFrame *dst, const AVFrame *src, int flags)
Copy data to or from a hw surface.
Definition: hwcontext.c:435
AVCodecContext * avcodec_alloc_context3(const AVCodec *codec)
Allocate an AVCodecContext and set its fields to default values.
Definition: options.c:157
static const chunk_decoder decoder[8]
Definition: dfa.c:330
AVFormatContext * ctx
Definition: movenc.c:48
Stream structure.
Definition: avformat.h:872
int format
format of the frame, -1 if unknown or unset Values correspond to enum AVPixelFormat for video frames...
Definition: frame.h:274
static FILE * output_file
Definition: hw_decode.c:45
int avcodec_send_packet(AVCodecContext *avctx, const AVPacket *avpkt)
Supply raw packet data as input to a decoder.
Definition: decode.c:642
Libavcodec external API header.
static int hw_decoder_init(AVCodecContext *ctx, const enum AVHWDeviceType type)
Definition: hw_decode.c:47
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:172
int linesize[AV_NUM_DATA_POINTERS]
For video, size in bytes of each picture line.
Definition: frame.h:232
const AVCodecHWConfig * avcodec_get_hw_config(const AVCodec *codec, int index)
Retrieve supported hardware configurations for a codec.
Definition: utils.c:1890
main external API structure.
Definition: avcodec.h:1488
void av_packet_unref(AVPacket *pkt)
Wipe the packet.
Definition: avpacket.c:590
static int decode_write(AVCodecContext *avctx, AVPacket *packet)
Definition: hw_decode.c:75
GLint GLenum type
Definition: opengl_enc.c:105
enum AVPixelFormat(* get_format)(struct AVCodecContext *s, const enum AVPixelFormat *fmt)
callback to negotiate the pixelFormat
Definition: avcodec.h:1739
const char * av_hwdevice_get_type_name(enum AVHWDeviceType type)
Get the string name of an AVHWDeviceType.
Definition: hwcontext.c:84
int avcodec_open2(AVCodecContext *avctx, const AVCodec *codec, AVDictionary **options)
Initialize the AVCodecContext to use the given AVCodec.
Definition: utils.c:614
int av_read_frame(AVFormatContext *s, AVPacket *pkt)
Return the next frame of a stream.
Definition: utils.c:1712
static enum AVPixelFormat pix_fmts[]
Definition: libkvazaar.c:266
uint8_t * data[AV_NUM_DATA_POINTERS]
pointer to the picture/channel planes.
Definition: frame.h:215
A reference to a data buffer.
Definition: buffer.h:81
Main libavformat public API header.
static enum AVPixelFormat hw_pix_fmt
Definition: hw_decode.c:44
int avformat_find_stream_info(AVFormatContext *ic, AVDictionary **options)
Read packets of a media file to get stream information.
Definition: utils.c:3497
AVBufferRef * av_buffer_ref(AVBufferRef *buf)
Create a new reference to an AVBuffer.
Definition: buffer.c:93
void avformat_close_input(AVFormatContext **s)
Close an opened input AVFormatContext.
Definition: utils.c:4350
The codec supports this format via the hw_device_ctx interface.
Definition: avcodec.h:3297
enum AVHWDeviceType av_hwdevice_iterate_types(enum AVHWDeviceType prev)
Iterate over supported device types.
Definition: hwcontext.c:93
AVHWDeviceType
Definition: hwcontext.h:27
int avformat_open_input(AVFormatContext **ps, const char *url, AVInputFormat *fmt, AVDictionary **options)
Open an input stream and read the header.
Definition: utils.c:515
int height
Definition: frame.h:259
#define av_freep(p)
AVCodecParameters * codecpar
Codec parameters associated with this stream.
Definition: avformat.h:1014
enum AVHWDeviceType device_type
The device type associated with the configuration.
Definition: avcodec.h:3341
int stream_index
Definition: avcodec.h:1402
AVBufferRef * hw_device_ctx
A reference to the AVHWDeviceContext describing the device which will be used by a hardware encoder/d...
Definition: avcodec.h:3206
AVPixelFormat
Pixel format.
Definition: pixfmt.h:60
This structure stores compressed data.
Definition: avcodec.h:1377
void av_register_all(void)
Initialize libavformat and register all the muxers, demuxers and protocols.
Definition: allformats.c:395
GLuint buffer
Definition: opengl_enc.c:102