FFmpeg 5.1.6
vaapi_encode.c
Go to the documentation of this file.
1/*
2 * Video Acceleration API (video encoding) encode sample
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 * Intel VAAPI-accelerated encoding example.
26 *
27 * @example vaapi_encode.c
28 * This example shows how to do VAAPI-accelerated encoding. now only support NV12
29 * raw file, usage like: vaapi_encode 1920 1080 input.yuv output.h264
30 *
31 */
32
33#include <stdio.h>
34#include <string.h>
35#include <errno.h>
36
37#include <libavcodec/avcodec.h>
38#include <libavutil/pixdesc.h>
39#include <libavutil/hwcontext.h>
40
41static int width, height;
43
45{
46 AVBufferRef *hw_frames_ref;
47 AVHWFramesContext *frames_ctx = NULL;
48 int err = 0;
49
50 if (!(hw_frames_ref = av_hwframe_ctx_alloc(hw_device_ctx))) {
51 fprintf(stderr, "Failed to create VAAPI frame context.\n");
52 return -1;
53 }
54 frames_ctx = (AVHWFramesContext *)(hw_frames_ref->data);
55 frames_ctx->format = AV_PIX_FMT_VAAPI;
56 frames_ctx->sw_format = AV_PIX_FMT_NV12;
57 frames_ctx->width = width;
58 frames_ctx->height = height;
59 frames_ctx->initial_pool_size = 20;
60 if ((err = av_hwframe_ctx_init(hw_frames_ref)) < 0) {
61 fprintf(stderr, "Failed to initialize VAAPI frame context."
62 "Error code: %s\n",av_err2str(err));
63 av_buffer_unref(&hw_frames_ref);
64 return err;
65 }
66 ctx->hw_frames_ctx = av_buffer_ref(hw_frames_ref);
67 if (!ctx->hw_frames_ctx)
68 err = AVERROR(ENOMEM);
69
70 av_buffer_unref(&hw_frames_ref);
71 return err;
72}
73
74static int encode_write(AVCodecContext *avctx, AVFrame *frame, FILE *fout)
75{
76 int ret = 0;
77 AVPacket *enc_pkt;
78
79 if (!(enc_pkt = av_packet_alloc()))
80 return AVERROR(ENOMEM);
81
82 if ((ret = avcodec_send_frame(avctx, frame)) < 0) {
83 fprintf(stderr, "Error code: %s\n", av_err2str(ret));
84 goto end;
85 }
86 while (1) {
87 ret = avcodec_receive_packet(avctx, enc_pkt);
88 if (ret)
89 break;
90
91 enc_pkt->stream_index = 0;
92 ret = fwrite(enc_pkt->data, enc_pkt->size, 1, fout);
93 av_packet_unref(enc_pkt);
94 if (ret != enc_pkt->size) {
95 ret = AVERROR(errno);
96 break;
97 }
98 }
99
100end:
101 av_packet_free(&enc_pkt);
102 ret = ((ret == AVERROR(EAGAIN)) ? 0 : -1);
103 return ret;
104}
105
106int main(int argc, char *argv[])
107{
108 int size, err;
109 FILE *fin = NULL, *fout = NULL;
110 AVFrame *sw_frame = NULL, *hw_frame = NULL;
111 AVCodecContext *avctx = NULL;
112 const AVCodec *codec = NULL;
113 const char *enc_name = "h264_vaapi";
114
115 if (argc < 5) {
116 fprintf(stderr, "Usage: %s <width> <height> <input file> <output file>\n", argv[0]);
117 return -1;
118 }
119
120 width = atoi(argv[1]);
121 height = atoi(argv[2]);
122 size = width * height;
123
124 if (!(fin = fopen(argv[3], "r"))) {
125 fprintf(stderr, "Fail to open input file : %s\n", strerror(errno));
126 return -1;
127 }
128 if (!(fout = fopen(argv[4], "w+b"))) {
129 fprintf(stderr, "Fail to open output file : %s\n", strerror(errno));
130 err = -1;
131 goto close;
132 }
133
135 NULL, NULL, 0);
136 if (err < 0) {
137 fprintf(stderr, "Failed to create a VAAPI device. Error code: %s\n", av_err2str(err));
138 goto close;
139 }
140
141 if (!(codec = avcodec_find_encoder_by_name(enc_name))) {
142 fprintf(stderr, "Could not find encoder.\n");
143 err = -1;
144 goto close;
145 }
146
147 if (!(avctx = avcodec_alloc_context3(codec))) {
148 err = AVERROR(ENOMEM);
149 goto close;
150 }
151
152 avctx->width = width;
153 avctx->height = height;
154 avctx->time_base = (AVRational){1, 25};
155 avctx->framerate = (AVRational){25, 1};
156 avctx->sample_aspect_ratio = (AVRational){1, 1};
157 avctx->pix_fmt = AV_PIX_FMT_VAAPI;
158
159 /* set hw_frames_ctx for encoder's AVCodecContext */
160 if ((err = set_hwframe_ctx(avctx, hw_device_ctx)) < 0) {
161 fprintf(stderr, "Failed to set hwframe context.\n");
162 goto close;
163 }
164
165 if ((err = avcodec_open2(avctx, codec, NULL)) < 0) {
166 fprintf(stderr, "Cannot open video encoder codec. Error code: %s\n", av_err2str(err));
167 goto close;
168 }
169
170 while (1) {
171 if (!(sw_frame = av_frame_alloc())) {
172 err = AVERROR(ENOMEM);
173 goto close;
174 }
175 /* read data into software frame, and transfer them into hw frame */
176 sw_frame->width = width;
177 sw_frame->height = height;
178 sw_frame->format = AV_PIX_FMT_NV12;
179 if ((err = av_frame_get_buffer(sw_frame, 0)) < 0)
180 goto close;
181 if ((err = fread((uint8_t*)(sw_frame->data[0]), size, 1, fin)) <= 0)
182 break;
183 if ((err = fread((uint8_t*)(sw_frame->data[1]), size/2, 1, fin)) <= 0)
184 break;
185
186 if (!(hw_frame = av_frame_alloc())) {
187 err = AVERROR(ENOMEM);
188 goto close;
189 }
190 if ((err = av_hwframe_get_buffer(avctx->hw_frames_ctx, hw_frame, 0)) < 0) {
191 fprintf(stderr, "Error code: %s.\n", av_err2str(err));
192 goto close;
193 }
194 if (!hw_frame->hw_frames_ctx) {
195 err = AVERROR(ENOMEM);
196 goto close;
197 }
198 if ((err = av_hwframe_transfer_data(hw_frame, sw_frame, 0)) < 0) {
199 fprintf(stderr, "Error while transferring frame data to surface."
200 "Error code: %s.\n", av_err2str(err));
201 goto close;
202 }
203
204 if ((err = (encode_write(avctx, hw_frame, fout))) < 0) {
205 fprintf(stderr, "Failed to encode.\n");
206 goto close;
207 }
208 av_frame_free(&hw_frame);
209 av_frame_free(&sw_frame);
210 }
211
212 /* flush encoder */
213 err = encode_write(avctx, NULL, fout);
214 if (err == AVERROR_EOF)
215 err = 0;
216
217close:
218 if (fin)
219 fclose(fin);
220 if (fout)
221 fclose(fout);
222 av_frame_free(&sw_frame);
223 av_frame_free(&hw_frame);
224 avcodec_free_context(&avctx);
226
227 return err;
228}
Libavcodec external API header.
static AVFrame * frame
int avcodec_open2(AVCodecContext *avctx, const AVCodec *codec, AVDictionary **options)
Initialize the AVCodecContext to use the given AVCodec.
AVCodecContext * avcodec_alloc_context3(const AVCodec *codec)
Allocate an AVCodecContext and set its fields to default values.
const AVCodec * avcodec_find_encoder_by_name(const char *name)
Find a registered encoder with the specified name.
void avcodec_free_context(AVCodecContext **avctx)
Free the codec context and everything associated with it and write NULL to the provided pointer.
int avcodec_receive_packet(AVCodecContext *avctx, AVPacket *avpkt)
Read encoded data from the encoder.
int avcodec_send_frame(AVCodecContext *avctx, const AVFrame *frame)
Supply a raw video or audio frame to the encoder.
void av_packet_free(AVPacket **pkt)
Free the packet, if the packet is reference counted, it will be unreferenced first.
void av_packet_unref(AVPacket *pkt)
Wipe the packet.
AVPacket * av_packet_alloc(void)
Allocate an AVPacket and set its fields to default values.
void av_buffer_unref(AVBufferRef **buf)
Free a given reference and automatically free the buffer if there are no more references to it.
AVBufferRef * av_buffer_ref(const AVBufferRef *buf)
Create a new reference to an AVBuffer.
#define AVERROR_EOF
End of file.
Definition: error.h:57
#define av_err2str(errnum)
Convenience macro, the return value should be used only directly in function arguments but never stan...
Definition: error.h:121
#define AVERROR(e)
Definition: error.h:45
int av_frame_get_buffer(AVFrame *frame, int align)
Allocate new buffer(s) for audio or video data.
void av_frame_free(AVFrame **frame)
Free the frame and any dynamically allocated objects in it, e.g.
AVFrame * av_frame_alloc(void)
Allocate an AVFrame and set its fields to default values.
int av_hwframe_get_buffer(AVBufferRef *hwframe_ctx, AVFrame *frame, int flags)
Allocate a new frame attached to the given AVHWFramesContext.
AVBufferRef * av_hwframe_ctx_alloc(AVBufferRef *device_ctx)
Allocate an AVHWFramesContext tied to a given device context.
int av_hwframe_ctx_init(AVBufferRef *ref)
Finalize the context before use.
int av_hwframe_transfer_data(AVFrame *dst, const AVFrame *src, int flags)
Copy data to or from a hw surface.
int av_hwdevice_ctx_create(AVBufferRef **device_ctx, enum AVHWDeviceType type, const char *device, AVDictionary *opts, int flags)
Open a device of the specified type and create an AVHWDeviceContext for it.
@ AV_HWDEVICE_TYPE_VAAPI
Definition: hwcontext.h:31
@ AV_PIX_FMT_NV12
planar YUV 4:2:0, 12bpp, 1 plane for Y and 1 plane for the UV components, which are interleaved (firs...
Definition: pixfmt.h:89
@ AV_PIX_FMT_VAAPI
Hardware acceleration through VA-API, data[3] contains a VASurfaceID.
Definition: pixfmt.h:119
A reference to a data buffer.
Definition: buffer.h:82
uint8_t * data
The data buffer.
Definition: buffer.h:90
main external API structure.
Definition: avcodec.h:389
enum AVPixelFormat pix_fmt
Pixel format, see AV_PIX_FMT_xxx.
Definition: avcodec.h:599
int width
picture width / height.
Definition: avcodec.h:562
AVBufferRef * hw_frames_ctx
A reference to the AVHWFramesContext describing the input (for encoding) or output (decoding) frames.
Definition: avcodec.h:1880
AVRational framerate
Definition: avcodec.h:1732
AVRational sample_aspect_ratio
sample aspect ratio (0 if unknown) That is the width of a pixel divided by the height of the pixel.
Definition: avcodec.h:759
AVRational time_base
This is the fundamental unit of time (in seconds) in terms of which frame timestamps are represented.
Definition: avcodec.h:512
AVCodec.
Definition: codec.h:196
This structure describes decoded (raw) audio or video data.
Definition: frame.h:325
uint8_t * data[AV_NUM_DATA_POINTERS]
pointer to the picture/channel planes.
Definition: frame.h:346
int width
Definition: frame.h:397
int height
Definition: frame.h:397
int format
format of the frame, -1 if unknown or unset Values correspond to enum AVPixelFormat for video frames,...
Definition: frame.h:412
This struct describes a set or pool of "hardware" frames (i.e.
Definition: hwcontext.h:124
enum AVPixelFormat format
The pixel format identifying the underlying HW surface type.
Definition: hwcontext.h:209
enum AVPixelFormat sw_format
The pixel format identifying the actual data layout of the hardware frames.
Definition: hwcontext.h:222
int initial_pool_size
Initial size of the frame pool.
Definition: hwcontext.h:199
int width
The allocated dimensions of the frames in this pool.
Definition: hwcontext.h:229
This structure stores compressed data.
Definition: packet.h:351
int stream_index
Definition: packet.h:376
int size
Definition: packet.h:375
uint8_t * data
Definition: packet.h:374
Rational number (pair of numerator and denominator).
Definition: rational.h:58
static AVBufferRef * hw_device_ctx
Definition: vaapi_encode.c:42
int main(int argc, char *argv[])
Definition: vaapi_encode.c:106
static int width
Definition: vaapi_encode.c:41
static int encode_write(AVCodecContext *avctx, AVFrame *frame, FILE *fout)
Definition: vaapi_encode.c:74
static int set_hwframe_ctx(AVCodecContext *ctx, AVBufferRef *hw_device_ctx)
Definition: vaapi_encode.c:44
static int height
Definition: vaapi_encode.c:41