dxva: add declarative profile checks
[ffmpeg.git] / libavcodec / dxva2.c
1 /*
2  * DXVA2 HW acceleration.
3  *
4  * copyright (c) 2010 Laurent Aimar
5  *
6  * This file is part of FFmpeg.
7  *
8  * FFmpeg is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Lesser General Public
10  * License as published by the Free Software Foundation; either
11  * version 2.1 of the License, or (at your option) any later version.
12  *
13  * FFmpeg is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Lesser General Public License for more details.
17  *
18  * You should have received a copy of the GNU Lesser General Public
19  * License along with FFmpeg; if not, write to the Free Software
20  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21  */
22
23 #include <assert.h>
24 #include <string.h>
25 #include <initguid.h>
26
27 #include "libavutil/common.h"
28 #include "libavutil/log.h"
29 #include "libavutil/time.h"
30
31 #include "avcodec.h"
32 #include "dxva2_internal.h"
33
34 /* define all the GUIDs used directly here,
35  to avoid problems with inconsistent dxva2api.h versions in mingw-w64 and different MSVC version */
36 DEFINE_GUID(ff_DXVA2_ModeMPEG2_VLD,      0xee27417f, 0x5e28,0x4e65,0xbe,0xea,0x1d,0x26,0xb5,0x08,0xad,0xc9);
37 DEFINE_GUID(ff_DXVA2_ModeMPEG2and1_VLD,  0x86695f12, 0x340e,0x4f04,0x9f,0xd3,0x92,0x53,0xdd,0x32,0x74,0x60);
38 DEFINE_GUID(ff_DXVA2_ModeH264_E,         0x1b81be68, 0xa0c7,0x11d3,0xb9,0x84,0x00,0xc0,0x4f,0x2e,0x73,0xc5);
39 DEFINE_GUID(ff_DXVA2_ModeH264_F,         0x1b81be69, 0xa0c7,0x11d3,0xb9,0x84,0x00,0xc0,0x4f,0x2e,0x73,0xc5);
40 DEFINE_GUID(ff_DXVADDI_Intel_ModeH264_E, 0x604F8E68, 0x4951,0x4C54,0x88,0xFE,0xAB,0xD2,0x5C,0x15,0xB3,0xD6);
41 DEFINE_GUID(ff_DXVA2_ModeVC1_D,          0x1b81beA3, 0xa0c7,0x11d3,0xb9,0x84,0x00,0xc0,0x4f,0x2e,0x73,0xc5);
42 DEFINE_GUID(ff_DXVA2_ModeVC1_D2010,      0x1b81beA4, 0xa0c7,0x11d3,0xb9,0x84,0x00,0xc0,0x4f,0x2e,0x73,0xc5);
43 DEFINE_GUID(ff_DXVA2_ModeHEVC_VLD_Main,  0x5b11d51b, 0x2f4c,0x4452,0xbc,0xc3,0x09,0xf2,0xa1,0x16,0x0c,0xc0);
44 DEFINE_GUID(ff_DXVA2_ModeHEVC_VLD_Main10,0x107af0e0, 0xef1a,0x4d19,0xab,0xa8,0x67,0xa1,0x63,0x07,0x3d,0x13);
45 DEFINE_GUID(ff_DXVA2_ModeVP9_VLD_Profile0,0x463707f8,0xa1d0,0x4585,0x87,0x6d,0x83,0xaa,0x6d,0x60,0xb8,0x9e);
46 DEFINE_GUID(ff_DXVA2_NoEncrypt,          0x1b81beD0, 0xa0c7,0x11d3,0xb9,0x84,0x00,0xc0,0x4f,0x2e,0x73,0xc5);
47 DEFINE_GUID(ff_GUID_NULL,                0x00000000, 0x0000,0x0000,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00);
48 DEFINE_GUID(ff_IID_IDirectXVideoDecoderService, 0xfc51a551,0xd5e7,0x11d9,0xaf,0x55,0x00,0x05,0x4e,0x43,0xff,0x02);
49
50 typedef struct dxva_mode {
51     const GUID     *guid;
52     enum AVCodecID codec;
53     // List of supported profiles, terminated by a FF_PROFILE_UNKNOWN entry.
54     // If NULL, don't check profile.
55     const int      *profiles;
56 } dxva_mode;
57
58 static const int prof_mpeg2_main[]   = {FF_PROFILE_MPEG2_SIMPLE,
59                                         FF_PROFILE_MPEG2_MAIN,
60                                         FF_PROFILE_UNKNOWN};
61 static const int prof_h264_high[]    = {FF_PROFILE_H264_CONSTRAINED_BASELINE,
62                                         FF_PROFILE_H264_MAIN,
63                                         FF_PROFILE_H264_HIGH,
64                                         FF_PROFILE_UNKNOWN};
65 static const int prof_hevc_main[]    = {FF_PROFILE_HEVC_MAIN,
66                                         FF_PROFILE_UNKNOWN};
67 static const int prof_hevc_main10[]  = {FF_PROFILE_HEVC_MAIN,
68                                         FF_PROFILE_HEVC_MAIN_10,
69                                         FF_PROFILE_UNKNOWN};
70
71 static const dxva_mode dxva_modes[] = {
72     /* MPEG-2 */
73     { &ff_DXVA2_ModeMPEG2_VLD,       AV_CODEC_ID_MPEG2VIDEO, prof_mpeg2_main },
74     { &ff_DXVA2_ModeMPEG2and1_VLD,   AV_CODEC_ID_MPEG2VIDEO, prof_mpeg2_main },
75
76     /* H.264 */
77     { &ff_DXVA2_ModeH264_F,          AV_CODEC_ID_H264, prof_h264_high },
78     { &ff_DXVA2_ModeH264_E,          AV_CODEC_ID_H264, prof_h264_high },
79     /* Intel specific H.264 mode */
80     { &ff_DXVADDI_Intel_ModeH264_E,  AV_CODEC_ID_H264, prof_h264_high },
81
82     /* VC-1 / WMV3 */
83     { &ff_DXVA2_ModeVC1_D2010,       AV_CODEC_ID_VC1 },
84     { &ff_DXVA2_ModeVC1_D2010,       AV_CODEC_ID_WMV3 },
85     { &ff_DXVA2_ModeVC1_D,           AV_CODEC_ID_VC1 },
86     { &ff_DXVA2_ModeVC1_D,           AV_CODEC_ID_WMV3 },
87
88     /* HEVC/H.265 */
89     { &ff_DXVA2_ModeHEVC_VLD_Main10, AV_CODEC_ID_HEVC, prof_hevc_main10 },
90     { &ff_DXVA2_ModeHEVC_VLD_Main,   AV_CODEC_ID_HEVC, prof_hevc_main },
91
92     /* VP8/9 */
93     { &ff_DXVA2_ModeVP9_VLD_Profile0,AV_CODEC_ID_VP9 },
94
95     { NULL,                          0 },
96 };
97
98 static int dxva_get_decoder_configuration(AVCodecContext *avctx,
99                                           const void *cfg_list,
100                                           unsigned cfg_count)
101 {
102     FFDXVASharedContext *sctx = DXVA_SHARED_CONTEXT(avctx);
103     unsigned i, best_score = 0;
104     int best_cfg = -1;
105
106     for (i = 0; i < cfg_count; i++) {
107         unsigned score;
108         UINT ConfigBitstreamRaw;
109         GUID guidConfigBitstreamEncryption;
110
111 #if CONFIG_D3D11VA
112         if (sctx->pix_fmt == AV_PIX_FMT_D3D11) {
113             D3D11_VIDEO_DECODER_CONFIG *cfg = &((D3D11_VIDEO_DECODER_CONFIG *)cfg_list)[i];
114             ConfigBitstreamRaw = cfg->ConfigBitstreamRaw;
115             guidConfigBitstreamEncryption = cfg->guidConfigBitstreamEncryption;
116         }
117 #endif
118 #if CONFIG_DXVA2
119         if (sctx->pix_fmt == AV_PIX_FMT_DXVA2_VLD) {
120             DXVA2_ConfigPictureDecode *cfg = &((DXVA2_ConfigPictureDecode *)cfg_list)[i];
121             ConfigBitstreamRaw = cfg->ConfigBitstreamRaw;
122             guidConfigBitstreamEncryption = cfg->guidConfigBitstreamEncryption;
123         }
124 #endif
125
126         if (ConfigBitstreamRaw == 1)
127             score = 1;
128         else if (avctx->codec_id == AV_CODEC_ID_H264 && ConfigBitstreamRaw == 2)
129             score = 2;
130         else
131             continue;
132         if (IsEqualGUID(&guidConfigBitstreamEncryption, &ff_DXVA2_NoEncrypt))
133             score += 16;
134         if (score > best_score) {
135             best_score = score;
136             best_cfg = i;
137         }
138     }
139
140     if (!best_score) {
141         av_log(avctx, AV_LOG_VERBOSE, "No valid decoder configuration available\n");
142         return AVERROR(EINVAL);
143     }
144
145     return best_cfg;
146 }
147
148 #if CONFIG_D3D11VA
149 static int d3d11va_validate_output(void *service, GUID guid, const void *surface_format)
150 {
151     HRESULT hr;
152     BOOL is_supported = FALSE;
153     hr = ID3D11VideoDevice_CheckVideoDecoderFormat((ID3D11VideoDevice *)service,
154                                                    &guid,
155                                                    *(DXGI_FORMAT *)surface_format,
156                                                    &is_supported);
157     return SUCCEEDED(hr) && is_supported;
158 }
159 #endif
160
161 #if CONFIG_DXVA2
162 static int dxva2_validate_output(void *decoder_service, GUID guid, const void *surface_format)
163 {
164     HRESULT hr;
165     int ret = 0;
166     unsigned j, target_count;
167     D3DFORMAT *target_list;
168     hr = IDirectXVideoDecoderService_GetDecoderRenderTargets((IDirectXVideoDecoderService *)decoder_service, &guid, &target_count, &target_list);
169     if (SUCCEEDED(hr)) {
170         for (j = 0; j < target_count; j++) {
171             const D3DFORMAT format = target_list[j];
172             if (format == *(D3DFORMAT *)surface_format) {
173                 ret = 1;
174                 break;
175             }
176         }
177         CoTaskMemFree(target_list);
178     }
179     return ret;
180 }
181 #endif
182
183 static int dxva_check_codec_compatibility(AVCodecContext *avctx, const dxva_mode *mode)
184 {
185     if (mode->codec != avctx->codec_id)
186             return 0;
187
188     if (mode->profiles && !(avctx->hwaccel_flags & AV_HWACCEL_FLAG_ALLOW_PROFILE_MISMATCH)) {
189         int i, found = 0;
190         for (i = 0; mode->profiles[i] != FF_PROFILE_UNKNOWN; i++) {
191             if (avctx->profile == mode->profiles[i]) {
192                 found = 1;
193                 break;
194             }
195         }
196         if (!found)
197             return 0;
198     }
199
200     return 1;
201 }
202
203 static int dxva_get_decoder_guid(AVCodecContext *avctx, void *service, void *surface_format,
204                                  unsigned guid_count, const GUID *guid_list, GUID *decoder_guid)
205 {
206     FFDXVASharedContext *sctx = DXVA_SHARED_CONTEXT(avctx);
207     unsigned i, j;
208
209     *decoder_guid = ff_GUID_NULL;
210     for (i = 0; dxva_modes[i].guid; i++) {
211         const dxva_mode *mode = &dxva_modes[i];
212         int validate;
213         if (!dxva_check_codec_compatibility(avctx, mode))
214             continue;
215
216         for (j = 0; j < guid_count; j++) {
217             if (IsEqualGUID(mode->guid, &guid_list[j]))
218                 break;
219         }
220         if (j == guid_count)
221             continue;
222
223 #if CONFIG_D3D11VA
224         if (sctx->pix_fmt == AV_PIX_FMT_D3D11)
225             validate = d3d11va_validate_output(service, *mode->guid, surface_format);
226 #endif
227 #if CONFIG_DXVA2
228         if (sctx->pix_fmt == AV_PIX_FMT_DXVA2_VLD)
229             validate = dxva2_validate_output(service, *mode->guid, surface_format);
230 #endif
231         if (validate) {
232             *decoder_guid = *mode->guid;
233             break;
234         }
235     }
236
237     if (IsEqualGUID(decoder_guid, &ff_GUID_NULL)) {
238         av_log(avctx, AV_LOG_VERBOSE, "No decoder device for codec found\n");
239         return AVERROR(EINVAL);
240     }
241
242     if (IsEqualGUID(decoder_guid, &ff_DXVADDI_Intel_ModeH264_E))
243         sctx->workaround |= FF_DXVA2_WORKAROUND_INTEL_CLEARVIDEO;
244
245     return 0;
246 }
247
248 static void bufref_free_interface(void *opaque, uint8_t *data)
249 {
250     IUnknown_Release((IUnknown *)opaque);
251 }
252
253 static AVBufferRef *bufref_wrap_interface(IUnknown *iface)
254 {
255     return av_buffer_create((uint8_t*)iface, 1, bufref_free_interface, iface, 0);
256 }
257
258 #if CONFIG_DXVA2
259
260 static int dxva2_get_decoder_configuration(AVCodecContext *avctx, const GUID *device_guid,
261                                            const DXVA2_VideoDesc *desc,
262                                            DXVA2_ConfigPictureDecode *config)
263 {
264     FFDXVASharedContext *sctx = DXVA_SHARED_CONTEXT(avctx);
265     unsigned cfg_count;
266     DXVA2_ConfigPictureDecode *cfg_list;
267     HRESULT hr;
268     int ret;
269
270     hr = IDirectXVideoDecoderService_GetDecoderConfigurations(sctx->dxva2_service, device_guid, desc, NULL, &cfg_count, &cfg_list);
271     if (FAILED(hr)) {
272         av_log(avctx, AV_LOG_ERROR, "Unable to retrieve decoder configurations\n");
273         return AVERROR(EINVAL);
274     }
275
276     ret = dxva_get_decoder_configuration(avctx, cfg_list, cfg_count);
277     if (ret >= 0)
278         *config = cfg_list[ret];
279     CoTaskMemFree(cfg_list);
280     return ret;
281 }
282
283 static int dxva2_create_decoder(AVCodecContext *avctx)
284 {
285     FFDXVASharedContext *sctx = DXVA_SHARED_CONTEXT(avctx);
286     GUID *guid_list;
287     unsigned guid_count;
288     GUID device_guid;
289     D3DFORMAT surface_format = avctx->sw_pix_fmt == AV_PIX_FMT_YUV420P10 ?
290                                MKTAG('P', '0', '1', '0') : MKTAG('N', 'V', '1', '2');
291     DXVA2_VideoDesc desc = { 0 };
292     DXVA2_ConfigPictureDecode config;
293     HRESULT hr;
294     int ret;
295     HANDLE device_handle;
296     AVHWFramesContext *frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
297     AVDXVA2FramesContext *frames_hwctx = frames_ctx->hwctx;
298     AVDXVA2DeviceContext *device_hwctx = frames_ctx->device_ctx->hwctx;
299
300     hr = IDirect3DDeviceManager9_OpenDeviceHandle(device_hwctx->devmgr,
301                                                   &device_handle);
302     if (FAILED(hr)) {
303         av_log(avctx, AV_LOG_ERROR, "Failed to open a device handle\n");
304         goto fail;
305     }
306
307     hr = IDirect3DDeviceManager9_GetVideoService(device_hwctx->devmgr, device_handle,
308                                                  &ff_IID_IDirectXVideoDecoderService,
309                                                  (void **)&sctx->dxva2_service);
310     IDirect3DDeviceManager9_CloseDeviceHandle(device_hwctx->devmgr, device_handle);
311     if (FAILED(hr)) {
312         av_log(avctx, AV_LOG_ERROR, "Failed to create IDirectXVideoDecoderService\n");
313         goto fail;
314     }
315
316     hr = IDirectXVideoDecoderService_GetDecoderDeviceGuids(sctx->dxva2_service, &guid_count, &guid_list);
317     if (FAILED(hr)) {
318         av_log(avctx, AV_LOG_ERROR, "Failed to retrieve decoder device GUIDs\n");
319         goto fail;
320     }
321
322     ret = dxva_get_decoder_guid(avctx, sctx->dxva2_service, &surface_format,
323                                 guid_count, guid_list, &device_guid);
324     CoTaskMemFree(guid_list);
325     if (ret < 0) {
326         goto fail;
327     }
328
329     desc.SampleWidth  = avctx->coded_width;
330     desc.SampleHeight = avctx->coded_height;
331     desc.Format       = surface_format;
332
333     ret = dxva2_get_decoder_configuration(avctx, &device_guid, &desc, &config);
334     if (ret < 0) {
335         goto fail;
336     }
337
338     hr = IDirectXVideoDecoderService_CreateVideoDecoder(sctx->dxva2_service, &device_guid,
339                                                         &desc, &config, frames_hwctx->surfaces,
340                                                         frames_hwctx->nb_surfaces, &sctx->dxva2_decoder);
341     if (FAILED(hr)) {
342         av_log(avctx, AV_LOG_ERROR, "Failed to create DXVA2 video decoder\n");
343         goto fail;
344     }
345
346     sctx->dxva2_config = config;
347
348     sctx->decoder_ref = bufref_wrap_interface((IUnknown *)sctx->dxva2_decoder);
349     if (!sctx->decoder_ref)
350         return AVERROR(ENOMEM);
351
352     return 0;
353 fail:
354     return AVERROR(EINVAL);
355 }
356
357 #endif
358
359 #if CONFIG_D3D11VA
360
361 static int d3d11va_get_decoder_configuration(AVCodecContext *avctx,
362                                              ID3D11VideoDevice *video_device,
363                                              const D3D11_VIDEO_DECODER_DESC *desc,
364                                              D3D11_VIDEO_DECODER_CONFIG *config)
365 {
366     FFDXVASharedContext *sctx = DXVA_SHARED_CONTEXT(avctx);
367     unsigned cfg_count = 0;
368     D3D11_VIDEO_DECODER_CONFIG *cfg_list = NULL;
369     HRESULT hr;
370     int i, ret;
371
372     hr = ID3D11VideoDevice_GetVideoDecoderConfigCount(video_device, desc, &cfg_count);
373     if (FAILED(hr)) {
374         av_log(avctx, AV_LOG_ERROR, "Unable to retrieve decoder configurations\n");
375         return AVERROR(EINVAL);
376     }
377
378     cfg_list = av_malloc_array(cfg_count, sizeof(D3D11_VIDEO_DECODER_CONFIG));
379     if (cfg_list == NULL)
380         return AVERROR(ENOMEM);
381     for (i = 0; i < cfg_count; i++) {
382         hr = ID3D11VideoDevice_GetVideoDecoderConfig(video_device, desc, i, &cfg_list[i]);
383         if (FAILED(hr)) {
384             av_log(avctx, AV_LOG_ERROR, "Unable to retrieve decoder configurations. (hr=0x%lX)\n", hr);
385             av_free(cfg_list);
386             return AVERROR(EINVAL);
387         }
388     }
389
390     ret = dxva_get_decoder_configuration(avctx, cfg_list, cfg_count);
391     if (ret >= 0)
392         *config = cfg_list[ret];
393     av_free(cfg_list);
394     return ret;
395 }
396
397 static int d3d11va_create_decoder(AVCodecContext *avctx)
398 {
399     FFDXVASharedContext *sctx = DXVA_SHARED_CONTEXT(avctx);
400     GUID *guid_list;
401     unsigned guid_count, i;
402     GUID decoder_guid;
403     DXGI_FORMAT surface_format = avctx->sw_pix_fmt == AV_PIX_FMT_YUV420P10 ?
404                                  DXGI_FORMAT_P010 : DXGI_FORMAT_NV12;
405     D3D11_VIDEO_DECODER_DESC desc = { 0 };
406     D3D11_VIDEO_DECODER_CONFIG config;
407     AVHWFramesContext *frames_ctx = (AVHWFramesContext *)avctx->hw_frames_ctx->data;
408     AVD3D11VADeviceContext *device_hwctx = frames_ctx->device_ctx->hwctx;
409     AVD3D11VAFramesContext *frames_hwctx = frames_ctx->hwctx;
410     D3D11_TEXTURE2D_DESC texdesc;
411     HRESULT hr;
412     int ret;
413
414     if (!frames_hwctx->texture) {
415         av_log(avctx, AV_LOG_ERROR, "AVD3D11VAFramesContext.texture not set.\n");
416         return AVERROR(EINVAL);
417     }
418     ID3D11Texture2D_GetDesc(frames_hwctx->texture, &texdesc);
419
420     guid_count = ID3D11VideoDevice_GetVideoDecoderProfileCount(device_hwctx->video_device);
421     guid_list = av_malloc_array(guid_count, sizeof(*guid_list));
422     if (guid_list == NULL || guid_count == 0) {
423         av_log(avctx, AV_LOG_ERROR, "Failed to get the decoder GUIDs\n");
424         av_free(guid_list);
425         return AVERROR(EINVAL);
426     }
427     for (i = 0; i < guid_count; i++) {
428         hr = ID3D11VideoDevice_GetVideoDecoderProfile(device_hwctx->video_device, i, &guid_list[i]);
429         if (FAILED(hr)) {
430             av_log(avctx, AV_LOG_ERROR, "Failed to retrieve decoder GUID %d\n", i);
431             av_free(guid_list);
432             return AVERROR(EINVAL);
433         }
434     }
435
436     ret = dxva_get_decoder_guid(avctx, device_hwctx->video_device, &surface_format,
437                                 guid_count, guid_list, &decoder_guid);
438     av_free(guid_list);
439     if (ret < 0)
440         return AVERROR(EINVAL);
441
442     desc.SampleWidth  = avctx->coded_width;
443     desc.SampleHeight = avctx->coded_height;
444     desc.OutputFormat = surface_format;
445     desc.Guid         = decoder_guid;
446
447     ret = d3d11va_get_decoder_configuration(avctx, device_hwctx->video_device, &desc, &config);
448     if (ret < 0)
449         return AVERROR(EINVAL);
450
451     sctx->d3d11_views = av_mallocz_array(texdesc.ArraySize, sizeof(sctx->d3d11_views[0]));
452     if (!sctx->d3d11_views)
453         return AVERROR(ENOMEM);
454     sctx->nb_d3d11_views = texdesc.ArraySize;
455
456     for (i = 0; i < sctx->nb_d3d11_views; i++) {
457         D3D11_VIDEO_DECODER_OUTPUT_VIEW_DESC viewDesc = {
458             .DecodeProfile = decoder_guid,
459             .ViewDimension = D3D11_VDOV_DIMENSION_TEXTURE2D,
460             .Texture2D = {
461                 .ArraySlice = i,
462             }
463         };
464         hr = ID3D11VideoDevice_CreateVideoDecoderOutputView(device_hwctx->video_device,
465                                                             (ID3D11Resource*) frames_hwctx->texture,
466                                                             &viewDesc,
467                                                             (ID3D11VideoDecoderOutputView**) &sctx->d3d11_views[i]);
468         if (FAILED(hr)) {
469             av_log(avctx, AV_LOG_ERROR, "Could not create the decoder output view %d\n", i);
470             return AVERROR_UNKNOWN;
471         }
472     }
473
474     hr = ID3D11VideoDevice_CreateVideoDecoder(device_hwctx->video_device, &desc,
475                                               &config, &sctx->d3d11_decoder);
476     if (FAILED(hr)) {
477         av_log(avctx, AV_LOG_ERROR, "Failed to create D3D11VA video decoder\n");
478         return AVERROR(EINVAL);
479     }
480
481     sctx->d3d11_config = config;
482     sctx->d3d11_texture = frames_hwctx->texture;
483
484     sctx->decoder_ref = bufref_wrap_interface((IUnknown *)sctx->d3d11_decoder);
485     if (!sctx->decoder_ref)
486         return AVERROR(ENOMEM);
487
488     return 0;
489 }
490
491 #endif
492
493 static void ff_dxva2_lock(AVCodecContext *avctx)
494 {
495 #if CONFIG_D3D11VA
496     if (ff_dxva2_is_d3d11(avctx)) {
497         FFDXVASharedContext *sctx = DXVA_SHARED_CONTEXT(avctx);
498         AVDXVAContext *ctx = DXVA_CONTEXT(avctx);
499         if (D3D11VA_CONTEXT(ctx)->context_mutex != INVALID_HANDLE_VALUE)
500             WaitForSingleObjectEx(D3D11VA_CONTEXT(ctx)->context_mutex, INFINITE, FALSE);
501         if (sctx->device_ctx) {
502             AVD3D11VADeviceContext *hwctx = sctx->device_ctx->hwctx;
503             hwctx->lock(hwctx->lock_ctx);
504         }
505     }
506 #endif
507 }
508
509 static void ff_dxva2_unlock(AVCodecContext *avctx)
510 {
511 #if CONFIG_D3D11VA
512     if (ff_dxva2_is_d3d11(avctx)) {
513         FFDXVASharedContext *sctx = DXVA_SHARED_CONTEXT(avctx);
514         AVDXVAContext *ctx = DXVA_CONTEXT(avctx);
515         if (D3D11VA_CONTEXT(ctx)->context_mutex != INVALID_HANDLE_VALUE)
516             ReleaseMutex(D3D11VA_CONTEXT(ctx)->context_mutex);
517         if (sctx->device_ctx) {
518             AVD3D11VADeviceContext *hwctx = sctx->device_ctx->hwctx;
519             hwctx->unlock(hwctx->lock_ctx);
520         }
521     }
522 #endif
523 }
524
525 // This must work before the decoder is created.
526 // This somehow needs to be exported to the user.
527 static void dxva_adjust_hwframes(AVCodecContext *avctx, AVHWFramesContext *frames_ctx)
528 {
529     FFDXVASharedContext *sctx = DXVA_SHARED_CONTEXT(avctx);
530     int surface_alignment, num_surfaces;
531
532     frames_ctx->format = sctx->pix_fmt;
533
534     /* decoding MPEG-2 requires additional alignment on some Intel GPUs,
535     but it causes issues for H.264 on certain AMD GPUs..... */
536     if (avctx->codec_id == AV_CODEC_ID_MPEG2VIDEO)
537         surface_alignment = 32;
538     /* the HEVC DXVA2 spec asks for 128 pixel aligned surfaces to ensure
539     all coding features have enough room to work with */
540     else if (avctx->codec_id == AV_CODEC_ID_HEVC)
541         surface_alignment = 128;
542     else
543         surface_alignment = 16;
544
545     /* 4 base work surfaces */
546     num_surfaces = 4;
547
548     /* add surfaces based on number of possible refs */
549     if (avctx->codec_id == AV_CODEC_ID_H264 || avctx->codec_id == AV_CODEC_ID_HEVC)
550         num_surfaces += 16;
551     else if (avctx->codec_id == AV_CODEC_ID_VP9)
552         num_surfaces += 8;
553     else
554         num_surfaces += 2;
555
556     /* add extra surfaces for frame threading */
557     if (avctx->active_thread_type & FF_THREAD_FRAME)
558         num_surfaces += avctx->thread_count;
559
560     frames_ctx->sw_format = avctx->sw_pix_fmt == AV_PIX_FMT_YUV420P10 ?
561                             AV_PIX_FMT_P010 : AV_PIX_FMT_NV12;
562     frames_ctx->width = FFALIGN(avctx->coded_width, surface_alignment);
563     frames_ctx->height = FFALIGN(avctx->coded_height, surface_alignment);
564     frames_ctx->initial_pool_size = num_surfaces;
565
566
567 #if CONFIG_DXVA2
568     if (frames_ctx->format == AV_PIX_FMT_DXVA2_VLD) {
569         AVDXVA2FramesContext *frames_hwctx = frames_ctx->hwctx;
570
571         frames_hwctx->surface_type = DXVA2_VideoDecoderRenderTarget;
572     }
573 #endif
574
575 #if CONFIG_D3D11VA
576     if (frames_ctx->format == AV_PIX_FMT_D3D11) {
577         AVD3D11VAFramesContext *frames_hwctx = frames_ctx->hwctx;
578
579         frames_hwctx->BindFlags |= D3D11_BIND_DECODER;
580     }
581 #endif
582 }
583
584 int ff_dxva2_decode_init(AVCodecContext *avctx)
585 {
586     FFDXVASharedContext *sctx = DXVA_SHARED_CONTEXT(avctx);
587     AVHWFramesContext *frames_ctx = NULL;
588     int ret = 0;
589
590     // Old API.
591     if (avctx->hwaccel_context)
592         return 0;
593
594     // (avctx->pix_fmt is not updated yet at this point)
595     sctx->pix_fmt = avctx->hwaccel->pix_fmt;
596
597     if (!avctx->hw_frames_ctx && !avctx->hw_device_ctx) {
598         av_log(avctx, AV_LOG_ERROR, "Either a hw_frames_ctx or a hw_device_ctx needs to be set for hardware decoding.\n");
599         return AVERROR(EINVAL);
600     }
601
602     if (avctx->hw_frames_ctx) {
603         frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
604     } else {
605         avctx->hw_frames_ctx = av_hwframe_ctx_alloc(avctx->hw_device_ctx);
606         if (!avctx->hw_frames_ctx)
607             return AVERROR(ENOMEM);
608
609         frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
610
611         dxva_adjust_hwframes(avctx, frames_ctx);
612
613         ret = av_hwframe_ctx_init(avctx->hw_frames_ctx);
614         if (ret < 0)
615             goto fail;
616     }
617
618     sctx->device_ctx = frames_ctx->device_ctx;
619
620     if (frames_ctx->format != sctx->pix_fmt ||
621         !((sctx->pix_fmt == AV_PIX_FMT_D3D11 && CONFIG_D3D11VA) ||
622           (sctx->pix_fmt == AV_PIX_FMT_DXVA2_VLD && CONFIG_DXVA2))) {
623         av_log(avctx, AV_LOG_ERROR, "Invalid pixfmt for hwaccel!\n");
624         ret = AVERROR(EINVAL);
625         goto fail;
626     }
627
628 #if CONFIG_D3D11VA
629     if (sctx->pix_fmt == AV_PIX_FMT_D3D11) {
630         AVD3D11VADeviceContext *device_hwctx = frames_ctx->device_ctx->hwctx;
631         AVD3D11VAContext *d3d11_ctx = &sctx->ctx.d3d11va;
632         HRESULT hr;
633
634         ff_dxva2_lock(avctx);
635         ret = d3d11va_create_decoder(avctx);
636         ff_dxva2_unlock(avctx);
637         if (ret < 0)
638             goto fail;
639
640         d3d11_ctx->decoder       = sctx->d3d11_decoder;
641         d3d11_ctx->video_context = device_hwctx->video_context;
642         d3d11_ctx->cfg           = &sctx->d3d11_config;
643         d3d11_ctx->surface_count = sctx->nb_d3d11_views;
644         d3d11_ctx->surface       = sctx->d3d11_views;
645         d3d11_ctx->workaround    = sctx->workaround;
646         d3d11_ctx->context_mutex = INVALID_HANDLE_VALUE;
647     }
648 #endif
649
650 #if CONFIG_DXVA2
651     if (sctx->pix_fmt == AV_PIX_FMT_DXVA2_VLD) {
652         AVDXVA2FramesContext *frames_hwctx = frames_ctx->hwctx;
653         struct dxva_context *dxva_ctx = &sctx->ctx.dxva2;
654
655         ff_dxva2_lock(avctx);
656         ret = dxva2_create_decoder(avctx);
657         ff_dxva2_unlock(avctx);
658         if (ret < 0)
659             goto fail;
660
661         dxva_ctx->decoder       = sctx->dxva2_decoder;
662         dxva_ctx->cfg           = &sctx->dxva2_config;
663         dxva_ctx->surface       = frames_hwctx->surfaces;
664         dxva_ctx->surface_count = frames_hwctx->nb_surfaces;
665         dxva_ctx->workaround    = sctx->workaround;
666     }
667 #endif
668
669     return 0;
670
671 fail:
672     ff_dxva2_decode_uninit(avctx);
673     return ret;
674 }
675
676 int ff_dxva2_decode_uninit(AVCodecContext *avctx)
677 {
678     FFDXVASharedContext *sctx = DXVA_SHARED_CONTEXT(avctx);
679     int i;
680
681     av_buffer_unref(&sctx->decoder_ref);
682
683 #if CONFIG_D3D11VA
684     for (i = 0; i < sctx->nb_d3d11_views; i++) {
685         if (sctx->d3d11_views[i])
686             ID3D11VideoDecoderOutputView_Release(sctx->d3d11_views[i]);
687     }
688     av_freep(&sctx->d3d11_views);
689 #endif
690
691 #if CONFIG_DXVA2
692     if (sctx->dxva2_service)
693         IDirectXVideoDecoderService_Release(sctx->dxva2_service);
694 #endif
695
696     return 0;
697 }
698
699 static void *get_surface(AVCodecContext *avctx, const AVFrame *frame)
700 {
701 #if CONFIG_D3D11VA
702     if (frame->format == AV_PIX_FMT_D3D11) {
703         FFDXVASharedContext *sctx = DXVA_SHARED_CONTEXT(avctx);
704         intptr_t index = (intptr_t)frame->data[1];
705         if (index < 0 || index >= sctx->nb_d3d11_views ||
706             sctx->d3d11_texture != (ID3D11Texture2D *)frame->data[0]) {
707             av_log(avctx, AV_LOG_ERROR, "get_buffer frame is invalid!\n");
708             return NULL;
709         }
710         return sctx->d3d11_views[index];
711     }
712 #endif
713     return frame->data[3];
714 }
715
716 unsigned ff_dxva2_get_surface_index(const AVCodecContext *avctx,
717                                     const AVDXVAContext *ctx,
718                                     const AVFrame *frame)
719 {
720     void *surface = get_surface(avctx, frame);
721     unsigned i;
722
723 #if CONFIG_D3D11VA
724     if (avctx->pix_fmt == AV_PIX_FMT_D3D11)
725         return (intptr_t)frame->data[1];
726     if (avctx->pix_fmt == AV_PIX_FMT_D3D11VA_VLD) {
727         D3D11_VIDEO_DECODER_OUTPUT_VIEW_DESC viewDesc;
728         ID3D11VideoDecoderOutputView_GetDesc((ID3D11VideoDecoderOutputView*) surface, &viewDesc);
729         return viewDesc.Texture2D.ArraySlice;
730     }
731 #endif
732 #if CONFIG_DXVA2
733     for (i = 0; i < DXVA_CONTEXT_COUNT(avctx, ctx); i++) {
734         if (avctx->pix_fmt == AV_PIX_FMT_DXVA2_VLD && ctx->dxva2.surface[i] == surface)
735             return i;
736     }
737 #endif
738
739     assert(0);
740     return 0;
741 }
742
743 int ff_dxva2_commit_buffer(AVCodecContext *avctx,
744                            AVDXVAContext *ctx,
745                            DECODER_BUFFER_DESC *dsc,
746                            unsigned type, const void *data, unsigned size,
747                            unsigned mb_count)
748 {
749     void     *dxva_data;
750     unsigned dxva_size;
751     int      result;
752     HRESULT hr = 0;
753
754 #if CONFIG_D3D11VA
755     if (ff_dxva2_is_d3d11(avctx))
756         hr = ID3D11VideoContext_GetDecoderBuffer(D3D11VA_CONTEXT(ctx)->video_context,
757                                                  D3D11VA_CONTEXT(ctx)->decoder,
758                                                  type,
759                                                  &dxva_size, &dxva_data);
760 #endif
761 #if CONFIG_DXVA2
762     if (avctx->pix_fmt == AV_PIX_FMT_DXVA2_VLD)
763         hr = IDirectXVideoDecoder_GetBuffer(DXVA2_CONTEXT(ctx)->decoder, type,
764                                             &dxva_data, &dxva_size);
765 #endif
766     if (FAILED(hr)) {
767         av_log(avctx, AV_LOG_ERROR, "Failed to get a buffer for %u: 0x%x\n",
768                type, hr);
769         return -1;
770     }
771     if (size <= dxva_size) {
772         memcpy(dxva_data, data, size);
773
774 #if CONFIG_D3D11VA
775         if (ff_dxva2_is_d3d11(avctx)) {
776             D3D11_VIDEO_DECODER_BUFFER_DESC *dsc11 = dsc;
777             memset(dsc11, 0, sizeof(*dsc11));
778             dsc11->BufferType           = type;
779             dsc11->DataSize             = size;
780             dsc11->NumMBsInBuffer       = mb_count;
781         }
782 #endif
783 #if CONFIG_DXVA2
784         if (avctx->pix_fmt == AV_PIX_FMT_DXVA2_VLD) {
785             DXVA2_DecodeBufferDesc *dsc2 = dsc;
786             memset(dsc2, 0, sizeof(*dsc2));
787             dsc2->CompressedBufferType = type;
788             dsc2->DataSize             = size;
789             dsc2->NumMBsInBuffer       = mb_count;
790         }
791 #endif
792
793         result = 0;
794     } else {
795         av_log(avctx, AV_LOG_ERROR, "Buffer for type %u was too small\n", type);
796         result = -1;
797     }
798
799 #if CONFIG_D3D11VA
800     if (ff_dxva2_is_d3d11(avctx))
801         hr = ID3D11VideoContext_ReleaseDecoderBuffer(D3D11VA_CONTEXT(ctx)->video_context, D3D11VA_CONTEXT(ctx)->decoder, type);
802 #endif
803 #if CONFIG_DXVA2
804     if (avctx->pix_fmt == AV_PIX_FMT_DXVA2_VLD)
805         hr = IDirectXVideoDecoder_ReleaseBuffer(DXVA2_CONTEXT(ctx)->decoder, type);
806 #endif
807     if (FAILED(hr)) {
808         av_log(avctx, AV_LOG_ERROR,
809                "Failed to release buffer type %u: 0x%x\n",
810                type, hr);
811         result = -1;
812     }
813     return result;
814 }
815
816 static int frame_add_buf(AVFrame *frame, AVBufferRef *ref)
817 {
818     int i;
819
820     for (i = 0; i < AV_NUM_DATA_POINTERS; i++) {
821         if (!frame->buf[i]) {
822             frame->buf[i] = av_buffer_ref(ref);
823             return frame->buf[i] ? 0 : AVERROR(ENOMEM);
824         }
825     }
826
827     // For now we expect that the caller does not use more than
828     // AV_NUM_DATA_POINTERS-1 buffers if the user uses a custom pool.
829     return AVERROR(EINVAL);
830 }
831
832 int ff_dxva2_common_end_frame(AVCodecContext *avctx, AVFrame *frame,
833                               const void *pp, unsigned pp_size,
834                               const void *qm, unsigned qm_size,
835                               int (*commit_bs_si)(AVCodecContext *,
836                                                   DECODER_BUFFER_DESC *bs,
837                                                   DECODER_BUFFER_DESC *slice))
838 {
839     AVDXVAContext *ctx = DXVA_CONTEXT(avctx);
840     unsigned               buffer_count = 0;
841 #if CONFIG_D3D11VA
842     D3D11_VIDEO_DECODER_BUFFER_DESC buffer11[4];
843 #endif
844 #if CONFIG_DXVA2
845     DXVA2_DecodeBufferDesc          buffer2[4];
846 #endif
847     DECODER_BUFFER_DESC             *buffer = NULL, *buffer_slice = NULL;
848     int result, runs = 0;
849     HRESULT hr;
850     unsigned type;
851     FFDXVASharedContext *sctx = DXVA_SHARED_CONTEXT(avctx);
852
853     if (sctx->decoder_ref) {
854         result = frame_add_buf(frame, sctx->decoder_ref);
855         if (result < 0)
856             return result;
857     }
858
859     do {
860         ff_dxva2_lock(avctx);
861 #if CONFIG_D3D11VA
862         if (ff_dxva2_is_d3d11(avctx))
863             hr = ID3D11VideoContext_DecoderBeginFrame(D3D11VA_CONTEXT(ctx)->video_context, D3D11VA_CONTEXT(ctx)->decoder,
864                                                       get_surface(avctx, frame),
865                                                       0, NULL);
866 #endif
867 #if CONFIG_DXVA2
868         if (avctx->pix_fmt == AV_PIX_FMT_DXVA2_VLD)
869             hr = IDirectXVideoDecoder_BeginFrame(DXVA2_CONTEXT(ctx)->decoder,
870                                                  get_surface(avctx, frame),
871                                                  NULL);
872 #endif
873         if (hr != E_PENDING || ++runs > 50)
874             break;
875         ff_dxva2_unlock(avctx);
876         av_usleep(2000);
877     } while(1);
878
879     if (FAILED(hr)) {
880         av_log(avctx, AV_LOG_ERROR, "Failed to begin frame: 0x%x\n", hr);
881         ff_dxva2_unlock(avctx);
882         return -1;
883     }
884
885 #if CONFIG_D3D11VA
886     if (ff_dxva2_is_d3d11(avctx)) {
887         buffer = &buffer11[buffer_count];
888         type = D3D11_VIDEO_DECODER_BUFFER_PICTURE_PARAMETERS;
889     }
890 #endif
891 #if CONFIG_DXVA2
892     if (avctx->pix_fmt == AV_PIX_FMT_DXVA2_VLD) {
893         buffer = &buffer2[buffer_count];
894         type = DXVA2_PictureParametersBufferType;
895     }
896 #endif
897     result = ff_dxva2_commit_buffer(avctx, ctx, buffer,
898                                     type,
899                                     pp, pp_size, 0);
900     if (result) {
901         av_log(avctx, AV_LOG_ERROR,
902                "Failed to add picture parameter buffer\n");
903         goto end;
904     }
905     buffer_count++;
906
907     if (qm_size > 0) {
908 #if CONFIG_D3D11VA
909         if (ff_dxva2_is_d3d11(avctx)) {
910             buffer = &buffer11[buffer_count];
911             type = D3D11_VIDEO_DECODER_BUFFER_INVERSE_QUANTIZATION_MATRIX;
912         }
913 #endif
914 #if CONFIG_DXVA2
915         if (avctx->pix_fmt == AV_PIX_FMT_DXVA2_VLD) {
916             buffer = &buffer2[buffer_count];
917             type = DXVA2_InverseQuantizationMatrixBufferType;
918         }
919 #endif
920         result = ff_dxva2_commit_buffer(avctx, ctx, buffer,
921                                         type,
922                                         qm, qm_size, 0);
923         if (result) {
924             av_log(avctx, AV_LOG_ERROR,
925                    "Failed to add inverse quantization matrix buffer\n");
926             goto end;
927         }
928         buffer_count++;
929     }
930
931 #if CONFIG_D3D11VA
932     if (ff_dxva2_is_d3d11(avctx)) {
933         buffer       = &buffer11[buffer_count + 0];
934         buffer_slice = &buffer11[buffer_count + 1];
935     }
936 #endif
937 #if CONFIG_DXVA2
938     if (avctx->pix_fmt == AV_PIX_FMT_DXVA2_VLD) {
939         buffer       = &buffer2[buffer_count + 0];
940         buffer_slice = &buffer2[buffer_count + 1];
941     }
942 #endif
943
944     result = commit_bs_si(avctx,
945                           buffer,
946                           buffer_slice);
947     if (result) {
948         av_log(avctx, AV_LOG_ERROR,
949                "Failed to add bitstream or slice control buffer\n");
950         goto end;
951     }
952     buffer_count += 2;
953
954     /* TODO Film Grain when possible */
955
956     assert(buffer_count == 1 + (qm_size > 0) + 2);
957
958 #if CONFIG_D3D11VA
959     if (ff_dxva2_is_d3d11(avctx))
960         hr = ID3D11VideoContext_SubmitDecoderBuffers(D3D11VA_CONTEXT(ctx)->video_context,
961                                                      D3D11VA_CONTEXT(ctx)->decoder,
962                                                      buffer_count, buffer11);
963 #endif
964 #if CONFIG_DXVA2
965     if (avctx->pix_fmt == AV_PIX_FMT_DXVA2_VLD) {
966         DXVA2_DecodeExecuteParams exec = {
967             .NumCompBuffers     = buffer_count,
968             .pCompressedBuffers = buffer2,
969             .pExtensionData     = NULL,
970         };
971         hr = IDirectXVideoDecoder_Execute(DXVA2_CONTEXT(ctx)->decoder, &exec);
972     }
973 #endif
974     if (FAILED(hr)) {
975         av_log(avctx, AV_LOG_ERROR, "Failed to execute: 0x%x\n", hr);
976         result = -1;
977     }
978
979 end:
980 #if CONFIG_D3D11VA
981     if (ff_dxva2_is_d3d11(avctx))
982         hr = ID3D11VideoContext_DecoderEndFrame(D3D11VA_CONTEXT(ctx)->video_context, D3D11VA_CONTEXT(ctx)->decoder);
983 #endif
984 #if CONFIG_DXVA2
985     if (avctx->pix_fmt == AV_PIX_FMT_DXVA2_VLD)
986         hr = IDirectXVideoDecoder_EndFrame(DXVA2_CONTEXT(ctx)->decoder, NULL);
987 #endif
988     ff_dxva2_unlock(avctx);
989     if (FAILED(hr)) {
990         av_log(avctx, AV_LOG_ERROR, "Failed to end frame: 0x%x\n", hr);
991         result = -1;
992     }
993
994     return result;
995 }
996
997 int ff_dxva2_is_d3d11(const AVCodecContext *avctx)
998 {
999     if (CONFIG_D3D11VA)
1000         return avctx->pix_fmt == AV_PIX_FMT_D3D11VA_VLD ||
1001                avctx->pix_fmt == AV_PIX_FMT_D3D11;
1002     else
1003         return 0;
1004 }