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