]> git.sesse.net Git - ffmpeg/blob - libavcodec/vaapi_decode.c
configure: Use pkgconfig for VAAPI
[ffmpeg] / libavcodec / vaapi_decode.c
1 /*
2  * This file is part of FFmpeg.
3  *
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.
8  *
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.
13  *
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
17  */
18
19 #include "libavutil/avassert.h"
20 #include "libavutil/common.h"
21 #include "libavutil/pixdesc.h"
22
23 #include "avcodec.h"
24 #include "decode.h"
25 #include "internal.h"
26 #include "vaapi_decode.h"
27
28
29 int ff_vaapi_decode_make_param_buffer(AVCodecContext *avctx,
30                                       VAAPIDecodePicture *pic,
31                                       int type,
32                                       const void *data,
33                                       size_t size)
34 {
35     VAAPIDecodeContext *ctx = avctx->internal->hwaccel_priv_data;
36     VAStatus vas;
37     VABufferID buffer;
38
39     av_assert0(pic->nb_param_buffers + 1 <= MAX_PARAM_BUFFERS);
40
41     vas = vaCreateBuffer(ctx->hwctx->display, ctx->va_context,
42                          type, size, 1, (void*)data, &buffer);
43     if (vas != VA_STATUS_SUCCESS) {
44         av_log(avctx, AV_LOG_ERROR, "Failed to create parameter "
45                "buffer (type %d): %d (%s).\n",
46                type, vas, vaErrorStr(vas));
47         return AVERROR(EIO);
48     }
49
50     pic->param_buffers[pic->nb_param_buffers++] = buffer;
51
52     av_log(avctx, AV_LOG_DEBUG, "Param buffer (type %d, %zu bytes) "
53            "is %#x.\n", type, size, buffer);
54     return 0;
55 }
56
57
58 int ff_vaapi_decode_make_slice_buffer(AVCodecContext *avctx,
59                                       VAAPIDecodePicture *pic,
60                                       const void *params_data,
61                                       size_t params_size,
62                                       const void *slice_data,
63                                       size_t slice_size)
64 {
65     VAAPIDecodeContext *ctx = avctx->internal->hwaccel_priv_data;
66     VAStatus vas;
67     int index;
68
69     av_assert0(pic->nb_slices <= pic->slices_allocated);
70     if (pic->nb_slices == pic->slices_allocated) {
71         if (pic->slices_allocated > 0)
72             pic->slices_allocated *= 2;
73         else
74             pic->slices_allocated = 64;
75
76         pic->slice_buffers =
77             av_realloc_array(pic->slice_buffers,
78                              pic->slices_allocated,
79                              2 * sizeof(*pic->slice_buffers));
80         if (!pic->slice_buffers)
81             return AVERROR(ENOMEM);
82     }
83     av_assert0(pic->nb_slices + 1 <= pic->slices_allocated);
84
85     index = 2 * pic->nb_slices;
86
87     vas = vaCreateBuffer(ctx->hwctx->display, ctx->va_context,
88                          VASliceParameterBufferType,
89                          params_size, 1, (void*)params_data,
90                          &pic->slice_buffers[index]);
91     if (vas != VA_STATUS_SUCCESS) {
92         av_log(avctx, AV_LOG_ERROR, "Failed to create slice "
93                "parameter buffer: %d (%s).\n", vas, vaErrorStr(vas));
94         return AVERROR(EIO);
95     }
96
97     av_log(avctx, AV_LOG_DEBUG, "Slice %d param buffer (%zu bytes) "
98            "is %#x.\n", pic->nb_slices, params_size,
99            pic->slice_buffers[index]);
100
101     vas = vaCreateBuffer(ctx->hwctx->display, ctx->va_context,
102                          VASliceDataBufferType,
103                          slice_size, 1, (void*)slice_data,
104                          &pic->slice_buffers[index + 1]);
105     if (vas != VA_STATUS_SUCCESS) {
106         av_log(avctx, AV_LOG_ERROR, "Failed to create slice "
107                "data buffer (size %zu): %d (%s).\n",
108                slice_size, vas, vaErrorStr(vas));
109         vaDestroyBuffer(ctx->hwctx->display,
110                         pic->slice_buffers[index]);
111         return AVERROR(EIO);
112     }
113
114     av_log(avctx, AV_LOG_DEBUG, "Slice %d data buffer (%zu bytes) "
115            "is %#x.\n", pic->nb_slices, slice_size,
116            pic->slice_buffers[index + 1]);
117
118     ++pic->nb_slices;
119     return 0;
120 }
121
122 static void ff_vaapi_decode_destroy_buffers(AVCodecContext *avctx,
123                                             VAAPIDecodePicture *pic)
124 {
125     VAAPIDecodeContext *ctx = avctx->internal->hwaccel_priv_data;
126     VAStatus vas;
127     int i;
128
129     for (i = 0; i < pic->nb_param_buffers; i++) {
130         vas = vaDestroyBuffer(ctx->hwctx->display,
131                               pic->param_buffers[i]);
132         if (vas != VA_STATUS_SUCCESS) {
133             av_log(avctx, AV_LOG_ERROR, "Failed to destroy "
134                    "parameter buffer %#x: %d (%s).\n",
135                    pic->param_buffers[i], vas, vaErrorStr(vas));
136         }
137     }
138
139     for (i = 0; i < 2 * pic->nb_slices; i++) {
140         vas = vaDestroyBuffer(ctx->hwctx->display,
141                               pic->slice_buffers[i]);
142         if (vas != VA_STATUS_SUCCESS) {
143             av_log(avctx, AV_LOG_ERROR, "Failed to destroy slice "
144                    "slice buffer %#x: %d (%s).\n",
145                    pic->slice_buffers[i], vas, vaErrorStr(vas));
146         }
147     }
148 }
149
150 int ff_vaapi_decode_issue(AVCodecContext *avctx,
151                           VAAPIDecodePicture *pic)
152 {
153     VAAPIDecodeContext *ctx = avctx->internal->hwaccel_priv_data;
154     VAStatus vas;
155     int err;
156
157     av_log(avctx, AV_LOG_DEBUG, "Decode to surface %#x.\n",
158            pic->output_surface);
159
160     vas = vaBeginPicture(ctx->hwctx->display, ctx->va_context,
161                          pic->output_surface);
162     if (vas != VA_STATUS_SUCCESS) {
163         av_log(avctx, AV_LOG_ERROR, "Failed to begin picture decode "
164                "issue: %d (%s).\n", vas, vaErrorStr(vas));
165         err = AVERROR(EIO);
166         goto fail_with_picture;
167     }
168
169     vas = vaRenderPicture(ctx->hwctx->display, ctx->va_context,
170                           pic->param_buffers, pic->nb_param_buffers);
171     if (vas != VA_STATUS_SUCCESS) {
172         av_log(avctx, AV_LOG_ERROR, "Failed to upload decode "
173                "parameters: %d (%s).\n", vas, vaErrorStr(vas));
174         err = AVERROR(EIO);
175         goto fail_with_picture;
176     }
177
178     vas = vaRenderPicture(ctx->hwctx->display, ctx->va_context,
179                           pic->slice_buffers, 2 * pic->nb_slices);
180     if (vas != VA_STATUS_SUCCESS) {
181         av_log(avctx, AV_LOG_ERROR, "Failed to upload slices: "
182                "%d (%s).\n", vas, vaErrorStr(vas));
183         err = AVERROR(EIO);
184         goto fail_with_picture;
185     }
186
187     vas = vaEndPicture(ctx->hwctx->display, ctx->va_context);
188     if (vas != VA_STATUS_SUCCESS) {
189         av_log(avctx, AV_LOG_ERROR, "Failed to end picture decode "
190                "issue: %d (%s).\n", vas, vaErrorStr(vas));
191         err = AVERROR(EIO);
192         if (CONFIG_VAAPI_1 || ctx->hwctx->driver_quirks &
193             AV_VAAPI_DRIVER_QUIRK_RENDER_PARAM_BUFFERS)
194             goto fail;
195         else
196             goto fail_at_end;
197     }
198
199     if (CONFIG_VAAPI_1 || ctx->hwctx->driver_quirks &
200         AV_VAAPI_DRIVER_QUIRK_RENDER_PARAM_BUFFERS)
201         ff_vaapi_decode_destroy_buffers(avctx, pic);
202
203     pic->nb_param_buffers = 0;
204     pic->nb_slices        = 0;
205     pic->slices_allocated = 0;
206     av_freep(&pic->slice_buffers);
207
208     return 0;
209
210 fail_with_picture:
211     vas = vaEndPicture(ctx->hwctx->display, ctx->va_context);
212     if (vas != VA_STATUS_SUCCESS) {
213         av_log(avctx, AV_LOG_ERROR, "Failed to end picture decode "
214                "after error: %d (%s).\n", vas, vaErrorStr(vas));
215     }
216 fail:
217     ff_vaapi_decode_destroy_buffers(avctx, pic);
218 fail_at_end:
219     return err;
220 }
221
222 int ff_vaapi_decode_cancel(AVCodecContext *avctx,
223                            VAAPIDecodePicture *pic)
224 {
225     ff_vaapi_decode_destroy_buffers(avctx, pic);
226
227     pic->nb_param_buffers = 0;
228     pic->nb_slices        = 0;
229     pic->slices_allocated = 0;
230     av_freep(&pic->slice_buffers);
231
232     return 0;
233 }
234
235 static const struct {
236     uint32_t fourcc;
237     enum AVPixelFormat pix_fmt;
238 } vaapi_format_map[] = {
239 #define MAP(va, av) { VA_FOURCC_ ## va, AV_PIX_FMT_ ## av }
240     // 4:0:0
241     MAP(Y800, GRAY8),
242     // 4:2:0
243     MAP(NV12, NV12),
244     MAP(YV12, YUV420P),
245     MAP(IYUV, YUV420P),
246 #ifdef VA_FOURCC_I420
247     MAP(I420, YUV420P),
248 #endif
249     MAP(IMC3, YUV420P),
250     // 4:1:1
251     MAP(411P, YUV411P),
252     // 4:2:2
253     MAP(422H, YUV422P),
254 #ifdef VA_FOURCC_YV16
255     MAP(YV16, YUV422P),
256 #endif
257     // 4:4:0
258     MAP(422V, YUV440P),
259     // 4:4:4
260     MAP(444P, YUV444P),
261     // 4:2:0 10-bit
262 #ifdef VA_FOURCC_P010
263     MAP(P010, P010),
264 #endif
265 #ifdef VA_FOURCC_I010
266     MAP(I010, YUV420P10),
267 #endif
268 #undef MAP
269 };
270
271 static int vaapi_decode_find_best_format(AVCodecContext *avctx,
272                                          AVHWDeviceContext *device,
273                                          VAConfigID config_id,
274                                          AVHWFramesContext *frames)
275 {
276     AVVAAPIDeviceContext *hwctx = device->hwctx;
277     VAStatus vas;
278     VASurfaceAttrib *attr;
279     enum AVPixelFormat source_format, best_format, format;
280     uint32_t best_fourcc, fourcc;
281     int i, j, nb_attr;
282
283     source_format = avctx->sw_pix_fmt;
284     av_assert0(source_format != AV_PIX_FMT_NONE);
285
286     vas = vaQuerySurfaceAttributes(hwctx->display, config_id,
287                                    NULL, &nb_attr);
288     if (vas != VA_STATUS_SUCCESS) {
289         av_log(avctx, AV_LOG_ERROR, "Failed to query surface attributes: "
290                "%d (%s).\n", vas, vaErrorStr(vas));
291         return AVERROR(ENOSYS);
292     }
293
294     attr = av_malloc_array(nb_attr, sizeof(*attr));
295     if (!attr)
296         return AVERROR(ENOMEM);
297
298     vas = vaQuerySurfaceAttributes(hwctx->display, config_id,
299                                    attr, &nb_attr);
300     if (vas != VA_STATUS_SUCCESS) {
301         av_log(avctx, AV_LOG_ERROR, "Failed to query surface attributes: "
302                "%d (%s).\n", vas, vaErrorStr(vas));
303         av_freep(&attr);
304         return AVERROR(ENOSYS);
305     }
306
307     best_format = AV_PIX_FMT_NONE;
308
309     for (i = 0; i < nb_attr; i++) {
310         if (attr[i].type != VASurfaceAttribPixelFormat)
311             continue;
312
313         fourcc = attr[i].value.value.i;
314         for (j = 0; j < FF_ARRAY_ELEMS(vaapi_format_map); j++) {
315             if (fourcc == vaapi_format_map[j].fourcc)
316                 break;
317         }
318         if (j >= FF_ARRAY_ELEMS(vaapi_format_map)) {
319             av_log(avctx, AV_LOG_DEBUG, "Ignoring unknown format %#x.\n",
320                    fourcc);
321             continue;
322         }
323         format = vaapi_format_map[j].pix_fmt;
324         av_log(avctx, AV_LOG_DEBUG, "Considering format %#x -> %s.\n",
325                fourcc, av_get_pix_fmt_name(format));
326
327         best_format = av_find_best_pix_fmt_of_2(format, best_format,
328                                                 source_format, 0, NULL);
329         if (format == best_format)
330             best_fourcc = fourcc;
331     }
332
333     av_freep(&attr);
334
335     if (best_format == AV_PIX_FMT_NONE) {
336         av_log(avctx, AV_LOG_ERROR, "No usable formats for decoding!\n");
337         return AVERROR(EINVAL);
338     }
339
340     av_log(avctx, AV_LOG_DEBUG, "Picked %s (%#x) as best match for %s.\n",
341            av_get_pix_fmt_name(best_format), best_fourcc,
342            av_get_pix_fmt_name(source_format));
343
344     frames->sw_format = best_format;
345     if (avctx->internal->hwaccel_priv_data) {
346         VAAPIDecodeContext    *ctx = avctx->internal->hwaccel_priv_data;
347         AVVAAPIFramesContext *avfc = frames->hwctx;
348
349         ctx->pixel_format_attribute = (VASurfaceAttrib) {
350             .type          = VASurfaceAttribPixelFormat,
351             .value.value.i = best_fourcc,
352         };
353
354         avfc->attributes    = &ctx->pixel_format_attribute;
355         avfc->nb_attributes = 1;
356     }
357
358     return 0;
359 }
360
361 static const struct {
362     enum AVCodecID codec_id;
363     int codec_profile;
364     VAProfile va_profile;
365 } vaapi_profile_map[] = {
366 #define MAP(c, p, v) { AV_CODEC_ID_ ## c, FF_PROFILE_ ## p, VAProfile ## v }
367     MAP(MPEG2VIDEO,  MPEG2_SIMPLE,    MPEG2Simple ),
368     MAP(MPEG2VIDEO,  MPEG2_MAIN,      MPEG2Main   ),
369     MAP(H263,        UNKNOWN,         H263Baseline),
370     MAP(MPEG4,       MPEG4_SIMPLE,    MPEG4Simple ),
371     MAP(MPEG4,       MPEG4_ADVANCED_SIMPLE,
372                                MPEG4AdvancedSimple),
373     MAP(MPEG4,       MPEG4_MAIN,      MPEG4Main   ),
374     MAP(H264,        H264_CONSTRAINED_BASELINE,
375                            H264ConstrainedBaseline),
376     MAP(H264,        H264_MAIN,       H264Main    ),
377     MAP(H264,        H264_HIGH,       H264High    ),
378 #if VA_CHECK_VERSION(0, 37, 0)
379     MAP(HEVC,        HEVC_MAIN,       HEVCMain    ),
380     MAP(HEVC,        HEVC_MAIN_10,    HEVCMain10  ),
381 #endif
382     MAP(MJPEG,       MJPEG_HUFFMAN_BASELINE_DCT,
383                                       JPEGBaseline),
384     MAP(WMV3,        VC1_SIMPLE,      VC1Simple   ),
385     MAP(WMV3,        VC1_MAIN,        VC1Main     ),
386     MAP(WMV3,        VC1_COMPLEX,     VC1Advanced ),
387     MAP(WMV3,        VC1_ADVANCED,    VC1Advanced ),
388     MAP(VC1,         VC1_SIMPLE,      VC1Simple   ),
389     MAP(VC1,         VC1_MAIN,        VC1Main     ),
390     MAP(VC1,         VC1_COMPLEX,     VC1Advanced ),
391     MAP(VC1,         VC1_ADVANCED,    VC1Advanced ),
392     MAP(VP8,         UNKNOWN,       VP8Version0_3 ),
393 #if VA_CHECK_VERSION(0, 38, 0)
394     MAP(VP9,         VP9_0,           VP9Profile0 ),
395 #endif
396 #if VA_CHECK_VERSION(0, 39, 0)
397     MAP(VP9,         VP9_2,           VP9Profile2 ),
398 #endif
399 #undef MAP
400 };
401
402 /*
403  * Set *va_config and the frames_ref fields from the current codec parameters
404  * in avctx.
405  */
406 static int vaapi_decode_make_config(AVCodecContext *avctx,
407                                     AVBufferRef *device_ref,
408                                     VAConfigID *va_config,
409                                     AVBufferRef *frames_ref)
410 {
411     AVVAAPIHWConfig       *hwconfig    = NULL;
412     AVHWFramesConstraints *constraints = NULL;
413     VAStatus vas;
414     int err, i, j;
415     const AVCodecDescriptor *codec_desc;
416     VAProfile *profile_list = NULL, matched_va_profile;
417     int profile_count, exact_match, matched_ff_profile;
418
419     AVHWDeviceContext    *device = (AVHWDeviceContext*)device_ref->data;
420     AVVAAPIDeviceContext *hwctx = device->hwctx;
421
422     codec_desc = avcodec_descriptor_get(avctx->codec_id);
423     if (!codec_desc) {
424         err = AVERROR(EINVAL);
425         goto fail;
426     }
427
428     profile_count = vaMaxNumProfiles(hwctx->display);
429     profile_list  = av_malloc_array(profile_count,
430                                     sizeof(VAProfile));
431     if (!profile_list) {
432         err = AVERROR(ENOMEM);
433         goto fail;
434     }
435
436     vas = vaQueryConfigProfiles(hwctx->display,
437                                 profile_list, &profile_count);
438     if (vas != VA_STATUS_SUCCESS) {
439         av_log(avctx, AV_LOG_ERROR, "Failed to query profiles: "
440                "%d (%s).\n", vas, vaErrorStr(vas));
441         err = AVERROR(ENOSYS);
442         goto fail;
443     }
444
445     matched_va_profile = VAProfileNone;
446     exact_match = 0;
447
448     for (i = 0; i < FF_ARRAY_ELEMS(vaapi_profile_map); i++) {
449         int profile_match = 0;
450         if (avctx->codec_id != vaapi_profile_map[i].codec_id)
451             continue;
452         if (avctx->profile == vaapi_profile_map[i].codec_profile ||
453             vaapi_profile_map[i].codec_profile == FF_PROFILE_UNKNOWN)
454             profile_match = 1;
455         for (j = 0; j < profile_count; j++) {
456             if (vaapi_profile_map[i].va_profile == profile_list[j]) {
457                 exact_match = profile_match;
458                 break;
459             }
460         }
461         if (j < profile_count) {
462             matched_va_profile = vaapi_profile_map[i].va_profile;
463             matched_ff_profile = vaapi_profile_map[i].codec_profile;
464             if (exact_match)
465                 break;
466         }
467     }
468     av_freep(&profile_list);
469
470     if (matched_va_profile == VAProfileNone) {
471         av_log(avctx, AV_LOG_ERROR, "No support for codec %s "
472                "profile %d.\n", codec_desc->name, avctx->profile);
473         err = AVERROR(ENOSYS);
474         goto fail;
475     }
476     if (!exact_match) {
477         if (avctx->hwaccel_flags &
478             AV_HWACCEL_FLAG_ALLOW_PROFILE_MISMATCH) {
479             av_log(avctx, AV_LOG_VERBOSE, "Codec %s profile %d not "
480                    "supported for hardware decode.\n",
481                    codec_desc->name, avctx->profile);
482             av_log(avctx, AV_LOG_WARNING, "Using possibly-"
483                    "incompatible profile %d instead.\n",
484                    matched_ff_profile);
485         } else {
486             av_log(avctx, AV_LOG_VERBOSE, "Codec %s profile %d not "
487                    "supported for hardware decode.\n",
488                    codec_desc->name, avctx->profile);
489             err = AVERROR(EINVAL);
490             goto fail;
491         }
492     }
493
494     vas = vaCreateConfig(hwctx->display, matched_va_profile,
495                          VAEntrypointVLD, NULL, 0,
496                          va_config);
497     if (vas != VA_STATUS_SUCCESS) {
498         av_log(avctx, AV_LOG_ERROR, "Failed to create decode "
499                "configuration: %d (%s).\n", vas, vaErrorStr(vas));
500         err = AVERROR(EIO);
501         goto fail;
502     }
503
504     hwconfig = av_hwdevice_hwconfig_alloc(device_ref);
505     if (!hwconfig) {
506         err = AVERROR(ENOMEM);
507         goto fail;
508     }
509     hwconfig->config_id = *va_config;
510
511     constraints =
512         av_hwdevice_get_hwframe_constraints(device_ref, hwconfig);
513     if (!constraints) {
514         err = AVERROR(ENOMEM);
515         goto fail;
516     }
517
518     if (avctx->coded_width  < constraints->min_width  ||
519         avctx->coded_height < constraints->min_height ||
520         avctx->coded_width  > constraints->max_width  ||
521         avctx->coded_height > constraints->max_height) {
522         av_log(avctx, AV_LOG_ERROR, "Hardware does not support image "
523                "size %dx%d (constraints: width %d-%d height %d-%d).\n",
524                avctx->coded_width, avctx->coded_height,
525                constraints->min_width,  constraints->max_width,
526                constraints->min_height, constraints->max_height);
527         err = AVERROR(EINVAL);
528         goto fail;
529     }
530     if (!constraints->valid_sw_formats ||
531         constraints->valid_sw_formats[0] == AV_PIX_FMT_NONE) {
532         av_log(avctx, AV_LOG_ERROR, "Hardware does not offer any "
533                "usable surface formats.\n");
534         err = AVERROR(EINVAL);
535         goto fail;
536     }
537
538     if (frames_ref) {
539         AVHWFramesContext *frames = (AVHWFramesContext *)frames_ref->data;
540
541         frames->format = AV_PIX_FMT_VAAPI;
542         frames->width = avctx->coded_width;
543         frames->height = avctx->coded_height;
544
545         err = vaapi_decode_find_best_format(avctx, device,
546                                             *va_config, frames);
547         if (err < 0)
548             goto fail;
549
550         frames->initial_pool_size = 1;
551         // Add per-codec number of surfaces used for storing reference frames.
552         switch (avctx->codec_id) {
553         case AV_CODEC_ID_H264:
554         case AV_CODEC_ID_HEVC:
555             frames->initial_pool_size += 16;
556             break;
557         case AV_CODEC_ID_VP9:
558             frames->initial_pool_size += 8;
559             break;
560         case AV_CODEC_ID_VP8:
561             frames->initial_pool_size += 3;
562             break;
563         default:
564             frames->initial_pool_size += 2;
565         }
566     }
567
568     av_hwframe_constraints_free(&constraints);
569     av_freep(&hwconfig);
570
571     return 0;
572
573 fail:
574     av_hwframe_constraints_free(&constraints);
575     av_freep(&hwconfig);
576     if (*va_config != VA_INVALID_ID) {
577         vaDestroyConfig(hwctx->display, *va_config);
578         *va_config = VA_INVALID_ID;
579     }
580     av_freep(&profile_list);
581     return err;
582 }
583
584 int ff_vaapi_common_frame_params(AVCodecContext *avctx,
585                                  AVBufferRef *hw_frames_ctx)
586 {
587     AVHWFramesContext *hw_frames = (AVHWFramesContext *)hw_frames_ctx->data;
588     AVHWDeviceContext *device_ctx = hw_frames->device_ctx;
589     AVVAAPIDeviceContext *hwctx;
590     VAConfigID va_config = VA_INVALID_ID;
591     int err;
592
593     if (device_ctx->type != AV_HWDEVICE_TYPE_VAAPI)
594         return AVERROR(EINVAL);
595     hwctx = device_ctx->hwctx;
596
597     err = vaapi_decode_make_config(avctx, hw_frames->device_ref, &va_config,
598                                    hw_frames_ctx);
599     if (err)
600         return err;
601
602     if (va_config != VA_INVALID_ID)
603         vaDestroyConfig(hwctx->display, va_config);
604
605     return 0;
606 }
607
608 int ff_vaapi_decode_init(AVCodecContext *avctx)
609 {
610     VAAPIDecodeContext *ctx = avctx->internal->hwaccel_priv_data;
611     VAStatus vas;
612     int err;
613
614     ctx->va_config  = VA_INVALID_ID;
615     ctx->va_context = VA_INVALID_ID;
616
617 #if FF_API_STRUCT_VAAPI_CONTEXT
618     if (avctx->hwaccel_context) {
619         av_log(avctx, AV_LOG_WARNING, "Using deprecated struct "
620                "vaapi_context in decode.\n");
621
622         ctx->have_old_context = 1;
623         ctx->old_context = avctx->hwaccel_context;
624
625         // Really we only want the VAAPI device context, but this
626         // allocates a whole generic device context because we don't
627         // have any other way to determine how big it should be.
628         ctx->device_ref =
629             av_hwdevice_ctx_alloc(AV_HWDEVICE_TYPE_VAAPI);
630         if (!ctx->device_ref) {
631             err = AVERROR(ENOMEM);
632             goto fail;
633         }
634         ctx->device = (AVHWDeviceContext*)ctx->device_ref->data;
635         ctx->hwctx  = ctx->device->hwctx;
636
637         ctx->hwctx->display = ctx->old_context->display;
638
639         // The old VAAPI decode setup assumed this quirk was always
640         // present, so set it here to avoid the behaviour changing.
641         ctx->hwctx->driver_quirks =
642             AV_VAAPI_DRIVER_QUIRK_RENDER_PARAM_BUFFERS;
643
644     }
645 #endif
646
647 #if FF_API_STRUCT_VAAPI_CONTEXT
648     if (ctx->have_old_context) {
649         ctx->va_config  = ctx->old_context->config_id;
650         ctx->va_context = ctx->old_context->context_id;
651
652         av_log(avctx, AV_LOG_DEBUG, "Using user-supplied decoder "
653                "context: %#x/%#x.\n", ctx->va_config, ctx->va_context);
654     } else {
655 #endif
656
657     err = ff_decode_get_hw_frames_ctx(avctx, AV_HWDEVICE_TYPE_VAAPI);
658     if (err < 0)
659         goto fail;
660
661     ctx->frames = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
662     ctx->hwfc   = ctx->frames->hwctx;
663     ctx->device = ctx->frames->device_ctx;
664     ctx->hwctx  = ctx->device->hwctx;
665
666     err = vaapi_decode_make_config(avctx, ctx->frames->device_ref,
667                                    &ctx->va_config, avctx->hw_frames_ctx);
668     if (err)
669         goto fail;
670
671     vas = vaCreateContext(ctx->hwctx->display, ctx->va_config,
672                           avctx->coded_width, avctx->coded_height,
673                           VA_PROGRESSIVE,
674                           ctx->hwfc->surface_ids,
675                           ctx->hwfc->nb_surfaces,
676                           &ctx->va_context);
677     if (vas != VA_STATUS_SUCCESS) {
678         av_log(avctx, AV_LOG_ERROR, "Failed to create decode "
679                "context: %d (%s).\n", vas, vaErrorStr(vas));
680         err = AVERROR(EIO);
681         goto fail;
682     }
683
684     av_log(avctx, AV_LOG_DEBUG, "Decode context initialised: "
685            "%#x/%#x.\n", ctx->va_config, ctx->va_context);
686 #if FF_API_STRUCT_VAAPI_CONTEXT
687     }
688 #endif
689
690     return 0;
691
692 fail:
693     ff_vaapi_decode_uninit(avctx);
694     return err;
695 }
696
697 int ff_vaapi_decode_uninit(AVCodecContext *avctx)
698 {
699     VAAPIDecodeContext *ctx = avctx->internal->hwaccel_priv_data;
700     VAStatus vas;
701
702 #if FF_API_STRUCT_VAAPI_CONTEXT
703     if (ctx->have_old_context) {
704         av_buffer_unref(&ctx->device_ref);
705     } else {
706 #endif
707
708     if (ctx->va_context != VA_INVALID_ID) {
709         vas = vaDestroyContext(ctx->hwctx->display, ctx->va_context);
710         if (vas != VA_STATUS_SUCCESS) {
711             av_log(avctx, AV_LOG_ERROR, "Failed to destroy decode "
712                    "context %#x: %d (%s).\n",
713                    ctx->va_context, vas, vaErrorStr(vas));
714         }
715     }
716     if (ctx->va_config != VA_INVALID_ID) {
717         vas = vaDestroyConfig(ctx->hwctx->display, ctx->va_config);
718         if (vas != VA_STATUS_SUCCESS) {
719             av_log(avctx, AV_LOG_ERROR, "Failed to destroy decode "
720                    "configuration %#x: %d (%s).\n",
721                    ctx->va_config, vas, vaErrorStr(vas));
722         }
723     }
724
725 #if FF_API_STRUCT_VAAPI_CONTEXT
726     }
727 #endif
728
729     return 0;
730 }