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