f2d8714ba2637b9738551d69bfa64090dc5b9f40
[vlc.git] / modules / codec / avcodec / dxva2.c
1 /*****************************************************************************
2  * dxva2.c: Video Acceleration helpers
3  *****************************************************************************
4  * Copyright (C) 2009 Geoffroy Couprie
5  * Copyright (C) 2009 Laurent Aimar
6  *
7  * Authors: Geoffroy Couprie <geal@videolan.org>
8  *          Laurent Aimar <fenrir _AT_ videolan _DOT_ org>
9  *
10  * This program is free software; you can redistribute it and/or modify it
11  * under the terms of the GNU Lesser General Public License as published by
12  * the Free Software Foundation; either version 2.1 of the License, or
13  * (at your option) any later version.
14  *
15  * This program is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18  * GNU Lesser General Public License for more details.
19  *
20  * You should have received a copy of the GNU Lesser General Public License
21  * along with this program; if not, write to the Free Software Foundation,
22  * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
23  *****************************************************************************/
24
25 #ifdef HAVE_CONFIG_H
26 # include "config.h"
27 #endif
28
29 #include <assert.h>
30
31 #include <vlc_common.h>
32 #include <vlc_picture.h>
33 #include <vlc_plugin.h>
34
35 #define DXVA2API_USE_BITFIELDS
36 #define COBJMACROS
37 #include <libavcodec/dxva2.h>
38 #include "../../video_chroma/d3d9_fmt.h"
39
40 struct dxva2_pic_context
41 {
42     struct d3d9_pic_context ctx;
43     struct vlc_va_surface_t *va_surface;
44     HINSTANCE               dxva2_dll;
45 };
46
47 #define DXVA2_PICCONTEXT_FROM_PICCTX(pic_ctx)  \
48     container_of((pic_ctx), struct dxva2_pic_context, ctx.s)
49
50 #include "directx_va.h"
51
52 static int Open(vlc_va_t *, AVCodecContext *, enum PixelFormat hwfmt, const AVPixFmtDescriptor *,
53                 const es_format_t *, vlc_decoder_device *, video_format_t *, vlc_video_context **);
54
55 vlc_module_begin()
56     set_description(N_("DirectX Video Acceleration (DXVA) 2.0"))
57     set_category(CAT_INPUT)
58     set_subcategory(SUBCAT_INPUT_VCODEC)
59     set_va_callback(Open, 110)
60 vlc_module_end()
61
62 #include <initguid.h> /* must be last included to not redefine existing GUIDs */
63
64 /* dxva2api.h GUIDs: http://msdn.microsoft.com/en-us/library/windows/desktop/ms697067(v=vs100).aspx
65  * assume that they are declared in dxva2api.h */
66 #define MS_GUID(name, l, w1, w2, b1, b2, b3, b4, b5, b6, b7, b8)
67
68 #ifdef __MINGW32__
69 # include <_mingw.h>
70
71 # if !defined(__MINGW64_VERSION_MAJOR)
72 #  undef MS_GUID
73 #  define MS_GUID DEFINE_GUID /* dxva2api.h fails to declare those, redefine as static */
74 #  define DXVA2_E_NEW_VIDEO_DEVICE MAKE_HRESULT(1, 4, 4097)
75 # else
76 #  include <dxva.h>
77 # endif
78
79 #endif /* __MINGW32__ */
80
81 MS_GUID(IID_IDirectXVideoDecoderService, 0xfc51a551, 0xd5e7, 0x11d9, 0xaf,0x55,0x00,0x05,0x4e,0x43,0xff,0x02);
82 MS_GUID(IID_IDirectXVideoAccelerationService, 0xfc51a550, 0xd5e7, 0x11d9, 0xaf,0x55,0x00,0x05,0x4e,0x43,0xff,0x02);
83
84 DEFINE_GUID(DXVA2_NoEncrypt,                        0x1b81bed0, 0xa0c7, 0x11d3, 0xb9, 0x84, 0x00, 0xc0, 0x4f, 0x2e, 0x73, 0xc5);
85
86 DEFINE_GUID(DXVA_Intel_H264_NoFGT_ClearVideo,       0x604F8E68, 0x4951, 0x4c54, 0x88, 0xFE, 0xAB, 0xD2, 0x5C, 0x15, 0xB3, 0xD6);
87
88
89 /* */
90 typedef struct {
91     const char   *name;
92     D3DFORMAT    format;
93     vlc_fourcc_t codec;
94 } d3d9_format_t;
95 /* XXX Prefered format must come first */
96 static const d3d9_format_t d3d_formats[] = {
97     { "YV12",   MAKEFOURCC('Y','V','1','2'),    VLC_CODEC_YV12 },
98     { "NV12",   MAKEFOURCC('N','V','1','2'),    VLC_CODEC_NV12 },
99     //{ "IMC3",   MAKEFOURCC('I','M','C','3'),    VLC_CODEC_YV12 },
100     { "P010",   MAKEFOURCC('P','0','1','0'),    VLC_CODEC_P010 },
101
102     { NULL, 0, 0 }
103 };
104
105 static const d3d9_format_t *D3dFindFormat(D3DFORMAT format)
106 {
107     for (unsigned i = 0; d3d_formats[i].name; i++) {
108         if (d3d_formats[i].format == format)
109             return &d3d_formats[i];
110     }
111     return NULL;
112 }
113
114 struct vlc_va_sys_t
115 {
116     /* Direct3D */
117     vlc_video_context      *vctx;
118
119     /* DLL */
120     HINSTANCE              dxva2_dll;
121
122     /* Device manager */
123     IDirect3DDeviceManager9  *devmng;
124     HANDLE                   device;
125
126     /* Video service */
127     D3DFORMAT                    render;
128
129     /* Video decoder */
130     DXVA2_ConfigPictureDecode    cfg;
131     const directx_va_mode_t       *selected_decoder;
132     IDirectXVideoDecoderService  *d3ddec;
133
134     /* pool */
135     va_pool_t           *va_pool;
136     IDirect3DSurface9   *hw_surface[MAX_SURFACE_COUNT];
137
138     /* avcodec internals */
139     struct dxva_context hw;
140 };
141
142
143 /* */
144 static int D3dCreateDevice(vlc_va_t *);
145
146 static int DxGetInputList(vlc_va_t *, input_list_t *);
147 static int DxSetupOutput(vlc_va_t *, const directx_va_mode_t *, const video_format_t *);
148
149 static int DxCreateVideoDecoder(vlc_va_t *, int codec_id,
150                                 const video_format_t *, size_t surface_count);
151 static void DxDestroyVideoDecoder(void *);
152
153 static void SetupAVCodecContext(void *opaque, AVCodecContext *avctx)
154 {
155     vlc_va_sys_t *sys = opaque;
156     sys->hw.cfg = &sys->cfg;
157     sys->hw.surface = sys->hw_surface;
158     sys->hw.workaround = sys->selected_decoder->workaround;
159     avctx->hwaccel_context = &sys->hw;
160 }
161
162 static void dxva2_pic_context_destroy(picture_context_t *ctx)
163 {
164     struct dxva2_pic_context *pic_ctx = DXVA2_PICCONTEXT_FROM_PICCTX(ctx);
165     struct vlc_va_surface_t *va_surface = pic_ctx->va_surface;
166     HINSTANCE dxva2_dll = pic_ctx->dxva2_dll;
167     static_assert(offsetof(struct dxva2_pic_context, ctx.s) == 0,
168         "Cast assumption failure");
169     d3d9_pic_context_destroy(ctx);
170     va_surface_Release(va_surface);
171     FreeLibrary(dxva2_dll);
172 }
173
174 static picture_context_t *dxva2_pic_context_copy(picture_context_t *ctx)
175 {
176     struct dxva2_pic_context *src_ctx = DXVA2_PICCONTEXT_FROM_PICCTX(ctx);
177     struct dxva2_pic_context *pic_ctx = malloc(sizeof(*pic_ctx));
178     if (unlikely(pic_ctx==NULL))
179         return NULL;
180     *pic_ctx = *src_ctx;
181     pic_ctx->dxva2_dll = LoadLibrary(TEXT("DXVA2.DLL"));
182     vlc_video_context_Hold(pic_ctx->ctx.s.vctx);
183     va_surface_AddRef(pic_ctx->va_surface);
184     AcquireD3D9PictureSys(&pic_ctx->ctx.picsys);
185     return &pic_ctx->ctx.s;
186 }
187
188 static struct dxva2_pic_context *CreatePicContext(IDirect3DSurface9 *surface, vlc_video_context *vctx)
189 {
190     struct dxva2_pic_context *pic_ctx = calloc(1, sizeof(*pic_ctx));
191     if (unlikely(pic_ctx==NULL))
192         return NULL;
193     pic_ctx->ctx.s = (picture_context_t) {
194         dxva2_pic_context_destroy, dxva2_pic_context_copy,
195         vlc_video_context_Hold(vctx),
196     };
197     pic_ctx->ctx.picsys.surface = surface;
198     AcquireD3D9PictureSys(&pic_ctx->ctx.picsys);
199     return pic_ctx;
200 }
201
202 static picture_context_t* NewSurfacePicContext(vlc_va_t *va, vlc_va_surface_t *va_surface)
203 {
204     vlc_va_sys_t *sys = va->sys;
205     struct dxva2_pic_context *pic_ctx = CreatePicContext(sys->hw_surface[va_surface_GetIndex(va_surface)], sys->vctx);
206     if (unlikely(pic_ctx==NULL))
207         return NULL;
208     pic_ctx->va_surface = va_surface;
209     pic_ctx->dxva2_dll = LoadLibrary(TEXT("DXVA2.DLL"));
210     return &pic_ctx->ctx.s;
211 }
212
213 static int Get(vlc_va_t *va, picture_t *pic, uint8_t **data)
214 {
215     vlc_va_sys_t *sys = va->sys;
216
217     /* Check the device */
218     HRESULT hr = IDirect3DDeviceManager9_TestDevice(sys->devmng, sys->device);
219     if (FAILED(hr)) {
220         if (hr == DXVA2_E_NEW_VIDEO_DEVICE)
221             msg_Warn(va, "New video device detected.");
222         else
223             msg_Err(va, "device not usable. (hr=0x%lX)", hr);
224         return VLC_EGENERIC;
225     }
226
227     vlc_va_surface_t *va_surface = va_pool_Get(sys->va_pool);
228     if (unlikely(va_surface==NULL))
229         return VLC_ENOITEM;
230
231     pic->context = NewSurfacePicContext(va, va_surface);
232     if (unlikely(pic->context == NULL))
233     {
234         va_surface_Release(va_surface);
235         return VLC_ENOITEM;
236     }
237     *data = (uint8_t*)DXVA2_PICCONTEXT_FROM_PICCTX(pic->context)->ctx.picsys.surface;
238     return VLC_SUCCESS;
239 }
240
241 static void Close(vlc_va_t *va)
242 {
243     vlc_va_sys_t *sys = va->sys;
244
245     if (sys->vctx)
246         vlc_video_context_Release(sys->vctx);
247
248     if (sys->va_pool)
249         va_pool_Close(sys->va_pool);
250 }
251
252 static const struct vlc_va_operations ops = { Get, Close, };
253
254 static int Open(vlc_va_t *va, AVCodecContext *ctx, enum PixelFormat hwfmt, const AVPixFmtDescriptor *desc,
255                 const es_format_t *fmt_in, vlc_decoder_device *dec_device,
256                 video_format_t *fmt_out, vlc_video_context **vtcx_out)
257 {
258     int err = VLC_EGENERIC;
259
260     if ( hwfmt != AV_PIX_FMT_DXVA2_VLD )
261         return VLC_EGENERIC;
262
263     d3d9_decoder_device_t *d3d9_decoder = GetD3D9OpaqueDevice( dec_device );
264     if ( d3d9_decoder == NULL )
265         return VLC_EGENERIC;
266     assert(d3d9_decoder->d3ddev.dev != NULL); // coming from the decoder device
267
268     ctx->hwaccel_context = NULL;
269
270     vlc_va_sys_t *sys = calloc(1, sizeof (*sys));
271     if (unlikely(sys == NULL))
272         return VLC_ENOMEM;
273
274     sys->vctx = vlc_video_context_Create( dec_device, VLC_VIDEO_CONTEXT_DXVA2,
275                                           sizeof(d3d9_video_context_t), &d3d9_vctx_ops );
276     if (likely(sys->vctx == NULL))
277     {
278         free( sys );
279         return VLC_EGENERIC;
280     }
281
282     va->sys = sys;
283
284     /* Load dll*/
285     sys->dxva2_dll = LoadLibrary(TEXT("DXVA2.DLL"));
286     if (!sys->dxva2_dll) {
287         msg_Warn(va, "cannot load DXVA2 decoder DLL");
288         if (sys->vctx)
289             vlc_video_context_Release(sys->vctx);
290         free( sys );
291         return VLC_EGENERIC;
292     }
293
294     struct va_pool_cfg pool_cfg = {
295         D3dCreateDevice,
296         DxDestroyVideoDecoder,
297         DxCreateVideoDecoder,
298         SetupAVCodecContext,
299         sys,
300     };
301
302     sys->va_pool = va_pool_Create(va, &pool_cfg);
303     if (sys->va_pool == NULL)
304     {
305         err = VLC_EGENERIC;
306         goto error;
307     }
308
309     video_format_t final_fmt = *fmt_out;
310     static const directx_sys_t dx_sys = { DxGetInputList, DxSetupOutput };
311     sys->selected_decoder = directx_va_Setup(va, &dx_sys, ctx, desc, fmt_in, 0,
312                                              &final_fmt, &sys->hw.surface_count);
313     if (sys->selected_decoder == NULL)
314     {
315         err = VLC_EGENERIC;
316         goto error;
317     }
318
319     if (sys->render == MAKEFOURCC('P','0','1','0'))
320         final_fmt.i_chroma = VLC_CODEC_D3D9_OPAQUE_10B;
321     else
322         final_fmt.i_chroma = VLC_CODEC_D3D9_OPAQUE;
323     err = va_pool_SetupDecoder(va, sys->va_pool, ctx, &final_fmt, sys->hw.surface_count);
324     if (err != VLC_SUCCESS)
325         goto error;
326
327     const D3DADAPTER_IDENTIFIER9 *identifier = &d3d9_decoder->d3ddev.identifier;
328     msg_Info(va, "Using DXVA2 (%.*s, vendor %s(%lx), device %lx, revision %lx)",
329                 (int)sizeof(identifier->Description), identifier->Description,
330                 DxgiVendorStr(identifier->VendorId), identifier->VendorId,
331                 identifier->DeviceId, identifier->Revision);
332
333     d3d9_video_context_t *octx = GetD3D9ContextPrivate(sys->vctx);
334     octx->format = sys->render;
335
336     va->ops = &ops;
337     *fmt_out = final_fmt;
338     *vtcx_out = sys->vctx;
339     return VLC_SUCCESS;
340
341 error:
342     Close(va);
343     return VLC_EGENERIC;
344 }
345 /* */
346
347 /**
348  * It creates a Direct3D device usable for DXVA 2
349  */
350 static int D3dCreateDevice(vlc_va_t *va)
351 {
352     vlc_va_sys_t *sys = va->sys;
353
354     d3d9_decoder_device_t *d3d9_decoder = GetD3D9OpaqueContext(sys->vctx);
355
356     HRESULT (WINAPI *CreateDeviceManager9)(UINT *pResetToken,
357                                            IDirect3DDeviceManager9 **);
358     CreateDeviceManager9 =
359       (void *)GetProcAddress(sys->dxva2_dll,
360                              "DXVA2CreateDirect3DDeviceManager9");
361
362     if (!CreateDeviceManager9) {
363         msg_Err(va, "cannot load function");
364         return VLC_EGENERIC;
365     }
366     msg_Dbg(va, "got CreateDeviceManager9");
367
368     UINT token;
369     if (FAILED(CreateDeviceManager9(&token, &sys->devmng))) {
370         msg_Err(va, " OurDirect3DCreateDeviceManager9 failed");
371         return VLC_EGENERIC;
372     }
373     msg_Dbg(va, "obtained IDirect3DDeviceManager9");
374
375     HRESULT hr = IDirect3DDeviceManager9_ResetDevice(sys->devmng, d3d9_decoder->d3ddev.dev, token);
376     if (FAILED(hr)) {
377         msg_Err(va, "IDirect3DDeviceManager9_ResetDevice failed: 0x%lX)", hr);
378         IDirect3DDeviceManager9_Release(sys->devmng);
379         return VLC_EGENERIC;
380     }
381
382     hr = IDirect3DDeviceManager9_OpenDeviceHandle(sys->devmng, &sys->device);
383     if (FAILED(hr)) {
384         msg_Err(va, "OpenDeviceHandle failed");
385         IDirect3DDeviceManager9_Release(sys->devmng);
386         return VLC_EGENERIC;
387     }
388
389     void *pv;
390     hr = IDirect3DDeviceManager9_GetVideoService(sys->devmng, sys->device,
391                                         &IID_IDirectXVideoDecoderService, &pv);
392     if (FAILED(hr)) {
393         msg_Err(va, "GetVideoService failed");
394         IDirect3DDeviceManager9_CloseDeviceHandle(sys->devmng, sys->device);
395         IDirect3DDeviceManager9_Release(sys->devmng);
396         return VLC_EGENERIC;
397     }
398     sys->d3ddec = pv;
399
400     return VLC_SUCCESS;
401 }
402
403 static void ReleaseInputList(input_list_t *p_list)
404 {
405     CoTaskMemFree(p_list->list);
406 }
407
408 static int DxGetInputList(vlc_va_t *va, input_list_t *p_list)
409 {
410     vlc_va_sys_t *sys = va->sys;
411     UINT input_count = 0;
412     GUID *input_list = NULL;
413     if (FAILED(IDirectXVideoDecoderService_GetDecoderDeviceGuids(sys->d3ddec,
414                                                                  &input_count,
415                                                                  &input_list))) {
416         msg_Err(va, "IDirectXVideoDecoderService_GetDecoderDeviceGuids failed");
417         return VLC_EGENERIC;
418     }
419
420     p_list->count = input_count;
421     p_list->list = input_list;
422     p_list->pf_release = ReleaseInputList;
423     return VLC_SUCCESS;
424 }
425
426 static int DxSetupOutput(vlc_va_t *va, const directx_va_mode_t *mode, const video_format_t *fmt)
427 {
428     VLC_UNUSED(fmt);
429     vlc_va_sys_t *sys = va->sys;
430
431     d3d9_decoder_device_t *d3d9_decoder = GetD3D9OpaqueContext(sys->vctx);
432
433     const D3DADAPTER_IDENTIFIER9 *identifier = &d3d9_decoder->d3ddev.identifier;
434     UINT driverBuild = identifier->DriverVersion.LowPart & 0xFFFF;
435     if (identifier->VendorId == GPU_MANUFACTURER_INTEL && (identifier->DriverVersion.LowPart >> 16) >= 100)
436     {
437         /* new Intel driver format */
438         driverBuild += ((identifier->DriverVersion.LowPart >> 16) - 100) * 1000;
439     }
440     if (!directx_va_canUseDecoder(va, identifier->VendorId, identifier->DeviceId,
441                                   mode->guid, driverBuild))
442     {
443         msg_Warn(va, "GPU blacklisted for %s codec", mode->name);
444         return VLC_EGENERIC;
445     }
446
447     int err = VLC_EGENERIC;
448     UINT      output_count = 0;
449     D3DFORMAT *output_list = NULL;
450     if (FAILED(IDirectXVideoDecoderService_GetDecoderRenderTargets(sys->d3ddec,
451                                                                    mode->guid,
452                                                                    &output_count,
453                                                                    &output_list))) {
454         msg_Err(va, "IDirectXVideoDecoderService_GetDecoderRenderTargets failed");
455         return VLC_EGENERIC;
456     }
457
458     for (unsigned j = 0; j < output_count; j++) {
459         const D3DFORMAT f = output_list[j];
460         const d3d9_format_t *format = D3dFindFormat(f);
461         if (format) {
462             msg_Dbg(va, "%s is supported for output", format->name);
463         } else {
464             msg_Dbg(va, "%d is supported for output (%4.4s)", f, (const char*)&f);
465         }
466     }
467
468     D3DFORMAT preferredOutput;
469     if (mode->bit_depth > 8)
470         preferredOutput = MAKEFOURCC('P','0','1','0');
471     else
472         preferredOutput =  MAKEFOURCC('N','V','1','2');
473     msg_Dbg(va, "favor decoder format %4.4s (for 4:%d:%d %d bits)", (const char*)&preferredOutput,
474             (2-mode->log2_chroma_w)*2, (2-mode->log2_chroma_w-mode->log2_chroma_h)*2, mode->bit_depth);
475
476     /* */
477     for (unsigned pass = 0; pass < 2 && err != VLC_SUCCESS; ++pass)
478     {
479         for (unsigned j = 0; d3d_formats[j].name; j++) {
480             const d3d9_format_t *format = &d3d_formats[j];
481
482             /* */
483             bool is_supported = false;
484             for (unsigned k = 0; !is_supported && k < output_count; k++) {
485                 is_supported = format->format == output_list[k];
486             }
487             if (!is_supported)
488                 continue;
489             if (pass == 0 && format->format != preferredOutput)
490                 continue;
491
492             /* We have our solution */
493             msg_Dbg(va, "Using decoder output '%s'", format->name);
494             sys->render = format->format;
495             err = VLC_SUCCESS;
496             break;
497         }
498     }
499     CoTaskMemFree(output_list);
500     return err;
501 }
502
503 /**
504  * It creates a DXVA2 decoder using the given video format
505  */
506 static int DxCreateVideoDecoder(vlc_va_t *va, int codec_id,
507                                 const video_format_t *fmt, size_t surface_count)
508 {
509     vlc_va_sys_t *sys = va->sys;
510     HRESULT hr;
511
512     hr = IDirectXVideoDecoderService_CreateSurface(sys->d3ddec,
513                                                          fmt->i_width,
514                                                          fmt->i_height,
515                                                          surface_count - 1,
516                                                          sys->render,
517                                                          D3DPOOL_DEFAULT,
518                                                          0,
519                                                          DXVA2_VideoDecoderRenderTarget,
520                                                          sys->hw_surface,
521                                                          NULL);
522     if (FAILED(hr)) {
523         msg_Err(va, "IDirectXVideoAccelerationService_CreateSurface %zu failed (hr=0x%lX)", surface_count - 1, hr);
524         return VLC_EGENERIC;
525     }
526     msg_Dbg(va, "IDirectXVideoAccelerationService_CreateSurface succeed with %zu surfaces (%dx%d)",
527             surface_count, fmt->i_width, fmt->i_height);
528
529     IDirect3DSurface9 *tstCrash;
530     hr = IDirectXVideoDecoderService_CreateSurface(sys->d3ddec,
531                                                          fmt->i_width,
532                                                          fmt->i_height,
533                                                          0,
534                                                          sys->render,
535                                                          D3DPOOL_DEFAULT,
536                                                          0,
537                                                          DXVA2_VideoDecoderRenderTarget,
538                                                          &tstCrash,
539                                                          NULL);
540     if (FAILED(hr)) {
541         msg_Err(va, "extra buffer impossible, avoid a crash (hr=0x%lX)", hr);
542         goto error;
543     }
544     IDirect3DSurface9_Release(tstCrash);
545
546     /* */
547     DXVA2_VideoDesc dsc;
548     ZeroMemory(&dsc, sizeof(dsc));
549     dsc.SampleWidth     = fmt->i_width;
550     dsc.SampleHeight    = fmt->i_height;
551     dsc.Format          = sys->render;
552     if (fmt->i_frame_rate > 0 && fmt->i_frame_rate_base > 0) {
553         dsc.InputSampleFreq.Numerator   = fmt->i_frame_rate;
554         dsc.InputSampleFreq.Denominator = fmt->i_frame_rate_base;
555     } else {
556         dsc.InputSampleFreq.Numerator   = 0;
557         dsc.InputSampleFreq.Denominator = 0;
558     }
559     dsc.OutputFrameFreq = dsc.InputSampleFreq;
560     dsc.UABProtectionLevel = FALSE;
561     dsc.Reserved = 0;
562
563     /* FIXME I am unsure we can let unknown everywhere */
564     DXVA2_ExtendedFormat *ext = &dsc.SampleFormat;
565     ext->SampleFormat = 0;//DXVA2_SampleUnknown;
566     ext->VideoChromaSubsampling = 0;//DXVA2_VideoChromaSubsampling_Unknown;
567     ext->NominalRange = 0;//DXVA2_NominalRange_Unknown;
568     ext->VideoTransferMatrix = 0;//DXVA2_VideoTransferMatrix_Unknown;
569     ext->VideoLighting = 0;//DXVA2_VideoLighting_Unknown;
570     ext->VideoPrimaries = 0;//DXVA2_VideoPrimaries_Unknown;
571     ext->VideoTransferFunction = 0;//DXVA2_VideoTransFunc_Unknown;
572
573     /* List all configurations available for the decoder */
574     UINT                      cfg_count = 0;
575     DXVA2_ConfigPictureDecode *cfg_list = NULL;
576     hr = IDirectXVideoDecoderService_GetDecoderConfigurations(sys->d3ddec,
577                                                               sys->selected_decoder->guid,
578                                                               &dsc,
579                                                               NULL,
580                                                               &cfg_count,
581                                                               &cfg_list);
582     if (FAILED(hr)) {
583         msg_Err(va, "IDirectXVideoDecoderService_GetDecoderConfigurations failed. (hr=0x%lX)", hr);
584         goto error;
585     }
586     msg_Dbg(va, "we got %d decoder configurations", cfg_count);
587
588     /* Select the best decoder configuration */
589     int cfg_score = 0;
590     for (unsigned i = 0; i < cfg_count; i++) {
591         const DXVA2_ConfigPictureDecode *cfg = &cfg_list[i];
592
593         /* */
594         msg_Dbg(va, "configuration[%d] ConfigBitstreamRaw %d",
595                 i, cfg->ConfigBitstreamRaw);
596
597         /* */
598         int score;
599         if (cfg->ConfigBitstreamRaw == 1)
600             score = 1;
601         else if (codec_id == AV_CODEC_ID_H264 && cfg->ConfigBitstreamRaw == 2)
602             score = 2;
603         else
604             continue;
605         if (IsEqualGUID(&cfg->guidConfigBitstreamEncryption, &DXVA2_NoEncrypt))
606             score += 16;
607
608         if (cfg_score < score) {
609             sys->cfg = *cfg;
610             cfg_score = score;
611         }
612     }
613     CoTaskMemFree(cfg_list);
614     if (cfg_score <= 0) {
615         msg_Err(va, "Failed to find a supported decoder configuration");
616         goto error;
617     }
618
619     /* Create the decoder */
620     /* adds a reference on each decoder surface */
621     if (FAILED(IDirectXVideoDecoderService_CreateVideoDecoder(sys->d3ddec,
622                                                               sys->selected_decoder->guid,
623                                                               &dsc,
624                                                               &sys->cfg,
625                                                               sys->hw_surface,
626                                                               surface_count,
627                                                               &sys->hw.decoder))) {
628         msg_Err(va, "IDirectXVideoDecoderService_CreateVideoDecoder failed");
629         goto error;
630     }
631
632     msg_Dbg(va, "IDirectXVideoDecoderService_CreateVideoDecoder succeed");
633     return VLC_SUCCESS;
634 error:
635     for (size_t i = 0; i < surface_count; i++)
636         IDirect3DSurface9_Release( sys->hw_surface[i] );
637     return VLC_EGENERIC;
638 }
639
640 static void DxDestroyVideoDecoder(void *opaque)
641 {
642     vlc_va_sys_t *sys = opaque;
643     /* releases a reference on each decoder surface */
644     if (sys->hw.decoder)
645         IDirectXVideoDecoder_Release(sys->hw.decoder);
646     if (sys->hw_surface[0])
647     {
648         for (unsigned i = 0; i < sys->hw.surface_count; i++)
649             IDirect3DSurface9_Release(sys->hw_surface[i]);
650     }
651     IDirect3DDeviceManager9_CloseDeviceHandle(sys->devmng, sys->device);
652     IDirectXVideoDecoderService_Release(sys->d3ddec);
653     IDirect3DDeviceManager9_Release(sys->devmng);
654     if (sys->dxva2_dll)
655         FreeLibrary(sys->dxva2_dll);
656
657     free(sys);
658 }