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