]> git.sesse.net Git - vlc/blob - modules/codec/avcodec/dxva2.c
8bc9468c4105afe22b96f2a5350c8f6dd32e4ab2
[vlc] / modules / codec / avcodec / dxva2.c
1 /*****************************************************************************
2  * va.c: Video Acceleration helpers
3  *****************************************************************************
4  * Copyright (C) 2009 Geoffroy Couprie
5  * Copyright (C) 2009 Laurent Aimar
6  * $Id$
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
12  * it under the terms of the GNU General Public License as published by
13  * the Free Software Foundation; either version 2 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 General Public License for more details.
20  *
21  * You should have received a copy of the GNU General Public License
22  * along with this program; if not, write to the Free Software
23  * Foundation, 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 <vlc_common.h>
31 #include <vlc_picture.h>
32 #include <vlc_fourcc.h>
33 #include <vlc_cpu.h>
34 #include <assert.h>
35
36 #ifdef HAVE_LIBAVCODEC_AVCODEC_H
37 #   include <libavcodec/avcodec.h>
38 #   ifdef HAVE_AVCODEC_DXVA2
39 #       define DXVA2API_USE_BITFIELDS
40 #       include <libavcodec/dxva2.h>
41 #   endif
42 #elif defined(HAVE_FFMPEG_AVCODEC_H)
43 #   include <ffmpeg/avcodec.h>
44 #else
45 #   include <avcodec.h>
46 #endif
47
48 #include "avcodec.h"
49 #include "va.h"
50 #include "copy.h"
51
52 #ifdef HAVE_AVCODEC_DXVA2
53
54 #include <windows.h>
55 #include <windowsx.h>
56 #include <ole2.h>
57 #include <commctrl.h>
58 #include <shlwapi.h>
59 #include <d3d9.h>
60
61 /* */
62 #define DXVA2_E_NOT_INITIALIZED     MAKE_HRESULT(1, 4, 4096)
63 #define DXVA2_E_NEW_VIDEO_DEVICE    MAKE_HRESULT(1, 4, 4097)
64 #define DXVA2_E_VIDEO_DEVICE_LOCKED MAKE_HRESULT(1, 4, 4098)
65 #define DXVA2_E_NOT_AVAILABLE       MAKE_HRESULT(1, 4, 4099)
66
67 static const GUID DXVA2_ModeMPEG2_MoComp = {
68     0xe6a9f44b, 0x61b0, 0x4563, {0x9e,0xa4,0x63,0xd2,0xa3,0xc6,0xfe,0x66}
69 };
70 static const GUID DXVA2_ModeMPEG2_IDCT = {
71   0xbf22ad00, 0x03ea, 0x4690, {0x80,0x77,0x47,0x33,0x46,0x20,0x9b,0x7e}
72 };
73 static const GUID DXVA2_ModeMPEG2_VLD = {
74    0xee27417f, 0x5e28, 0x4e65, {0xbe,0xea,0x1d,0x26,0xb5,0x08,0xad,0xc9}
75 };
76
77 static const GUID DXVA2_ModeH264_A = {
78     0x1b81be64, 0xa0c7,0x11d3, {0xb9,0x84,0x00,0xc0,0x4f,0x2e,0x73,0xc5}
79 };
80 static const GUID DXVA2_ModeH264_B = {
81     0x1b81be65, 0xa0c7,0x11d3, {0xb9,0x84,0x00,0xc0,0x4f,0x2e,0x73,0xc5}
82 };
83 static const GUID DXVA2_ModeH264_C = {
84     0x1b81be66, 0xa0c7,0x11d3, {0xb9,0x84,0x00,0xc0,0x4f,0x2e,0x73,0xc5}
85 };
86 static const GUID DXVA2_ModeH264_D = {
87     0x1b81be67, 0xa0c7,0x11d3, {0xb9,0x84,0x00,0xc0,0x4f,0x2e,0x73,0xc5}
88 };
89 static const GUID DXVA2_ModeH264_E = {
90     0x1b81be68, 0xa0c7,0x11d3, {0xb9,0x84,0x00,0xc0,0x4f,0x2e,0x73,0xc5}
91 };
92 static const GUID DXVA2_ModeH264_F = {
93     0x1b81be69, 0xa0c7,0x11d3, {0xb9,0x84,0x00,0xc0,0x4f,0x2e,0x73,0xc5}
94 };
95 static const GUID DXVADDI_Intel_ModeH264_A = {
96     0x604F8E64, 0x4951,0x4c54, {0x88,0xFE,0xAB,0xD2,0x5C,0x15,0xB3,0xD6}
97 };
98 static const GUID DXVADDI_Intel_ModeH264_C = {
99     0x604F8E66,0x4951, 0x4c54, {0x88,0xFE,0xAB,0xD2,0x5C,0x15,0xB3,0xD6}
100 };
101 static const GUID DXVADDI_Intel_ModeH264_E = {
102     0x604F8E68,0x4951, 0x4c54, {0x88,0xFE,0xAB,0xD2,0x5C,0x15,0xB3,0xD6}
103 };
104 static const GUID DXVA2_ModeWMV8_A = {
105     0x1b81be80, 0xa0c7,0x11d3, {0xb9,0x84,0x00,0xc0,0x4f,0x2e,0x73,0xc5}
106 };
107 static const GUID DXVA2_ModeWMV8_B = {
108     0x1b81be81, 0xa0c7,0x11d3, {0xb9,0x84,0x00,0xc0,0x4f,0x2e,0x73,0xc5}
109 };
110 static const GUID DXVA2_ModeWMV9_A = {
111     0x1b81be90, 0xa0c7,0x11d3, {0xb9,0x84,0x00,0xc0,0x4f,0x2e,0x73,0xc5}
112 };
113 static const GUID DXVA2_ModeWMV9_B = {
114     0x1b81be91, 0xa0c7,0x11d3, {0xb9,0x84,0x00,0xc0,0x4f,0x2e,0x73,0xc5}
115 };
116 static const GUID DXVA2_ModeWMV9_C = {
117     0x1b81be94, 0xa0c7,0x11d3, {0xb9,0x84,0x00,0xc0,0x4f,0x2e,0x73,0xc5}
118 };
119
120 static const GUID DXVA2_ModeVC1_A = {
121     0x1b81beA0, 0xa0c7,0x11d3, {0xb9,0x84,0x00,0xc0,0x4f,0x2e,0x73,0xc5}
122 };
123 static const GUID DXVA2_ModeVC1_B = {
124     0x1b81beA1, 0xa0c7,0x11d3, {0xb9,0x84,0x00,0xc0,0x4f,0x2e,0x73,0xc5}
125 };
126 static const GUID DXVA2_ModeVC1_C = {
127     0x1b81beA2, 0xa0c7,0x11d3, {0xb9,0x84,0x00,0xc0,0x4f,0x2e,0x73,0xc5}
128 };
129 static const GUID DXVA2_ModeVC1_D = {
130     0x1b81beA3, 0xa0c7,0x11d3, {0xb9,0x84,0x00,0xc0,0x4f,0x2e,0x73,0xc5}
131 };
132
133 /* */
134 typedef struct {
135     const char   *name;
136     const GUID   *guid;
137     int          codec;
138 } dxva2_mode_t;
139 /* XXX Prefered modes must come first */
140 static const dxva2_mode_t dxva2_modes[] = {
141     { "DXVA2_ModeMPEG2_VLD",    &DXVA2_ModeMPEG2_VLD,     CODEC_ID_MPEG2VIDEO },
142     { "DXVA2_ModeMPEG2_MoComp", &DXVA2_ModeMPEG2_MoComp,  0 },
143     { "DXVA2_ModeMPEG2_IDCT",   &DXVA2_ModeMPEG2_IDCT,    0 },
144
145     { "H.264 variable-length decoder (VLD), FGT",               &DXVA2_ModeH264_F,         CODEC_ID_H264 },
146     { "H.264 VLD, no FGT",                                      &DXVA2_ModeH264_E,         CODEC_ID_H264 },
147     { "H.264 VLD, no FGT (Intel)",                              &DXVADDI_Intel_ModeH264_E, CODEC_ID_H264 },
148     { "H.264 IDCT, FGT",                                        &DXVA2_ModeH264_D,         0             },
149     { "H.264 inverse discrete cosine transform (IDCT), no FGT", &DXVA2_ModeH264_C,         0             },
150     { "H.264 inverse discrete cosine transform (IDCT), no FGT (Intel)", &DXVADDI_Intel_ModeH264_C, 0     },
151     { "H.264 MoComp, FGT",                                      &DXVA2_ModeH264_B,         0             },
152     { "H.264 motion compensation (MoComp), no FGT",             &DXVA2_ModeH264_A,         0             },
153     { "H.264 motion compensation (MoComp), no FGT (Intel)",     &DXVADDI_Intel_ModeH264_A, 0             },
154
155     { "Windows Media Video 8 MoComp",           &DXVA2_ModeWMV8_B, 0 },
156     { "Windows Media Video 8 post processing",  &DXVA2_ModeWMV8_A, 0 },
157
158     {  "Windows Media Video 9 IDCT",            &DXVA2_ModeWMV9_C, 0 },
159     {  "Windows Media Video 9 MoComp",          &DXVA2_ModeWMV9_B, 0 },
160     {  "Windows Media Video 9 post processing", &DXVA2_ModeWMV9_A, 0 },
161
162     { "VC-1 VLD",             &DXVA2_ModeVC1_D, CODEC_ID_VC1 },
163     { "VC-1 VLD",             &DXVA2_ModeVC1_D, CODEC_ID_WMV3 },
164     { "VC-1 IDCT",            &DXVA2_ModeVC1_C, 0 },
165     { "VC-1 MoComp",          &DXVA2_ModeVC1_B, 0 },
166     { "VC-1 post processing", &DXVA2_ModeVC1_A, 0 },
167
168     { NULL, NULL, 0 }
169 };
170
171 static const dxva2_mode_t *Dxva2FindMode(const GUID *guid)
172 {
173     for (unsigned i = 0; dxva2_modes[i].name; i++) {
174         if (IsEqualGUID(dxva2_modes[i].guid, guid))
175             return &dxva2_modes[i];
176     }
177     return NULL;
178 }
179
180 /* */
181 typedef struct {
182     const char   *name;
183     D3DFORMAT    format;
184     vlc_fourcc_t codec;
185 } d3d_format_t;
186 /* XXX Prefered format must come first */
187 static const d3d_format_t d3d_formats[] = {
188     { "YV12",   MAKEFOURCC('Y','V','1','2'),    VLC_CODEC_YV12 },
189     { "NV12",   MAKEFOURCC('N','V','1','2'),    VLC_CODEC_NV12 },
190
191     { NULL, 0, 0 }
192 };
193
194 static const d3d_format_t *D3dFindFormat(D3DFORMAT format)
195 {
196     for (unsigned i = 0; d3d_formats[i].name; i++) {
197         if (d3d_formats[i].format == format)
198             return &d3d_formats[i];
199     }
200     return NULL;
201 }
202
203 static const GUID IID_IDirectXVideoDecoderService = {
204     0xfc51a551, 0xd5e7, 0x11d9, {0xaf,0x55,0x00,0x05,0x4e,0x43,0xff,0x02}
205 };
206 static const GUID IID_IDirectXVideoAccelerationService = {
207     0xfc51a550, 0xd5e7, 0x11d9, {0xaf,0x55,0x00,0x05,0x4e,0x43,0xff,0x02}
208 };
209
210 /* */
211 typedef struct {
212     LPDIRECT3DSURFACE9 d3d;
213     int                refcount;
214     unsigned int       order;
215 } vlc_va_surface_t;
216
217 #define VA_DXVA2_MAX_SURFACE_COUNT (64)
218 typedef struct
219 {
220     /* */
221     vlc_va_t va;
222
223     /* */
224     vlc_object_t *log;
225     int          codec_id;
226
227     /* DLL */
228         HINSTANCE             hd3d9_dll;
229     HINSTANCE             hdxva2_dll;
230
231     /* Direct3D */
232     D3DPRESENT_PARAMETERS  d3dpp;
233     LPDIRECT3D9            d3dobj;
234     D3DADAPTER_IDENTIFIER9 d3dai;
235     LPDIRECT3DDEVICE9      d3ddev;
236
237     /* Device manager */
238     UINT                     token;
239     IDirect3DDeviceManager9  *devmng;
240     HANDLE                   device;
241
242     /* Video service */
243     IDirectXVideoDecoderService  *vs;
244     GUID                         input;
245     D3DFORMAT                    render;
246
247     /* Video decoder */
248     DXVA2_ConfigPictureDecode    cfg;
249     IDirectXVideoDecoder         *decoder;
250
251     /* Option conversion */
252     D3DFORMAT                    output;
253     copy_cache_t                 surface_cache;
254
255     /* */
256     struct dxva_context hw;
257
258     /* */
259     unsigned     surface_count;
260     unsigned     surface_order;
261     int          surface_width;
262     int          surface_height;
263     vlc_fourcc_t surface_chroma;
264
265     vlc_va_surface_t surface[VA_DXVA2_MAX_SURFACE_COUNT];
266     LPDIRECT3DSURFACE9 hw_surface[VA_DXVA2_MAX_SURFACE_COUNT];
267 } vlc_va_dxva2_t;
268
269 /* */
270 static vlc_va_dxva2_t *vlc_va_dxva2_Get(void *external)
271 {
272     assert(external == (void*)(&((vlc_va_dxva2_t*)external)->va));
273     return external;
274 }
275
276 /* */
277 static int D3dCreateDevice(vlc_va_dxva2_t *);
278 static void D3dDestroyDevice(vlc_va_dxva2_t *);
279 static char *DxDescribe(vlc_va_dxva2_t *);
280
281 static int D3dCreateDeviceManager(vlc_va_dxva2_t *);
282 static void D3dDestroyDeviceManager(vlc_va_dxva2_t *);
283
284 static int DxCreateVideoService(vlc_va_dxva2_t *);
285 static void DxDestroyVideoService(vlc_va_dxva2_t *);
286 static int DxFindVideoServiceConversion(vlc_va_dxva2_t *, GUID *input, D3DFORMAT *output);
287
288 static int DxCreateVideoDecoder(vlc_va_dxva2_t *,
289                                 int codec_id, const video_format_t *);
290 static void DxDestroyVideoDecoder(vlc_va_dxva2_t *);
291 static int DxResetVideoDecoder(vlc_va_dxva2_t *);
292
293 static void DxCreateVideoConversion(vlc_va_dxva2_t *);
294 static void DxDestroyVideoConversion(vlc_va_dxva2_t *);
295
296 /* */
297 static int Setup(vlc_va_t *external, void **hw, vlc_fourcc_t *chroma,
298                  int width, int height)
299 {
300     vlc_va_dxva2_t *va = vlc_va_dxva2_Get(external);
301
302     if (va->surface_width  == width &&
303         va->surface_height == height)
304         goto ok;
305
306     /* */
307     DxDestroyVideoConversion(va);
308     DxDestroyVideoDecoder(va);
309
310     *hw = NULL;
311     *chroma = 0;
312     if (width <= 0 || height <= 0)
313         return VLC_EGENERIC;
314
315     /* FIXME transmit a video_format_t by VaSetup directly */
316     video_format_t fmt;
317     memset(&fmt, 0, sizeof(fmt));
318     fmt.i_width = width;
319     fmt.i_height = height;
320
321     if (DxCreateVideoDecoder(va, va->codec_id, &fmt))
322         return VLC_EGENERIC;
323     /* */
324     va->hw.decoder = va->decoder;
325     va->hw.cfg = &va->cfg;
326     va->hw.surface_count = va->surface_count;
327     va->hw.surface = va->hw_surface;
328     for (unsigned i = 0; i < va->surface_count; i++)
329         va->hw.surface[i] = va->surface[i].d3d;
330
331     /* */
332     DxCreateVideoConversion(va);
333
334     /* */
335 ok:
336     *hw = &va->hw;
337     const d3d_format_t *output = D3dFindFormat(va->output);
338     *chroma = output->codec;
339
340     return VLC_SUCCESS;
341 }
342
343 static int Extract(vlc_va_t *external, picture_t *picture, AVFrame *ff)
344 {
345     vlc_va_dxva2_t *va = vlc_va_dxva2_Get(external);
346     LPDIRECT3DSURFACE9 d3d = (LPDIRECT3DSURFACE9)(uintptr_t)ff->data[3];
347
348     if (!va->surface_cache.buffer)
349         return VLC_EGENERIC;
350
351     /* */
352     assert(va->output == MAKEFOURCC('Y','V','1','2'));
353
354     /* */
355     D3DLOCKED_RECT lock;
356     if (FAILED(IDirect3DSurface9_LockRect(d3d, &lock, NULL, D3DLOCK_READONLY))) {
357         msg_Err(va->log, "Failed to lock surface");
358         return VLC_EGENERIC;
359     }
360
361     if (va->render == MAKEFOURCC('Y','V','1','2')) {
362         uint8_t *plane[3] = {
363             lock.pBits,
364             (uint8_t*)lock.pBits + lock.Pitch * va->surface_height,
365             (uint8_t*)lock.pBits + lock.Pitch * va->surface_height
366                                  + (lock.Pitch/2) * (va->surface_height/2)
367         };
368         size_t  pitch[3] = {
369             lock.Pitch,
370             lock.Pitch / 2,
371             lock.Pitch / 2,
372         };
373         CopyFromYv12(picture, plane, pitch,
374                      va->surface_width, va->surface_height,
375                      &va->surface_cache);
376     } else {
377         assert(va->render == MAKEFOURCC('N','V','1','2'));
378         uint8_t *plane[2] = {
379             lock.pBits,
380             (uint8_t*)lock.pBits + lock.Pitch * va->surface_height
381         };
382         size_t  pitch[2] = {
383             lock.Pitch,
384             lock.Pitch,
385         };
386         CopyFromNv12(picture, plane, pitch,
387                      va->surface_width, va->surface_height,
388                      &va->surface_cache);
389     }
390
391     /* */
392     IDirect3DSurface9_UnlockRect(d3d);
393     return VLC_SUCCESS;
394 }
395 /* FIXME it is nearly common with VAAPI */
396 static int Get(vlc_va_t *external, AVFrame *ff)
397 {
398     vlc_va_dxva2_t *va = vlc_va_dxva2_Get(external);
399
400     /* Check the device */
401     HRESULT hr = IDirect3DDeviceManager9_TestDevice(va->devmng, va->device);
402     if (hr == DXVA2_E_NEW_VIDEO_DEVICE) {
403         if (DxResetVideoDecoder(va))
404             return VLC_EGENERIC;
405     } else if (FAILED(hr)) {
406         msg_Err(va->log, "IDirect3DDeviceManager9_TestDevice %u", (unsigned)hr);
407         return VLC_EGENERIC;
408     }
409
410     /* Grab an unused surface, in case none are, try the oldest
411      * XXX using the oldest is a workaround in case a problem happens with ffmpeg */
412     unsigned i, old;
413     for (i = 0, old = 0; i < va->surface_count; i++) {
414         vlc_va_surface_t *surface = &va->surface[i];
415
416         if (!surface->refcount)
417             break;
418
419         if (surface->order < va->surface[old].order)
420             old = i;
421     }
422     if (i >= va->surface_count)
423         i = old;
424
425     vlc_va_surface_t *surface = &va->surface[i];
426
427     surface->refcount = 1;
428     surface->order = va->surface_order++;
429
430     /* */
431     for (int i = 0; i < 4; i++) {
432         ff->data[i] = NULL;
433         ff->linesize[i] = 0;
434
435         if (i == 0 || i == 3)
436             ff->data[i] = (void*)surface->d3d;/* Yummie */
437     }
438     return VLC_SUCCESS;
439 }
440 static void Release(vlc_va_t *external, AVFrame *ff)
441 {
442     vlc_va_dxva2_t *va = vlc_va_dxva2_Get(external);
443     LPDIRECT3DSURFACE9 d3d = (LPDIRECT3DSURFACE9)(uintptr_t)ff->data[3];
444
445     for (unsigned i = 0; i < va->surface_count; i++) {
446         vlc_va_surface_t *surface = &va->surface[i];
447
448         if (surface->d3d == d3d)
449             surface->refcount--;
450     }
451 }
452 static void Close(vlc_va_t *external)
453 {
454     vlc_va_dxva2_t *va = vlc_va_dxva2_Get(external);
455
456     DxDestroyVideoConversion(va);
457     DxDestroyVideoDecoder(va);
458     DxDestroyVideoService(va);
459     D3dDestroyDeviceManager(va);
460     D3dDestroyDevice(va);
461
462     if (va->hdxva2_dll)
463         FreeLibrary(va->hdxva2_dll);
464     if (va->hd3d9_dll)
465         FreeLibrary(va->hd3d9_dll);
466
467     free(va->va.description);
468     free(va);
469 }
470
471 vlc_va_t *vlc_va_NewDxva2(vlc_object_t *log, int codec_id)
472 {
473     vlc_va_dxva2_t *va = calloc(1, sizeof(*va));
474     if (!va)
475         return NULL;
476
477     /* */
478     va->log = log;
479     va->codec_id = codec_id;
480
481     /* Load dll*/
482     va->hd3d9_dll = LoadLibrary(TEXT("D3D9.DLL"));
483     if (!va->hd3d9_dll) {
484         msg_Warn(va->log, "cannot load d3d9.dll");
485         goto error;
486     }
487     va->hdxva2_dll = LoadLibrary(TEXT("DXVA2.DLL"));
488     if (!va->hdxva2_dll) {
489         msg_Warn(va->log, "cannot load dxva2.dll");
490         goto error;
491     }
492     msg_Dbg(va->log, "DLLs loaded");
493
494     /* */
495     if (D3dCreateDevice(va)) {
496         msg_Err(va->log, "Failed to create Direct3D device");
497         goto error;
498     }
499     msg_Dbg(va->log, "D3dCreateDevice succeed");
500
501     if (D3dCreateDeviceManager(va)) {
502         msg_Err(va->log, "D3dCreateDeviceManager failed");
503         goto error;
504     }
505
506     if (DxCreateVideoService(va)) {
507         msg_Err(va->log, "DxCreateVideoService failed");
508         goto error;
509     }
510
511     /* */
512     if (DxFindVideoServiceConversion(va, &va->input, &va->render)) {
513         msg_Err(va->log, "DxFindVideoServiceConversion failed");
514         goto error;
515     }
516
517     /* TODO print the hardware name/vendor for debugging purposes */
518     va->va.description = DxDescribe(va);
519     va->va.setup   = Setup;
520     va->va.get     = Get;
521     va->va.release = Release;
522     va->va.extract = Extract;
523     va->va.close   = Close;
524     return &va->va;
525
526 error:
527     Close(&va->va);
528     return NULL;
529 }
530 /* */
531
532 /**
533  * It creates a Direct3D device usable for DXVA 2
534  */
535 static int D3dCreateDevice(vlc_va_dxva2_t *va)
536 {
537     /* */
538     LPDIRECT3D9 (WINAPI *Create9)(UINT SDKVersion);
539     Create9 = (void *)GetProcAddress(va->hd3d9_dll,
540                                      TEXT("Direct3DCreate9"));
541     if (!Create9) {
542         msg_Err(va->log, "Cannot locate reference to Direct3DCreate9 ABI in DLL");
543         return VLC_EGENERIC;
544     }
545
546     /* */
547     LPDIRECT3D9 d3dobj;
548     d3dobj = Create9(D3D_SDK_VERSION);
549     if (!d3dobj) {
550         msg_Err(va->log, "Direct3DCreate9 failed");
551         return VLC_EGENERIC;
552     }
553     va->d3dobj = d3dobj;
554
555     /* */
556     D3DADAPTER_IDENTIFIER9 *d3dai = &va->d3dai;
557     if (FAILED(IDirect3D9_GetAdapterIdentifier(va->d3dobj,
558                                                D3DADAPTER_DEFAULT, 0, d3dai))) {
559         msg_Warn(va->log, "IDirect3D9_GetAdapterIdentifier failed");
560         ZeroMemory(d3dai, sizeof(*d3dai));
561     }
562
563     /* */
564     D3DPRESENT_PARAMETERS *d3dpp = &va->d3dpp;
565     ZeroMemory(d3dpp, sizeof(*d3dpp));
566     d3dpp->Flags                  = D3DPRESENTFLAG_VIDEO;
567     d3dpp->Windowed               = TRUE;
568     d3dpp->hDeviceWindow          = NULL;
569     d3dpp->SwapEffect             = D3DSWAPEFFECT_DISCARD;
570     d3dpp->MultiSampleType        = D3DMULTISAMPLE_NONE;
571     d3dpp->PresentationInterval   = D3DPRESENT_INTERVAL_DEFAULT;
572     d3dpp->BackBufferCount        = 0;                  /* FIXME what to put here */
573     d3dpp->BackBufferFormat       = D3DFMT_X8R8G8B8;    /* FIXME what to put here */
574     d3dpp->BackBufferWidth        = 0;
575     d3dpp->BackBufferHeight       = 0;
576     d3dpp->EnableAutoDepthStencil = FALSE;
577
578     /* Direct3D needs a HWND to create a device, even without using ::Present
579     this HWND is used to alert Direct3D when there's a change of focus window.
580     For now, use GetShellWindow, as it looks harmless */
581     LPDIRECT3DDEVICE9 d3ddev;
582     if (FAILED(IDirect3D9_CreateDevice(d3dobj, D3DADAPTER_DEFAULT,
583                                        D3DDEVTYPE_HAL, GetShellWindow(),
584                                        D3DCREATE_SOFTWARE_VERTEXPROCESSING |
585                                        D3DCREATE_MULTITHREADED,
586                                        d3dpp, &d3ddev))) {
587         msg_Err(va->log, "IDirect3D9_CreateDevice failed");
588         return VLC_EGENERIC;
589     }
590     va->d3ddev = d3ddev;
591
592     return VLC_SUCCESS;
593 }
594 /**
595  * It releases a Direct3D device and its resources.
596  */
597 static void D3dDestroyDevice(vlc_va_dxva2_t *va)
598 {
599     if (va->d3ddev)
600         IDirect3DDevice9_Release(va->d3ddev);
601     if (va->d3dobj)
602         IDirect3D9_Release(va->d3dobj);
603 }
604 /**
605  * It describes our Direct3D object
606  */
607 static char *DxDescribe(vlc_va_dxva2_t *va)
608 {
609     static const struct {
610         unsigned id;
611         char     name[32];
612     } vendors [] = {
613         { 0x1002, "ATI" },
614         { 0x10DE, "NVIDIA" },
615         { 0x8086, "Intel" },
616         { 0x5333, "S3 Graphics" },
617         { 0, "" }
618     };
619     D3DADAPTER_IDENTIFIER9 *id = &va->d3dai;
620
621     const char *vendor = "Unknown";
622     for (int i = 0; vendors[i].id != 0; i++) {
623         if (vendors[i].id == id->VendorId) {
624             vendor = vendors[i].name;
625             break;
626         }
627     }
628
629     char *description;
630     if (asprintf(&description, "DXVA2 (%.*s, vendor %d(%s), device %d, revision %d)",
631                  sizeof(id->Description), id->Description,
632                  id->VendorId, vendor, id->DeviceId, id->Revision) < 0)
633         return NULL;
634     return description;
635 }
636
637 /**
638  * It creates a Direct3D device manager
639  */
640 static int D3dCreateDeviceManager(vlc_va_dxva2_t *va)
641 {
642     HRESULT (WINAPI *CreateDeviceManager9)(UINT *pResetToken,
643                                            IDirect3DDeviceManager9 **);
644     CreateDeviceManager9 =
645       (void *)GetProcAddress(va->hdxva2_dll,
646                              TEXT("DXVA2CreateDirect3DDeviceManager9"));
647
648     if (!CreateDeviceManager9) {
649         msg_Err(va->log, "cannot load function\n");
650         return VLC_EGENERIC;
651     }
652     msg_Dbg(va->log, "OurDirect3DCreateDeviceManager9 Success!");
653
654     UINT token;
655     IDirect3DDeviceManager9 *devmng;
656     if (FAILED(CreateDeviceManager9(&token, &devmng))) {
657         msg_Err(va->log, " OurDirect3DCreateDeviceManager9 failed");
658         return VLC_EGENERIC;
659     }
660     va->token  = token;
661     va->devmng = devmng;
662     msg_Info(va->log, "obtained IDirect3DDeviceManager9");
663
664     HRESULT hr = IDirect3DDeviceManager9_ResetDevice(devmng, va->d3ddev, token);
665     if (FAILED(hr)) {
666         msg_Err(va->log, "IDirect3DDeviceManager9_ResetDevice failed: %08x", (unsigned)hr);
667         return VLC_EGENERIC;
668     }
669     return VLC_SUCCESS;
670 }
671 /**
672  * It destroys a Direct3D device manager
673  */
674 static void D3dDestroyDeviceManager(vlc_va_dxva2_t *va)
675 {
676     if (va->devmng)
677         IDirect3DDeviceManager9_Release(va->devmng);
678 }
679
680 /**
681  * It creates a DirectX video service
682  */
683 static int DxCreateVideoService(vlc_va_dxva2_t *va)
684 {
685     HRESULT (WINAPI *CreateVideoService)(IDirect3DDevice9 *,
686                                          REFIID riid,
687                                          void **ppService);
688     CreateVideoService =
689       (void *)GetProcAddress(va->hdxva2_dll,
690                              TEXT("DXVA2CreateVideoService"));
691
692     if (!CreateVideoService) {
693         msg_Err(va->log, "cannot load function\n");
694         return 4;
695     }
696     msg_Info(va->log, "DXVA2CreateVideoService Success!");
697
698     HRESULT hr;
699
700     HANDLE device;
701     hr = IDirect3DDeviceManager9_OpenDeviceHandle(va->devmng, &device);
702     if (FAILED(hr)) {
703         msg_Err(va->log, "OpenDeviceHandle failed");
704         return VLC_EGENERIC;
705     }
706     va->device = device;
707
708     IDirectXVideoDecoderService *vs;
709     hr = IDirect3DDeviceManager9_GetVideoService(va->devmng, device,
710                                                  &IID_IDirectXVideoDecoderService,
711                                                  &vs);
712     if (FAILED(hr)) {
713         msg_Err(va->log, "GetVideoService failed");
714         return VLC_EGENERIC;
715     }
716     va->vs = vs;
717
718     return VLC_SUCCESS;
719 }
720 /**
721  * It destroys a DirectX video service
722  */
723 static void DxDestroyVideoService(vlc_va_dxva2_t *va)
724 {
725     if (va->device)
726         IDirect3DDeviceManager9_CloseDeviceHandle(va->devmng, va->device);
727     if (va->vs)
728         IDirectXVideoDecoderService_Release(va->vs);
729 }
730 /**
731  * Find the best suited decoder mode GUID and render format.
732  */
733 static int DxFindVideoServiceConversion(vlc_va_dxva2_t *va, GUID *input, D3DFORMAT *output)
734 {
735     /* Retreive supported modes from the decoder service */
736     UINT input_count = 0;
737     GUID *input_list = NULL;
738     if (FAILED(IDirectXVideoDecoderService_GetDecoderDeviceGuids(va->vs,
739                                                                  &input_count,
740                                                                  &input_list))) {
741         msg_Err(va->log, "IDirectXVideoDecoderService_GetDecoderDeviceGuids failed");
742         return VLC_EGENERIC;
743     }
744     for (unsigned i = 0; i < input_count; i++) {
745         const GUID *g = &input_list[i];
746         const dxva2_mode_t *mode = Dxva2FindMode(g);
747         if (mode) {
748             msg_Dbg(va->log, "- '%s' is supported by hardware", mode->name);
749         } else {
750             msg_Warn(va->log, "- Unknown GUID = %08X-%04x-%04x-XXXX",
751                      (unsigned)g->Data1, g->Data2, g->Data3);
752         }
753     }
754
755     /* Try all supported mode by our priority */
756     for (unsigned i = 0; dxva2_modes[i].name; i++) {
757         const dxva2_mode_t *mode = &dxva2_modes[i];
758         if (!mode->codec || mode->codec != va->codec_id)
759             continue;
760
761         /* */
762         bool is_suported = false;
763         for (const GUID *g = &input_list[0]; !is_suported && g < &input_list[input_count]; g++) {
764             is_suported = IsEqualGUID(mode->guid, g);
765         }
766         if (!is_suported)
767             continue;
768
769         /* */
770         msg_Dbg(va->log, "Trying to use '%s' as input", mode->name);
771         UINT      output_count = 0;
772         D3DFORMAT *output_list = NULL;
773         if (FAILED(IDirectXVideoDecoderService_GetDecoderRenderTargets(va->vs, mode->guid,
774                                                                        &output_count,
775                                                                        &output_list))) {
776             msg_Err(va->log, "IDirectXVideoDecoderService_GetDecoderRenderTargets failed");
777             continue;
778         }
779         for (unsigned j = 0; j < output_count; j++) {
780             const D3DFORMAT f = output_list[j];
781             const d3d_format_t *format = D3dFindFormat(f);
782             if (format) {
783                 msg_Dbg(va->log, "%s is supported for output", format->name);
784             } else {
785                 msg_Dbg(va->log, "%d is supported for output (%4.4s)", f, (const char*)&f);
786             }
787         }
788
789         /* */
790         for (unsigned j = 0; d3d_formats[j].name; j++) {
791             const d3d_format_t *format = &d3d_formats[j];
792
793             /* */
794             bool is_suported = false;
795             for (unsigned k = 0; !is_suported && k < output_count; k++) {
796                 is_suported = format->format == output_list[k];
797             }
798             if (!is_suported)
799                 continue;
800
801             /* We have our solution */
802             msg_Dbg(va->log, "Using '%s' to decode to '%s'", mode->name, format->name);
803             *input  = *mode->guid;
804             *output = format->format;
805             CoTaskMemFree(output_list);
806             CoTaskMemFree(input_list);
807             return VLC_SUCCESS;
808         }
809         CoTaskMemFree(output_list);
810     }
811     CoTaskMemFree(input_list);
812     return VLC_EGENERIC;
813 }
814
815 /**
816  * It creates a DXVA2 decoder using the given video format
817  */
818 static int DxCreateVideoDecoder(vlc_va_dxva2_t *va,
819                                 int codec_id, const video_format_t *fmt)
820 {
821     /* */
822     msg_Dbg(va->log, "DxCreateVideoDecoder id %d %dx%d",
823             codec_id, fmt->i_width, fmt->i_height);
824
825     /* Allocates all surfaces needed for the decoder */
826     switch (codec_id) {
827     case CODEC_ID_H264:
828         va->surface_count = 16 + 1;
829         break;
830     default:
831         va->surface_count = 2 + 1;
832         break;
833     }
834     LPDIRECT3DSURFACE9 surface_list[VA_DXVA2_MAX_SURFACE_COUNT];
835     if (FAILED(IDirectXVideoDecoderService_CreateSurface(va->vs,
836                                                          fmt->i_width,
837                                                          fmt->i_height,
838                                                          va->surface_count - 1,
839                                                          va->render,
840                                                          D3DPOOL_DEFAULT,
841                                                          0,
842                                                          DXVA2_VideoDecoderRenderTarget,
843                                                          surface_list,
844                                                          NULL))) {
845         msg_Err(va->log, "IDirectXVideoAccelerationService_CreateSurface failed\n");
846         va->surface_count = 0;
847         return VLC_EGENERIC;
848     }
849     for (unsigned i = 0; i < va->surface_count; i++) {
850         vlc_va_surface_t *surface = &va->surface[i];
851         surface->d3d = surface_list[i];
852         surface->refcount = 0;
853         surface->order = 0;
854     }
855     va->surface_width  = fmt->i_width;
856     va->surface_height = fmt->i_height;
857     msg_Dbg(va->log, "IDirectXVideoAccelerationService_CreateSurface succeed with %d surfaces (%dx%d)",
858             va->surface_count, fmt->i_width, fmt->i_height);
859
860     /* */
861     DXVA2_VideoDesc dsc;
862     ZeroMemory(&dsc, sizeof(dsc));
863     dsc.SampleWidth     = fmt->i_width;
864     dsc.SampleHeight    = fmt->i_height;
865     dsc.Format          = va->render;
866     if (fmt->i_frame_rate > 0 && fmt->i_frame_rate_base > 0) {
867         dsc.InputSampleFreq.Numerator   = fmt->i_frame_rate;
868         dsc.InputSampleFreq.Denominator = fmt->i_frame_rate_base;
869     } else {
870         dsc.InputSampleFreq.Numerator   = 0;
871         dsc.InputSampleFreq.Denominator = 0;
872     }
873     dsc.OutputFrameFreq = dsc.InputSampleFreq;
874     dsc.UABProtectionLevel = FALSE;
875     dsc.Reserved = 0;
876
877     /* FIXME I am unsure we can let unknown everywhere */
878     DXVA2_ExtendedFormat *ext = &dsc.SampleFormat;
879     ext->SampleFormat = 0;//DXVA2_SampleUnknown;
880     ext->VideoChromaSubsampling = 0;//DXVA2_VideoChromaSubsampling_Unknown;
881     ext->NominalRange = 0;//DXVA2_NominalRange_Unknown;
882     ext->VideoTransferMatrix = 0;//DXVA2_VideoTransferMatrix_Unknown;
883     ext->VideoLighting = 0;//DXVA2_VideoLighting_Unknown;
884     ext->VideoPrimaries = 0;//DXVA2_VideoPrimaries_Unknown;
885     ext->VideoTransferFunction = 0;//DXVA2_VideoTransFunc_Unknown;
886
887     /* List all configurations available for the decoder */
888     UINT                      cfg_count = 0;
889     DXVA2_ConfigPictureDecode *cfg_list = NULL;
890     if (FAILED(IDirectXVideoDecoderService_GetDecoderConfigurations(va->vs,
891                                                                     &va->input,
892                                                                     &dsc,
893                                                                     NULL,
894                                                                     &cfg_count,
895                                                                     &cfg_list))) {
896         msg_Err(va->log, "IDirectXVideoDecoderService_GetDecoderConfigurations failed\n");
897         return VLC_EGENERIC;
898     }
899     msg_Dbg(va->log, "we got %d decoder configurations", cfg_count);
900
901     /* Select the best decoder configuration */
902     bool has_cfg = false;
903     for (unsigned i = 0; i < cfg_count; i++) {
904         const DXVA2_ConfigPictureDecode *cfg = &cfg_list[i];
905
906         /* */
907         msg_Dbg(va->log, "configuration[%d] ConfigBitstreamRaw %d",
908                 i, cfg->ConfigBitstreamRaw);
909
910         /* */
911         if ((!has_cfg && cfg->ConfigBitstreamRaw == 1) ||
912             (codec_id == CODEC_ID_H264 && cfg->ConfigBitstreamRaw == 2)) {
913             va->cfg = *cfg;
914             has_cfg = true;
915         }
916     }
917     CoTaskMemFree(cfg_list);
918     if (!has_cfg) {
919         msg_Err(va->log, "Failed to find a supported decoder configuration");
920         return VLC_EGENERIC;
921     }
922
923     /* Create the decoder */
924     IDirectXVideoDecoder *decoder;
925     if (FAILED(IDirectXVideoDecoderService_CreateVideoDecoder(va->vs,
926                                                               &va->input,
927                                                               &dsc,
928                                                               &va->cfg,
929                                                               surface_list,
930                                                               va->surface_count,
931                                                               &decoder))) {
932         msg_Err(va->log, "IDirectXVideoDecoderService_CreateVideoDecoder failed\n");
933         return VLC_EGENERIC;
934     }
935     va->decoder = decoder;
936     msg_Dbg(va->log, "IDirectXVideoDecoderService_CreateVideoDecoder succeed");
937     return VLC_SUCCESS;
938 }
939 static void DxDestroyVideoDecoder(vlc_va_dxva2_t *va)
940 {
941     if (va->decoder)
942         IDirectXVideoDecoder_Release(va->decoder);
943     va->decoder = NULL;
944
945     for (unsigned i = 0; i < va->surface_count; i++)
946         IDirect3DSurface9_Release(va->surface[i].d3d);
947     va->surface_count = 0;
948 }
949 static int DxResetVideoDecoder(vlc_va_dxva2_t *va)
950 {
951     msg_Err(va->log, "DxResetVideoDecoder unimplemented");
952     return VLC_EGENERIC;
953 }
954
955 static void DxCreateVideoConversion(vlc_va_dxva2_t *va)
956 {
957     switch (va->render) {
958     case MAKEFOURCC('N','V','1','2'):
959         va->output = MAKEFOURCC('Y','V','1','2');
960         break;
961     default:
962         va->output = va->render;
963         break;
964     }
965     CopyInitCache(&va->surface_cache, va->surface_width);
966 }
967 static void DxDestroyVideoConversion(vlc_va_dxva2_t *va)
968 {
969     CopyCleanCache(&va->surface_cache);
970 }
971 #else
972 vlc_va_t *vlc_va_NewDxva2(vlc_object_t *log, int codec_id)
973 {
974     (void)log;
975     (void)codec_id;
976     return NULL;
977 }
978 #endif