2 * This file is part of FFmpeg.
4 * FFmpeg is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU Lesser General Public
6 * License as published by the Free Software Foundation; either
7 * version 2.1 of the License, or (at your option) any later version.
9 * FFmpeg is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * Lesser General Public License for more details.
14 * You should have received a copy of the GNU Lesser General Public
15 * License along with FFmpeg; if not, write to the Free Software
16 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
26 # include <va/va_x11.h>
29 # include <va/va_drm.h>
32 #include "libavutil/avassert.h"
33 #include "libavutil/avconfig.h"
34 #include "libavutil/buffer.h"
35 #include "libavutil/frame.h"
36 #include "libavutil/hwcontext.h"
37 #include "libavutil/hwcontext_vaapi.h"
38 #include "libavutil/imgutils.h"
39 #include "libavutil/opt.h"
40 #include "libavutil/pixfmt.h"
42 #include "libavcodec/vaapi.h"
47 static AVClass vaapi_class = {
48 .class_name = "vaapi",
49 .item_name = av_default_item_name,
50 .version = LIBAVUTIL_VERSION_INT,
53 #define DEFAULT_SURFACES 20
55 typedef struct VAAPIDecoderContext {
58 AVBufferRef *device_ref;
59 AVHWDeviceContext *device;
60 AVBufferRef *frames_ref;
61 AVHWFramesContext *frames;
64 VAEntrypoint va_entrypoint;
66 VAContextID va_context;
68 enum AVPixelFormat decode_format;
73 // The output need not have the same format, width and height as the
74 // decoded frames - the copy for non-direct-mapped access is actually
75 // a whole vpp instance which can do arbitrary scaling and format
77 enum AVPixelFormat output_format;
79 struct vaapi_context decoder_vaapi_context;
80 } VAAPIDecoderContext;
83 static int vaapi_get_buffer(AVCodecContext *avctx, AVFrame *frame, int flags)
85 InputStream *ist = avctx->opaque;
86 VAAPIDecoderContext *ctx = ist->hwaccel_ctx;
89 err = av_hwframe_get_buffer(ctx->frames_ref, frame, 0);
91 av_log(ctx, AV_LOG_ERROR, "Failed to allocate decoder surface.\n");
93 av_log(ctx, AV_LOG_DEBUG, "Decoder given surface %#x.\n",
94 (unsigned int)(uintptr_t)frame->data[3]);
99 static int vaapi_retrieve_data(AVCodecContext *avctx, AVFrame *input)
101 InputStream *ist = avctx->opaque;
102 VAAPIDecoderContext *ctx = ist->hwaccel_ctx;
106 av_assert0(input->format == AV_PIX_FMT_VAAPI);
108 if (ctx->output_format == AV_PIX_FMT_VAAPI) {
113 av_log(ctx, AV_LOG_DEBUG, "Retrieve data from surface %#x.\n",
114 (unsigned int)(uintptr_t)input->data[3]);
116 output = av_frame_alloc();
118 return AVERROR(ENOMEM);
120 output->format = ctx->output_format;
122 err = av_hwframe_transfer_data(output, input, 0);
124 av_log(ctx, AV_LOG_ERROR, "Failed to transfer data to "
125 "output frame: %d.\n", err);
129 err = av_frame_copy_props(output, input);
131 av_frame_unref(output);
135 av_frame_unref(input);
136 av_frame_move_ref(input, output);
137 av_frame_free(&output);
143 av_frame_free(&output);
148 static const struct {
149 enum AVCodecID codec_id;
151 VAProfile va_profile;
152 } vaapi_profile_map[] = {
153 #define MAP(c, p, v) { AV_CODEC_ID_ ## c, FF_PROFILE_ ## p, VAProfile ## v }
154 MAP(MPEG2VIDEO, MPEG2_SIMPLE, MPEG2Simple ),
155 MAP(MPEG2VIDEO, MPEG2_MAIN, MPEG2Main ),
156 MAP(H263, UNKNOWN, H263Baseline),
157 MAP(MPEG4, MPEG4_SIMPLE, MPEG4Simple ),
158 MAP(MPEG4, MPEG4_ADVANCED_SIMPLE,
159 MPEG4AdvancedSimple),
160 MAP(MPEG4, MPEG4_MAIN, MPEG4Main ),
161 MAP(H264, H264_CONSTRAINED_BASELINE,
162 H264ConstrainedBaseline),
163 MAP(H264, H264_BASELINE, H264Baseline),
164 MAP(H264, H264_MAIN, H264Main ),
165 MAP(H264, H264_HIGH, H264High ),
166 #if VA_CHECK_VERSION(0, 37, 0)
167 MAP(HEVC, HEVC_MAIN, HEVCMain ),
169 MAP(WMV3, VC1_SIMPLE, VC1Simple ),
170 MAP(WMV3, VC1_MAIN, VC1Main ),
171 MAP(WMV3, VC1_COMPLEX, VC1Advanced ),
172 MAP(WMV3, VC1_ADVANCED, VC1Advanced ),
173 MAP(VC1, VC1_SIMPLE, VC1Simple ),
174 MAP(VC1, VC1_MAIN, VC1Main ),
175 MAP(VC1, VC1_COMPLEX, VC1Advanced ),
176 MAP(VC1, VC1_ADVANCED, VC1Advanced ),
177 #if VA_CHECK_VERSION(0, 35, 0)
178 MAP(VP8, UNKNOWN, VP8Version0_3 ),
180 #if VA_CHECK_VERSION(0, 37, 1)
181 MAP(VP9, VP9_0, VP9Profile0 ),
186 static int vaapi_build_decoder_config(VAAPIDecoderContext *ctx,
187 AVCodecContext *avctx,
188 int fallback_allowed)
190 AVVAAPIDeviceContext *hwctx = ctx->device->hwctx;
191 AVVAAPIHWConfig *hwconfig = NULL;
192 AVHWFramesConstraints *constraints = NULL;
195 int loglevel = fallback_allowed ? AV_LOG_VERBOSE : AV_LOG_ERROR;
196 const AVCodecDescriptor *codec_desc;
197 const AVPixFmtDescriptor *pix_desc;
198 enum AVPixelFormat pix_fmt;
199 VAProfile profile, *profile_list = NULL;
200 int profile_count, exact_match, alt_profile;
202 codec_desc = avcodec_descriptor_get(avctx->codec_id);
204 err = AVERROR(EINVAL);
208 profile_count = vaMaxNumProfiles(hwctx->display);
209 profile_list = av_malloc(profile_count * sizeof(VAProfile));
211 err = AVERROR(ENOMEM);
215 vas = vaQueryConfigProfiles(hwctx->display,
216 profile_list, &profile_count);
217 if (vas != VA_STATUS_SUCCESS) {
218 av_log(ctx, loglevel, "Failed to query profiles: %d (%s).\n",
219 vas, vaErrorStr(vas));
224 profile = VAProfileNone;
227 for (i = 0; i < FF_ARRAY_ELEMS(vaapi_profile_map); i++) {
228 int profile_match = 0;
229 if (avctx->codec_id != vaapi_profile_map[i].codec_id)
231 if (avctx->profile == vaapi_profile_map[i].codec_profile)
233 profile = vaapi_profile_map[i].va_profile;
234 for (j = 0; j < profile_count; j++) {
235 if (profile == profile_list[j]) {
236 exact_match = profile_match;
240 if (j < profile_count) {
243 alt_profile = vaapi_profile_map[i].codec_profile;
246 av_freep(&profile_list);
248 if (profile == VAProfileNone) {
249 av_log(ctx, loglevel, "No VAAPI support for codec %s.\n",
251 err = AVERROR(ENOSYS);
255 if (fallback_allowed || !hwaccel_lax_profile_check) {
256 av_log(ctx, loglevel, "No VAAPI support for codec %s "
257 "profile %d.\n", codec_desc->name, avctx->profile);
258 if (!fallback_allowed) {
259 av_log(ctx, AV_LOG_WARNING, "If you want attempt decoding "
260 "anyway with a possibly-incompatible profile, add "
261 "the option -hwaccel_lax_profile_check.\n");
263 err = AVERROR(EINVAL);
266 av_log(ctx, AV_LOG_WARNING, "No VAAPI support for codec %s "
267 "profile %d: trying instead with profile %d.\n",
268 codec_desc->name, avctx->profile, alt_profile);
269 av_log(ctx, AV_LOG_WARNING, "This may fail or give "
270 "incorrect results, depending on your hardware.\n");
274 ctx->va_profile = profile;
275 ctx->va_entrypoint = VAEntrypointVLD;
277 vas = vaCreateConfig(hwctx->display, ctx->va_profile,
278 ctx->va_entrypoint, 0, 0, &ctx->va_config);
279 if (vas != VA_STATUS_SUCCESS) {
280 av_log(ctx, AV_LOG_ERROR, "Failed to create decode pipeline "
281 "configuration: %d (%s).\n", vas, vaErrorStr(vas));
286 hwconfig = av_hwdevice_hwconfig_alloc(ctx->device_ref);
288 err = AVERROR(ENOMEM);
291 hwconfig->config_id = ctx->va_config;
293 constraints = av_hwdevice_get_hwframe_constraints(ctx->device_ref,
298 // Decide on the decoder target format.
299 // If the user specified something with -hwaccel_output_format then
300 // try to use that to minimise conversions later.
301 ctx->decode_format = AV_PIX_FMT_NONE;
302 if (ctx->output_format != AV_PIX_FMT_NONE &&
303 ctx->output_format != AV_PIX_FMT_VAAPI) {
304 for (i = 0; constraints->valid_sw_formats[i] != AV_PIX_FMT_NONE; i++) {
305 if (constraints->valid_sw_formats[i] == ctx->output_format) {
306 ctx->decode_format = ctx->output_format;
307 av_log(ctx, AV_LOG_DEBUG, "Using decode format %s (output "
308 "format).\n", av_get_pix_fmt_name(ctx->decode_format));
313 // Otherwise, we would like to try to choose something which matches the
314 // decoder output, but there isn't enough information available here to
315 // do so. Assume for now that we are always dealing with YUV 4:2:0, so
316 // pick a format which does that.
317 if (ctx->decode_format == AV_PIX_FMT_NONE) {
318 for (i = 0; constraints->valid_sw_formats[i] != AV_PIX_FMT_NONE; i++) {
319 pix_fmt = constraints->valid_sw_formats[i];
320 pix_desc = av_pix_fmt_desc_get(pix_fmt);
321 if (pix_desc->nb_components == 3 &&
322 pix_desc->log2_chroma_w == 1 &&
323 pix_desc->log2_chroma_h == 1) {
324 ctx->decode_format = pix_fmt;
325 av_log(ctx, AV_LOG_DEBUG, "Using decode format %s (format "
326 "matched).\n", av_get_pix_fmt_name(ctx->decode_format));
331 // Otherwise pick the first in the list and hope for the best.
332 if (ctx->decode_format == AV_PIX_FMT_NONE) {
333 ctx->decode_format = constraints->valid_sw_formats[0];
334 av_log(ctx, AV_LOG_DEBUG, "Using decode format %s (first in list).\n",
335 av_get_pix_fmt_name(ctx->decode_format));
337 // There was a choice, and we picked randomly. Warn the user
338 // that they might want to choose intelligently instead.
339 av_log(ctx, AV_LOG_WARNING, "Using randomly chosen decode "
340 "format %s.\n", av_get_pix_fmt_name(ctx->decode_format));
344 // Ensure the picture size is supported by the hardware.
345 ctx->decode_width = avctx->coded_width;
346 ctx->decode_height = avctx->coded_height;
347 if (ctx->decode_width < constraints->min_width ||
348 ctx->decode_height < constraints->min_height ||
349 ctx->decode_width > constraints->max_width ||
350 ctx->decode_height >constraints->max_height) {
351 av_log(ctx, AV_LOG_ERROR, "VAAPI hardware does not support image "
352 "size %dx%d (constraints: width %d-%d height %d-%d).\n",
353 ctx->decode_width, ctx->decode_height,
354 constraints->min_width, constraints->max_width,
355 constraints->min_height, constraints->max_height);
356 err = AVERROR(EINVAL);
360 av_hwframe_constraints_free(&constraints);
363 // Decide how many reference frames we need. This might be doable more
364 // nicely based on the codec and input stream?
365 ctx->decode_surfaces = DEFAULT_SURFACES;
366 // For frame-threaded decoding, one additional surfaces is needed for
368 if (avctx->active_thread_type & FF_THREAD_FRAME)
369 ctx->decode_surfaces += avctx->thread_count;
374 av_hwframe_constraints_free(&constraints);
376 vaDestroyConfig(hwctx->display, ctx->va_config);
377 av_freep(&profile_list);
381 static void vaapi_decode_uninit(AVCodecContext *avctx)
383 InputStream *ist = avctx->opaque;
384 VAAPIDecoderContext *ctx = ist->hwaccel_ctx;
387 AVVAAPIDeviceContext *hwctx = ctx->device->hwctx;
389 if (ctx->va_context != VA_INVALID_ID) {
390 vaDestroyContext(hwctx->display, ctx->va_context);
391 ctx->va_context = VA_INVALID_ID;
393 if (ctx->va_config != VA_INVALID_ID) {
394 vaDestroyConfig(hwctx->display, ctx->va_config);
395 ctx->va_config = VA_INVALID_ID;
398 av_buffer_unref(&ctx->frames_ref);
399 av_buffer_unref(&ctx->device_ref);
403 av_buffer_unref(&ist->hw_frames_ctx);
405 ist->hwaccel_ctx = 0;
406 ist->hwaccel_uninit = 0;
407 ist->hwaccel_get_buffer = 0;
408 ist->hwaccel_retrieve_data = 0;
411 int vaapi_decode_init(AVCodecContext *avctx)
413 InputStream *ist = avctx->opaque;
414 AVVAAPIDeviceContext *hwctx;
415 AVVAAPIFramesContext *avfc;
416 VAAPIDecoderContext *ctx;
419 int loglevel = (ist->hwaccel_id != HWACCEL_VAAPI ? AV_LOG_VERBOSE
422 if (ist->hwaccel_ctx)
423 vaapi_decode_uninit(avctx);
425 // We have -hwaccel without -vaapi_device, so just initialise here with
426 // the device passed as -hwaccel_device (if -vaapi_device was passed, it
427 // will always have been called before now).
428 if (!hw_device_ctx) {
429 err = vaapi_device_init(ist->hwaccel_device);
434 ctx = av_mallocz(sizeof(*ctx));
436 return AVERROR(ENOMEM);
437 ctx->class = &vaapi_class;
439 ctx->device_ref = av_buffer_ref(hw_device_ctx);
440 ctx->device = (AVHWDeviceContext*)ctx->device_ref->data;
442 ctx->va_config = VA_INVALID_ID;
443 ctx->va_context = VA_INVALID_ID;
445 hwctx = ctx->device->hwctx;
447 ctx->output_format = ist->hwaccel_output_format;
449 err = vaapi_build_decoder_config(ctx, avctx,
450 ist->hwaccel_id != HWACCEL_VAAPI);
452 av_log(ctx, loglevel, "No supported configuration for this codec.");
456 avctx->pix_fmt = ctx->output_format;
458 ctx->frames_ref = av_hwframe_ctx_alloc(ctx->device_ref);
459 if (!ctx->frames_ref) {
460 av_log(ctx, loglevel, "Failed to create VAAPI frame context.\n");
461 err = AVERROR(ENOMEM);
465 ctx->frames = (AVHWFramesContext*)ctx->frames_ref->data;
467 ctx->frames->format = AV_PIX_FMT_VAAPI;
468 ctx->frames->sw_format = ctx->decode_format;
469 ctx->frames->width = ctx->decode_width;
470 ctx->frames->height = ctx->decode_height;
471 ctx->frames->initial_pool_size = ctx->decode_surfaces;
473 err = av_hwframe_ctx_init(ctx->frames_ref);
475 av_log(ctx, loglevel, "Failed to initialise VAAPI frame "
476 "context: %d\n", err);
480 avfc = ctx->frames->hwctx;
482 vas = vaCreateContext(hwctx->display, ctx->va_config,
483 ctx->decode_width, ctx->decode_height,
485 avfc->surface_ids, avfc->nb_surfaces,
487 if (vas != VA_STATUS_SUCCESS) {
488 av_log(ctx, AV_LOG_ERROR, "Failed to create decode pipeline "
489 "context: %d (%s).\n", vas, vaErrorStr(vas));
490 err = AVERROR(EINVAL);
494 av_log(ctx, AV_LOG_DEBUG, "VAAPI decoder (re)init complete.\n");
496 // We would like to set this on the AVCodecContext for use by whoever gets
497 // the frames from the decoder, but unfortunately the AVCodecContext we
498 // have here need not be the "real" one (H.264 makes many copies for
499 // threading purposes). To avoid the problem, we instead store it in the
500 // InputStream and propagate it from there.
501 ist->hw_frames_ctx = av_buffer_ref(ctx->frames_ref);
502 if (!ist->hw_frames_ctx) {
503 err = AVERROR(ENOMEM);
507 ist->hwaccel_ctx = ctx;
508 ist->hwaccel_uninit = vaapi_decode_uninit;
509 ist->hwaccel_get_buffer = vaapi_get_buffer;
510 ist->hwaccel_retrieve_data = vaapi_retrieve_data;
512 ctx->decoder_vaapi_context.display = hwctx->display;
513 ctx->decoder_vaapi_context.config_id = ctx->va_config;
514 ctx->decoder_vaapi_context.context_id = ctx->va_context;
515 avctx->hwaccel_context = &ctx->decoder_vaapi_context;
520 vaapi_decode_uninit(avctx);
524 static AVClass *vaapi_log = &vaapi_class;
526 av_cold int vaapi_device_init(const char *device)
530 err = av_hwdevice_ctx_create(&hw_device_ctx, AV_HWDEVICE_TYPE_VAAPI,
533 av_log(&vaapi_log, AV_LOG_ERROR, "Failed to create a VAAPI device\n");