]> git.sesse.net Git - vlc/blob - modules/video_output/msw/directx.c
e676b05c26e2bf4aa251e76a2c9cb4d3edf12c05
[vlc] / modules / video_output / msw / directx.c
1 /*****************************************************************************
2  * directx.c: Windows DirectDraw video output
3  *****************************************************************************
4  * Copyright (C) 2001-2009 the VideoLAN team
5  * $Id$
6  *
7  * Authors: Gildas Bazin <gbazin@videolan.org>
8  *
9  * This program is free software; you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License as published by
11  * the Free Software Foundation; either version 2 of the License, or
12  * (at your option) any later version.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  * GNU General Public License for more details.
18  *
19  * You should have received a copy of the GNU General Public License
20  * along with this program; if not, write to the Free Software
21  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
22  *****************************************************************************/
23
24 /*****************************************************************************
25  * Preamble:
26  *
27  * This plugin will use YUV overlay if supported, using overlay will result in
28  * the best video quality (hardware interpolation when rescaling the picture)
29  * and the fastest display as it requires less processing.
30  *
31  * If YUV overlay is not supported this plugin will use RGB offscreen video
32  * surfaces that will be blitted onto the primary surface (display) to
33  * effectively display the pictures. This fallback method also enables us to
34  * display video in window mode.
35  *
36  *****************************************************************************/
37 #ifdef HAVE_CONFIG_H
38 # include "config.h"
39 #endif
40 #include <assert.h>
41
42 #include <vlc_common.h>
43 #include <vlc_plugin.h>
44 #include <vlc_vout_display.h>
45 #include <vlc_playlist.h>   /* needed for wallpaper */
46
47 #include <ddraw.h>
48 #include <commctrl.h>       /* ListView_(Get|Set)* */
49
50 #ifndef UNDER_CE
51 #   include <multimon.h>
52 #endif
53 #undef GetSystemMetrics
54
55 #ifndef MONITOR_DEFAULTTONEAREST
56 #   define MONITOR_DEFAULTTONEAREST 2
57 #endif
58
59 #include "common.h"
60
61 #ifdef UNICODE
62 #   error "Unicode mode not supported"
63 #endif
64
65 /*****************************************************************************
66  * Module descriptor
67  *****************************************************************************/
68 #define HW_YUV_TEXT N_("Use hardware YUV->RGB conversions")
69 #define HW_YUV_LONGTEXT N_(\
70     "Try to use hardware acceleration for YUV->RGB conversions. " \
71     "This option doesn't have any effect when using overlays.")
72
73 #define SYSMEM_TEXT N_("Use video buffers in system memory")
74 #define SYSMEM_LONGTEXT N_(\
75     "Create video buffers in system memory instead of video memory. This " \
76     "isn't recommended as usually using video memory allows to benefit from " \
77     "more hardware acceleration (like rescaling or YUV->RGB conversions). " \
78     "This option doesn't have any effect when using overlays.")
79
80 #define TRIPLEBUF_TEXT N_("Use triple buffering for overlays")
81 #define TRIPLEBUF_LONGTEXT N_(\
82     "Try to use triple buffering when using YUV overlays. That results in " \
83     "much better video quality (no flickering).")
84
85 #define DEVICE_TEXT N_("Name of desired display device")
86 #define DEVICE_LONGTEXT N_("In a multiple monitor configuration, you can " \
87     "specify the Windows device name of the display that you want the video " \
88     "window to open on. For example, \"\\\\.\\DISPLAY1\" or " \
89     "\"\\\\.\\DISPLAY2\".")
90
91 #define DX_HELP N_("Recommended video output for Windows XP. " \
92     "Incompatible with Vista's Aero interface" )
93
94 static const char * const device[] = { "" };
95 static const char * const device_text[] = { N_("Default") };
96
97 static int  Open (vlc_object_t *);
98 static void Close(vlc_object_t *);
99
100 static int  FindDevicesCallback(vlc_object_t *, char const *,
101                                 vlc_value_t, vlc_value_t, void *);
102 vlc_module_begin()
103     set_shortname("DirectX")
104     set_description(N_("DirectX (DirectDraw) video output"))
105     set_help(DX_HELP)
106     set_category(CAT_VIDEO)
107     set_subcategory(SUBCAT_VIDEO_VOUT)
108     add_bool("directx-hw-yuv", true, NULL, HW_YUV_TEXT, HW_YUV_LONGTEXT,
109               true)
110     add_bool("directx-use-sysmem", false, NULL, SYSMEM_TEXT, SYSMEM_LONGTEXT,
111               true)
112     add_bool("directx-3buffering", true, NULL, TRIPLEBUF_TEXT,
113               TRIPLEBUF_LONGTEXT, true)
114     add_string("directx-device", "", NULL, DEVICE_TEXT, DEVICE_LONGTEXT, true)
115         change_string_list(device, device_text, FindDevicesCallback)
116         change_action_add(FindDevicesCallback, N_("Refresh list"))
117
118     set_capability("vout display", 100)
119     add_shortcut("directx")
120     set_callbacks(Open, Close)
121
122     /* FIXME: Hack to avoid unregistering our window class */
123     cannot_unload_broken_library()
124 vlc_module_end()
125
126 #if 0 /* FIXME */
127     /* check if we registered a window class because we need to
128      * unregister it */
129     WNDCLASS wndclass;
130     if (GetClassInfo(GetModuleHandle(NULL), "VLC DirectX", &wndclass))
131         UnregisterClass("VLC DirectX", GetModuleHandle(NULL));
132 #endif
133
134 /*****************************************************************************
135  * Local prototypes.
136  *****************************************************************************/
137
138 struct picture_sys_t {
139     LPDIRECTDRAWSURFACE2 surface;
140     LPDIRECTDRAWSURFACE2 front_surface;
141 };
142
143 /*****************************************************************************
144  * DirectDraw GUIDs.
145  * Defining them here allows us to get rid of the dxguid library during
146  * the linking stage.
147  *****************************************************************************/
148 #include <initguid.h>
149 #undef GUID_EXT
150 #define GUID_EXT
151 DEFINE_GUID(IID_IDirectDraw2, 0xB3A6F3E0,0x2B43,0x11CF,0xA2,0xDE,0x00,0xAA,0x00,0xB9,0x33,0x56);
152 DEFINE_GUID(IID_IDirectDrawSurface2, 0x57805885,0x6eec,0x11cf,0x94,0x41,0xa8,0x23,0x03,0xc1,0x0e,0x27);
153
154 static picture_pool_t *Pool  (vout_display_t *, unsigned);
155 static void           Display(vout_display_t *, picture_t *);
156 static int            Control(vout_display_t *, int, va_list);
157 static void           Manage (vout_display_t *);
158
159 /* */
160 static int WallpaperCallback(vlc_object_t *, char const *,
161                              vlc_value_t, vlc_value_t, void *);
162
163 static int  DirectXOpen(vout_display_t *, video_format_t *fmt);
164 static void DirectXClose(vout_display_t *);
165
166 static int  DirectXLock(picture_t *);
167 static void DirectXUnlock(picture_t *);
168
169 static int DirectXUpdateOverlay(vout_display_t *, LPDIRECTDRAWSURFACE2 surface);
170
171 static void WallpaperChange(vout_display_t *vd, bool use_wallpaper);
172
173 /** This function allocates and initialize the DirectX vout display.
174  */
175 static int Open(vlc_object_t *object)
176 {
177     vout_display_t *vd = (vout_display_t *)object;
178     vout_display_sys_t *sys;
179
180     /* Allocate structure */
181     vd->sys = sys = calloc(1, sizeof(*sys));
182     if (!sys)
183         return VLC_ENOMEM;
184
185     /* Load direct draw DLL */
186     sys->hddraw_dll = LoadLibrary(_T("DDRAW.DLL"));
187     if (!sys->hddraw_dll) {
188         msg_Warn(vd, "DirectXInitDDraw failed loading ddraw.dll");
189         free(sys);
190         return VLC_EGENERIC;
191     }
192
193     /* */
194     HMODULE huser32 = GetModuleHandle(_T("USER32"));
195     if (huser32) {
196         sys->MonitorFromWindow = (void*)GetProcAddress(huser32, _T("MonitorFromWindow"));
197         sys->GetMonitorInfo = (void*)GetProcAddress(huser32, _T("GetMonitorInfoA"));
198     } else {
199         sys->MonitorFromWindow = NULL;
200         sys->GetMonitorInfo = NULL;
201     }
202
203     /* */
204     sys->use_wallpaper = var_CreateGetBool(vd, "video-wallpaper");
205     /* FIXME */
206     sys->use_overlay = false;//var_CreateGetBool(vd, "overlay"); /* FIXME */
207     var_Create(vd, "directx-device", VLC_VAR_STRING | VLC_VAR_DOINHERIT);
208
209     /* Initialisation */
210     if (CommonInit(vd))
211         goto error;
212
213     /* */
214     video_format_t fmt = vd->fmt;
215
216     if (DirectXOpen(vd, &fmt))
217         goto error;
218
219     /* */
220     vout_display_info_t info = vd->info;
221     info.is_slow = true;
222     info.has_double_click = true;
223     info.has_hide_mouse = true;
224     info.has_pictures_invalid = true;
225
226     /* Interaction TODO support starting with wallpaper mode */
227     vlc_mutex_init(&sys->lock);
228     sys->ch_wallpaper = sys->use_wallpaper;
229     sys->wallpaper_requested = sys->use_wallpaper;
230     sys->use_wallpaper = false;
231
232     vlc_value_t val;
233     val.psz_string = _("Wallpaper");
234     var_Change(vd, "video-wallpaper", VLC_VAR_SETTEXT, &val, NULL);
235     var_AddCallback(vd, "video-wallpaper", WallpaperCallback, NULL);
236
237     /* Setup vout_display now that everything is fine */
238     vd->fmt     = fmt;
239     vd->info    = info;
240
241     vd->pool    = Pool;
242     vd->prepare = NULL;
243     vd->display = Display;
244     vd->control = Control;
245     vd->manage  = Manage;
246     return VLC_SUCCESS;
247
248 error:
249     Close(VLC_OBJECT(vd));
250     return VLC_EGENERIC;
251 }
252
253 /** Terminate a vout display created by Open.
254  */
255 static void Close(vlc_object_t *object)
256 {
257     vout_display_t *vd = (vout_display_t *)object;
258     vout_display_sys_t *sys = vd->sys;
259
260     var_DelCallback(vd, "video-wallpaper", WallpaperCallback, NULL);
261     vlc_mutex_destroy(&sys->lock);
262
263     /* Make sure the wallpaper is restored */
264     WallpaperChange(vd, false);
265
266     DirectXClose(vd);
267
268     CommonClean(vd);
269
270     if (sys->hddraw_dll)
271         FreeLibrary(sys->hddraw_dll);
272     free(sys);
273 }
274
275 static picture_pool_t *Pool(vout_display_t *vd, unsigned count)
276 {
277     VLC_UNUSED(count);
278     return vd->sys->pool;
279 }
280 static void Display(vout_display_t *vd, picture_t *picture)
281 {
282     vout_display_sys_t *sys = vd->sys;
283
284     assert(sys->display);
285
286     /* Our surface can be lost so be sure to check this
287      * and restore it if need be */
288     if (IDirectDrawSurface2_IsLost(sys->display) == DDERR_SURFACELOST) {
289         if (IDirectDrawSurface2_Restore(sys->display) == DD_OK) {
290             if (sys->use_overlay)
291                 DirectXUpdateOverlay(vd, NULL);
292         }
293     }
294
295     /* */
296     DirectXUnlock(picture);
297
298     if (sys->use_overlay) {
299         /* Flip the overlay buffers if we are using back buffers */
300         if (picture->p_sys->surface != picture->p_sys->front_surface) {
301             HRESULT hr = IDirectDrawSurface2_Flip(picture->p_sys->front_surface,
302                                                   NULL, DDFLIP_WAIT);
303             if (hr != DD_OK)
304                 msg_Warn(vd, "could not flip overlay (error %li)", hr);
305         }
306     } else {
307         /* Blit video surface to display with the NOTEARING option */
308         DDBLTFX  ddbltfx;
309         ZeroMemory(&ddbltfx, sizeof(ddbltfx));
310         ddbltfx.dwSize = sizeof(ddbltfx);
311         ddbltfx.dwDDFX = DDBLTFX_NOTEARING;
312
313         HRESULT hr = IDirectDrawSurface2_Blt(sys->display,
314                                              &sys->rect_dest_clipped,
315                                              picture->p_sys->surface,
316                                              &sys->rect_src_clipped,
317                                              DDBLT_ASYNC, &ddbltfx);
318         if (hr != DD_OK)
319             msg_Warn(vd, "could not blit surface (error %li)", hr);
320     }
321     DirectXLock(picture);
322
323     if (sys->is_first_display) {
324         IDirectDraw_WaitForVerticalBlank(sys->ddobject,
325                                          DDWAITVB_BLOCKBEGIN, NULL);
326         if (sys->use_overlay) {
327             HBRUSH brush = CreateSolidBrush(sys->i_rgb_colorkey);
328             /* set the colorkey as the backgound brush for the video window */
329             SetClassLongPtr(sys->hvideownd, GCLP_HBRBACKGROUND, (LONG_PTR)brush);
330         }
331     }
332     CommonDisplay(vd);
333
334     picture_Release(picture);
335 }
336 static int Control(vout_display_t *vd, int query, va_list args)
337 {
338     vout_display_sys_t *sys = vd->sys;
339
340     switch (query) {
341     case VOUT_DISPLAY_RESET_PICTURES:
342         DirectXClose(vd);
343         /* Make sure the wallpaper is restored */
344         if (sys->use_wallpaper) {
345             vlc_mutex_lock(&sys->lock);
346             if (!sys->ch_wallpaper) {
347                 sys->ch_wallpaper = true;
348                 sys->wallpaper_requested = true;
349             }
350             vlc_mutex_unlock(&sys->lock);
351
352             WallpaperChange(vd, false);
353         }
354         return DirectXOpen(vd, &vd->fmt);
355     default:
356         return CommonControl(vd, query, args);
357     }
358 }
359 static void Manage(vout_display_t *vd)
360 {
361     vout_display_sys_t *sys = vd->sys;
362
363     CommonManage(vd);
364
365     if (sys->changes & DX_POSITION_CHANGE) {
366         /* Update overlay */
367         if (sys->use_overlay)
368             DirectXUpdateOverlay(vd, NULL);
369
370         /* Check if we are still on the same monitor */
371         if (sys->MonitorFromWindow &&
372             sys->hmonitor != sys->MonitorFromWindow(sys->hwnd, MONITOR_DEFAULTTONEAREST)) {
373             vout_display_SendEventPicturesInvalid(vd);
374         }
375         /* */
376         sys->changes &= ~DX_POSITION_CHANGE;
377     }
378
379     /* Wallpaper mode change */
380     vlc_mutex_lock(&sys->lock);
381     const bool ch_wallpaper = sys->ch_wallpaper;
382     const bool wallpaper_requested = sys->wallpaper_requested;
383     sys->ch_wallpaper = false;
384     vlc_mutex_unlock(&sys->lock);
385
386     if (ch_wallpaper)
387         WallpaperChange(vd, wallpaper_requested);
388 }
389
390 /* */
391 static int  DirectXOpenDDraw(vout_display_t *);
392 static void DirectXCloseDDraw(vout_display_t *);
393
394 static int  DirectXOpenDisplay(vout_display_t *vd);
395 static void DirectXCloseDisplay(vout_display_t *vd);
396
397 static int  DirectXCreatePool(vout_display_t *, bool *, video_format_t *);
398 static void DirectXDestroyPool(vout_display_t *);
399
400 static int DirectXOpen(vout_display_t *vd, video_format_t *fmt)
401 {
402     vout_display_sys_t *sys = vd->sys;
403
404     assert(!sys->ddobject);
405     assert(!sys->display);
406     assert(!sys->clipper);
407
408     /* Initialise DirectDraw */
409     if (DirectXOpenDDraw(vd)) {
410         msg_Err(vd, "cannot initialize DirectX DirectDraw");
411         return VLC_EGENERIC;
412     }
413
414     /* Create the directx display */
415     if (DirectXOpenDisplay(vd)) {
416         msg_Err(vd, "cannot initialize DirectX DirectDraw");
417         return VLC_EGENERIC;
418     }
419     UpdateRects(vd, NULL, NULL, true);
420
421     /* Create the picture pool */
422     if (DirectXCreatePool(vd, &sys->use_overlay, fmt)) {
423         msg_Err(vd, "cannot create any DirectX surface");
424         return VLC_EGENERIC;
425     }
426
427     /* */
428     if (sys->use_overlay)
429         DirectXUpdateOverlay(vd, NULL);
430     EventThreadUseOverlay(sys->event, sys->use_overlay);
431
432     /* Change the window title bar text */
433     const char *fallback;
434     if (sys->use_overlay)
435         fallback = VOUT_TITLE " (hardware YUV overlay DirectX output)";
436     else if (vlc_fourcc_IsYUV(fmt->i_chroma))
437         fallback = VOUT_TITLE " (hardware YUV DirectX output)";
438     else
439         fallback = VOUT_TITLE " (software RGB DirectX output)";
440     EventThreadUpdateTitle(sys->event, fallback);
441
442     return VLC_SUCCESS;
443 }
444 static void DirectXClose(vout_display_t *vd)
445 {
446     DirectXDestroyPool(vd);
447     DirectXCloseDisplay(vd);
448     DirectXCloseDDraw(vd);
449 }
450
451 /* */
452 static BOOL WINAPI DirectXOpenDDrawCallback(GUID *guid, LPTSTR desc,
453                                             LPTSTR drivername, VOID *context,
454                                             HMONITOR hmon)
455 {
456     vout_display_t *vd = context;
457     vout_display_sys_t *sys = vd->sys;
458
459     /* This callback function is called by DirectDraw once for each
460      * available DirectDraw device.
461      *
462      * Returning TRUE keeps enumerating.
463      */
464     if (!hmon)
465         return TRUE;
466
467     msg_Dbg(vd, "DirectXEnumCallback: %s, %s", desc, drivername);
468
469     char *device = var_GetString(vd, "directx-device");
470
471     /* Check for forced device */
472     if (device && *device && !strcmp(drivername, device)) {
473         MONITORINFO monitor_info;
474         monitor_info.cbSize = sizeof(MONITORINFO);
475
476         if (sys->GetMonitorInfo(hmon, &monitor_info)) {
477             RECT rect;
478
479             /* Move window to the right screen */
480             GetWindowRect(sys->hwnd, &rect);
481             if (!IntersectRect(&rect, &rect, &monitor_info.rcWork)) {
482                 rect.left = monitor_info.rcWork.left;
483                 rect.top = monitor_info.rcWork.top;
484                 msg_Dbg(vd, "DirectXEnumCallback: setting window "
485                             "position to %ld,%ld", rect.left, rect.top);
486                 SetWindowPos(sys->hwnd, NULL,
487                              rect.left, rect.top, 0, 0,
488                              SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE);
489             }
490         }
491         sys->hmonitor = hmon;
492     }
493     free(device);
494
495     if (hmon == sys->hmonitor) {
496         msg_Dbg(vd, "selecting %s, %s", desc, drivername);
497
498         free(sys->display_driver);
499         sys->display_driver = malloc(sizeof(*guid));
500         if (sys->display_driver)
501             *sys->display_driver = *guid;
502     }
503
504     return TRUE;
505 }
506 /**
507  * Probe the capabilities of the hardware
508  *
509  * It is nice to know which features are supported by the hardware so we can
510  * find ways to optimize our rendering.
511  */
512 static void DirectXGetDDrawCaps(vout_display_t *vd)
513 {
514     vout_display_sys_t *sys = vd->sys;
515
516     /* This is just an indication of whether or not we'll support overlay,
517      * but with this test we don't know if we support YUV overlay */
518     DDCAPS ddcaps;
519     ZeroMemory(&ddcaps, sizeof(ddcaps));
520     ddcaps.dwSize = sizeof(ddcaps);
521     HRESULT hr = IDirectDraw2_GetCaps(sys->ddobject, &ddcaps, NULL);
522     if (hr != DD_OK) {
523         msg_Warn(vd, "cannot get caps");
524         return;
525     }
526
527     /* Determine if the hardware supports overlay surfaces */
528     const bool has_overlay = ddcaps.dwCaps & DDCAPS_OVERLAY;
529     /* Determine if the hardware supports overlay surfaces */
530     const bool has_overlay_fourcc = ddcaps.dwCaps & DDCAPS_OVERLAYFOURCC;
531     /* Determine if the hardware supports overlay deinterlacing */
532     const bool can_deinterlace = ddcaps.dwCaps & DDCAPS2_CANFLIPODDEVEN;
533     /* Determine if the hardware supports colorkeying */
534     const bool has_color_key = ddcaps.dwCaps & DDCAPS_COLORKEY;
535     /* Determine if the hardware supports scaling of the overlay surface */
536     const bool can_stretch = ddcaps.dwCaps & DDCAPS_OVERLAYSTRETCH;
537     /* Determine if the hardware supports color conversion during a blit */
538     sys->can_blit_fourcc = ddcaps.dwCaps & DDCAPS_BLTFOURCC;
539     /* Determine overlay source boundary alignment */
540     const bool align_boundary_src  = ddcaps.dwCaps & DDCAPS_ALIGNBOUNDARYSRC;
541     /* Determine overlay destination boundary alignment */
542     const bool align_boundary_dest = ddcaps.dwCaps & DDCAPS_ALIGNBOUNDARYDEST;
543     /* Determine overlay destination size alignment */
544     const bool align_size_src  = ddcaps.dwCaps & DDCAPS_ALIGNSIZESRC;
545     /* Determine overlay destination size alignment */
546     const bool align_size_dest = ddcaps.dwCaps & DDCAPS_ALIGNSIZEDEST;
547
548     msg_Dbg(vd, "DirectDraw Capabilities: overlay=%i yuvoverlay=%i "
549                 "can_deinterlace_overlay=%i colorkey=%i stretch=%i "
550                 "bltfourcc=%i",
551                 has_overlay, has_overlay_fourcc, can_deinterlace,
552                 has_color_key, can_stretch, sys->can_blit_fourcc);
553
554     if (align_boundary_src || align_boundary_dest || align_size_src || align_size_dest) {
555         if (align_boundary_src)
556             vd->sys->i_align_src_boundary = ddcaps.dwAlignBoundarySrc;
557         if (align_boundary_dest)
558             vd->sys->i_align_dest_boundary = ddcaps.dwAlignBoundaryDest;
559         if (align_size_src)
560             vd->sys->i_align_src_size = ddcaps.dwAlignSizeSrc;
561         if (align_size_dest)
562             vd->sys->i_align_dest_size = ddcaps.dwAlignSizeDest;
563
564         msg_Dbg(vd,
565                 "align_boundary_src=%i,%i align_boundary_dest=%i,%i "
566                 "align_size_src=%i,%i align_size_dest=%i,%i",
567                 align_boundary_src,  vd->sys->i_align_src_boundary,
568                 align_boundary_dest, vd->sys->i_align_dest_boundary,
569                 align_size_src,  vd->sys->i_align_src_size,
570                 align_size_dest, vd->sys->i_align_dest_size);
571     }
572 }
573
574
575
576 /* */
577 static int DirectXOpenDDraw(vout_display_t *vd)
578 {
579     vout_display_sys_t *sys = vd->sys;
580     HRESULT hr;
581
582     /* */
583     HRESULT (WINAPI *OurDirectDrawCreate)(GUID *,LPDIRECTDRAW *,IUnknown *);
584     OurDirectDrawCreate =
585         (void *)GetProcAddress(sys->hddraw_dll, _T("DirectDrawCreate"));
586     if (!OurDirectDrawCreate) {
587         msg_Err(vd, "DirectXInitDDraw failed GetProcAddress");
588         return VLC_EGENERIC;
589     }
590
591     /* */
592     if (sys->MonitorFromWindow) {
593         HRESULT (WINAPI *OurDirectDrawEnumerateEx)(LPDDENUMCALLBACKEXA, LPVOID, DWORD);
594         OurDirectDrawEnumerateEx =
595           (void *)GetProcAddress(sys->hddraw_dll, _T("DirectDrawEnumerateExA"));
596
597         if (OurDirectDrawEnumerateEx) {
598             char *device = var_GetString(vd, "directx-device");
599             if (device) {
600                 msg_Dbg(vd, "directx-device: %s", device);
601                 free(device);
602             }
603
604             sys->hmonitor = sys->MonitorFromWindow(sys->hwnd, MONITOR_DEFAULTTONEAREST);
605
606             /* Enumerate displays */
607             OurDirectDrawEnumerateEx(DirectXOpenDDrawCallback,
608                                      vd, DDENUM_ATTACHEDSECONDARYDEVICES);
609         }
610     }
611
612     /* Initialize DirectDraw now */
613     LPDIRECTDRAW ddobject;
614     hr = OurDirectDrawCreate(sys->display_driver, &ddobject, NULL);
615     if (hr != DD_OK) {
616         msg_Err(vd, "DirectXInitDDraw cannot initialize DDraw");
617         return VLC_EGENERIC;
618     }
619
620     /* Get the IDirectDraw2 interface */
621     hr = IDirectDraw_QueryInterface(ddobject, &IID_IDirectDraw2,
622                                     &sys->ddobject);
623     /* Release the unused interface */
624     IDirectDraw_Release(ddobject);
625
626     if (hr != DD_OK) {
627         msg_Err(vd, "cannot get IDirectDraw2 interface");
628         sys->ddobject = NULL;
629         return VLC_EGENERIC;
630     }
631
632     /* Set DirectDraw Cooperative level, ie what control we want over Windows
633      * display */
634     hr = IDirectDraw2_SetCooperativeLevel(sys->ddobject, NULL, DDSCL_NORMAL);
635     if (hr != DD_OK) {
636         msg_Err(vd, "cannot set direct draw cooperative level");
637         return VLC_EGENERIC;
638     }
639
640     /* Get the size of the current display device */
641     if (sys->hmonitor && sys->GetMonitorInfo) {
642         MONITORINFO monitor_info;
643         monitor_info.cbSize = sizeof(MONITORINFO);
644         sys->GetMonitorInfo(vd->sys->hmonitor, &monitor_info);
645         sys->rect_display = monitor_info.rcMonitor;
646     } else {
647         sys->rect_display.left   = 0;
648         sys->rect_display.top    = 0;
649         sys->rect_display.right  = GetSystemMetrics(SM_CXSCREEN);
650         sys->rect_display.bottom = GetSystemMetrics(SM_CYSCREEN);
651     }
652
653     msg_Dbg(vd, "screen dimensions (%lix%li,%lix%li)",
654             sys->rect_display.left,
655             sys->rect_display.top,
656             sys->rect_display.right,
657             sys->rect_display.bottom);
658
659     /* Probe the capabilities of the hardware */
660     DirectXGetDDrawCaps(vd);
661
662     return VLC_SUCCESS;
663 }
664
665 static void DirectXCloseDDraw(vout_display_t *vd)
666 {
667     vout_display_sys_t *sys = vd->sys;
668     if (sys->ddobject)
669         IDirectDraw2_Release(sys->ddobject);
670
671     sys->ddobject = NULL;
672
673     free(sys->display_driver);
674     sys->display_driver = NULL;
675
676     sys->hmonitor = NULL;
677 }
678
679 /**
680  * Create a clipper that will be used when blitting the RGB surface to the main display.
681  *
682  * This clipper prevents us to modify by mistake anything on the screen
683  * which doesn't belong to our window. For example when a part of our video
684  * window is hidden by another window.
685  */
686 static void DirectXCreateClipper(vout_display_t *vd)
687 {
688     vout_display_sys_t *sys = vd->sys;
689     HRESULT hr;
690
691     /* Create the clipper */
692     hr = IDirectDraw2_CreateClipper(sys->ddobject, 0, &sys->clipper, NULL);
693     if (hr != DD_OK) {
694         msg_Warn(vd, "cannot create clipper (error %li)", hr);
695         goto error;
696     }
697
698     /* Associate the clipper to the window */
699     hr = IDirectDrawClipper_SetHWnd(sys->clipper, 0, sys->hvideownd);
700     if (hr != DD_OK) {
701         msg_Warn(vd, "cannot attach clipper to window (error %li)", hr);
702         goto error;
703     }
704
705     /* associate the clipper with the surface */
706     hr = IDirectDrawSurface_SetClipper(sys->display, sys->clipper);
707     if (hr != DD_OK)
708     {
709         msg_Warn(vd, "cannot attach clipper to surface (error %li)", hr);
710         goto error;
711     }
712
713     return;
714
715 error:
716     if (sys->clipper)
717         IDirectDrawClipper_Release(sys->clipper);
718     sys->clipper = NULL;
719 }
720
721 /**
722  * It finds out the 32bits RGB pixel value of the colorkey.
723  */
724 static uint32_t DirectXFindColorkey(vout_display_t *vd, uint32_t *color)
725 {
726     vout_display_sys_t *sys = vd->sys;
727     HRESULT hr;
728
729     /* */
730     DDSURFACEDESC ddsd;
731     ddsd.dwSize = sizeof(ddsd);
732     hr = IDirectDrawSurface2_Lock(sys->display, NULL, &ddsd, DDLOCK_WAIT, NULL);
733     if (hr != DD_OK)
734         return 0;
735
736     uint32_t backup = *(uint32_t *)ddsd.lpSurface;
737
738     switch (ddsd.ddpfPixelFormat.dwRGBBitCount) {
739     case 4:
740         *(uint8_t *)ddsd.lpSurface = *color | (*color << 4);
741         break;
742     case 8:
743         *(uint8_t *)ddsd.lpSurface = *color;
744         break;
745     case 15:
746     case 16:
747         *(uint16_t *)ddsd.lpSurface = *color;
748         break;
749     case 24:
750         /* Seems to be problematic so we'll just put black as the colorkey */
751         *color = 0;
752     default:
753         *(uint32_t *)ddsd.lpSurface = *color;
754         break;
755     }
756     IDirectDrawSurface2_Unlock(sys->display, NULL);
757
758     /* */
759     HDC hdc;
760     COLORREF rgb;
761     if (IDirectDrawSurface2_GetDC(sys->display, &hdc) == DD_OK) {
762         rgb = GetPixel(hdc, 0, 0);
763         IDirectDrawSurface2_ReleaseDC(sys->display, hdc);
764     } else {
765         rgb = 0;
766     }
767
768     /* Restore the pixel value */
769     ddsd.dwSize = sizeof(ddsd);
770     if (IDirectDrawSurface2_Lock(sys->display, NULL, &ddsd, DDLOCK_WAIT, NULL) == DD_OK) {
771         *(uint32_t *)ddsd.lpSurface = backup;
772         IDirectDrawSurface2_Unlock(sys->display, NULL);
773     }
774
775     return rgb;
776 }
777
778 /**
779  * Create and initialize display according to preferences specified in the vout
780  * thread fields.
781  */
782 static int DirectXOpenDisplay(vout_display_t *vd)
783 {
784     vout_display_sys_t *sys = vd->sys;
785     HRESULT hr;
786
787     /* Now get the primary surface. This surface is what you actually see
788      * on your screen */
789     DDSURFACEDESC ddsd;
790     ZeroMemory(&ddsd, sizeof(ddsd));
791     ddsd.dwSize = sizeof(ddsd);
792     ddsd.dwFlags = DDSD_CAPS;
793     ddsd.ddsCaps.dwCaps = DDSCAPS_PRIMARYSURFACE;
794
795     LPDIRECTDRAWSURFACE display;
796     hr = IDirectDraw2_CreateSurface(sys->ddobject, &ddsd, &display, NULL);
797     if (hr != DD_OK) {
798         msg_Err(vd, "cannot get primary surface (error %li)", hr);
799         return VLC_EGENERIC;
800     }
801
802     hr = IDirectDrawSurface_QueryInterface(display, &IID_IDirectDrawSurface2,
803                                            &sys->display);
804     /* Release the old interface */
805     IDirectDrawSurface_Release(display);
806
807     if (hr != DD_OK) {
808         msg_Err(vd, "cannot query IDirectDrawSurface2 interface (error %li)", hr);
809         sys->display = NULL;
810         return VLC_EGENERIC;
811     }
812
813     /* The clipper will be used only in non-overlay mode */
814     DirectXCreateClipper(vd);
815
816     /* Make sure the colorkey will be painted */
817     sys->i_colorkey = 1;
818     sys->i_rgb_colorkey = DirectXFindColorkey(vd, &sys->i_colorkey);
819
820     return VLC_SUCCESS;
821 }
822 static void DirectXCloseDisplay(vout_display_t *vd)
823 {
824     vout_display_sys_t *sys = vd->sys;
825
826     if (sys->clipper != NULL)
827         IDirectDrawClipper_Release(sys->clipper);
828
829     if (sys->display != NULL)
830         IDirectDrawSurface2_Release(sys->display);
831
832     sys->clipper = NULL;
833     sys->display = NULL;
834 }
835
836 /**
837  * Create an YUV overlay or RGB surface for the video.
838  *
839  * The best method of display is with an YUV overlay because the YUV->RGB
840  * conversion is done in hardware.
841  * You can also create a plain RGB surface.
842  * (Maybe we could also try an RGB overlay surface, which could have hardware
843  * scaling and which would also be faster in window mode because you don't
844  * need to do any blitting to the main display...)
845  */
846 static int DirectXCreateSurface(vout_display_t *vd,
847                                 LPDIRECTDRAWSURFACE2 *surface,
848                                 const video_format_t *fmt,
849                                 DWORD fourcc,
850                                 bool use_overlay,
851                                 bool use_sysmem,
852                                 int backbuffer_count)
853 {
854     vout_display_sys_t *sys = vd->sys;
855
856     DDSURFACEDESC ddsd;
857
858     ZeroMemory(&ddsd, sizeof(ddsd));
859     ddsd.dwSize   = sizeof(ddsd);
860     ddsd.ddpfPixelFormat.dwSize = sizeof(ddsd.ddpfPixelFormat);
861     ddsd.dwFlags  = DDSD_HEIGHT | DDSD_WIDTH;
862     ddsd.dwWidth  = fmt->i_width;
863     ddsd.dwHeight = fmt->i_height;
864     if (fourcc) {
865         ddsd.dwFlags |= DDSD_PIXELFORMAT;
866         ddsd.ddpfPixelFormat.dwFlags = DDPF_FOURCC;
867         ddsd.ddpfPixelFormat.dwFourCC = fourcc;
868     }
869     if (use_overlay) {
870         ddsd.dwFlags |= DDSD_CAPS;
871         ddsd.ddsCaps.dwCaps = DDSCAPS_OVERLAY | DDSCAPS_VIDEOMEMORY;
872         if (backbuffer_count > 0)
873             ddsd.ddsCaps.dwCaps |= DDSCAPS_COMPLEX | DDSCAPS_FLIP;
874
875         if (backbuffer_count > 0) {
876             ddsd.dwFlags |= DDSD_BACKBUFFERCOUNT;
877             ddsd.dwBackBufferCount = backbuffer_count;
878         }
879     } else {
880         ddsd.dwFlags |= DDSD_CAPS;
881         ddsd.ddsCaps.dwCaps = DDSCAPS_OFFSCREENPLAIN;
882         if (use_sysmem)
883             ddsd.ddsCaps.dwCaps |= DDSCAPS_SYSTEMMEMORY;
884         else
885             ddsd.ddsCaps.dwCaps |= DDSCAPS_VIDEOMEMORY;
886     }
887
888     /* Create the video surface */
889     LPDIRECTDRAWSURFACE surface_v1;
890     if (IDirectDraw2_CreateSurface(sys->ddobject, &ddsd, &surface_v1, NULL) != DD_OK)
891         return VLC_EGENERIC;
892
893     /* Now that the surface is created, try to get a newer DirectX interface */
894     HRESULT hr = IDirectDrawSurface_QueryInterface(surface_v1,
895                                                    &IID_IDirectDrawSurface2,
896                                                    (LPVOID *)surface);
897     IDirectDrawSurface_Release(surface_v1);
898     if (hr != DD_OK) {
899         msg_Err(vd, "cannot query IDirectDrawSurface2 interface (error %li)", hr);
900         return VLC_EGENERIC;
901     }
902
903     if (use_overlay) {
904         /* Check the overlay is useable as some graphics cards allow creating
905          * several overlays but only one can be used at one time. */
906         if (DirectXUpdateOverlay(vd, *surface)) {
907             IDirectDrawSurface2_Release(*surface);
908             msg_Err(vd, "overlay unuseable (might already be in use)");
909             return VLC_EGENERIC;
910         }
911     }
912
913     return VLC_SUCCESS;
914 }
915
916 static void DirectXDestroySurface(LPDIRECTDRAWSURFACE2 surface)
917 {
918     IDirectDrawSurface2_Release(surface);
919 }
920 /**
921  * This function locks a surface and get the surface descriptor.
922  */
923 static int DirectXLockSurface(LPDIRECTDRAWSURFACE2 front_surface,
924                               LPDIRECTDRAWSURFACE2 surface,
925                               DDSURFACEDESC *ddsd)
926 {
927     HRESULT hr;
928
929     DDSURFACEDESC ddsd_dummy;
930     if (!ddsd)
931         ddsd = &ddsd_dummy;
932
933     ZeroMemory(ddsd, sizeof(*ddsd));
934     ddsd->dwSize = sizeof(*ddsd);
935     hr = IDirectDrawSurface2_Lock(surface, NULL, ddsd, DDLOCK_NOSYSLOCK | DDLOCK_WAIT, NULL);
936     if (hr != DD_OK) {
937         if (hr == DDERR_INVALIDPARAMS) {
938             /* DirectX 3 doesn't support the DDLOCK_NOSYSLOCK flag, resulting
939              * in an invalid params error */
940             hr = IDirectDrawSurface2_Lock(surface, NULL, ddsd, DDLOCK_WAIT, NULL);
941         }
942         if (hr == DDERR_SURFACELOST) {
943             /* Your surface can be lost so be sure
944              * to check this and restore it if needed */
945
946             /* When using overlays with back-buffers, we need to restore
947              * the front buffer so the back-buffers get restored as well. */
948             if (front_surface != surface)
949                 IDirectDrawSurface2_Restore(front_surface);
950             else
951                 IDirectDrawSurface2_Restore(surface);
952
953             hr = IDirectDrawSurface2_Lock(surface, NULL, ddsd, DDLOCK_WAIT, NULL);
954         }
955         if (hr != DD_OK)
956             return VLC_EGENERIC;
957     }
958     return VLC_SUCCESS;
959 }
960 static void DirectXUnlockSurface(LPDIRECTDRAWSURFACE2 front_surface,
961                                  LPDIRECTDRAWSURFACE2 surface)
962 {
963     IDirectDrawSurface2_Unlock(surface, NULL);
964 }
965 static int DirectXCheckLockingSurface(LPDIRECTDRAWSURFACE2 front_surface,
966                                       LPDIRECTDRAWSURFACE2 surface)
967 {
968     if (DirectXLockSurface(front_surface, surface, NULL))
969         return VLC_EGENERIC;
970
971     DirectXUnlockSurface(front_surface, surface);
972     return VLC_SUCCESS;
973 }
974
975
976
977 typedef struct {
978     vlc_fourcc_t codec;
979     DWORD        fourcc;
980 } dx_format_t;
981
982 static DWORD DirectXGetFourcc(vlc_fourcc_t codec)
983 {
984     static const dx_format_t dx_formats[] = {
985         { VLC_CODEC_YUYV, MAKEFOURCC('Y','U','Y','2') },
986         { VLC_CODEC_UYVY, MAKEFOURCC('U','Y','V','Y') },
987         { VLC_CODEC_YVYU, MAKEFOURCC('Y','V','Y','U') },
988         { VLC_CODEC_YV12, MAKEFOURCC('Y','V','1','2') },
989         { VLC_CODEC_I420, MAKEFOURCC('Y','V','1','2') },
990         { VLC_CODEC_J420, MAKEFOURCC('Y','V','1','2') },
991         { 0, 0 }
992     };
993
994     for (unsigned i = 0; dx_formats[i].codec != 0; i++) {
995         if (dx_formats[i].codec == codec)
996             return dx_formats[i].fourcc;
997     }
998     return 0;
999 }
1000
1001 static int DirectXCreatePictureResourceYuvOverlay(vout_display_t *vd,
1002                                                   const video_format_t *fmt,
1003                                                   DWORD fourcc)
1004 {
1005     vout_display_sys_t *sys = vd->sys;
1006
1007     bool allow_3buf    = var_InheritBool(vd, "directx-3buffering");
1008
1009     /* The overlay surface that we create won't be used to decode directly
1010      * into it because accessing video memory directly is way to slow (remember
1011      * that pictures are decoded macroblock per macroblock). Instead the video
1012      * will be decoded in picture buffers in system memory which will then be
1013      * memcpy() to the overlay surface. */
1014     LPDIRECTDRAWSURFACE2 front_surface;
1015     int ret = VLC_EGENERIC;
1016     if (allow_3buf) {
1017         /* Triple buffering rocks! it doesn't have any processing overhead
1018          * (you don't have to wait for the vsync) and provides for a very nice
1019          * video quality (no tearing). */
1020         ret = DirectXCreateSurface(vd, &front_surface, fmt, fourcc, true, false, 2);
1021     }
1022     if (ret)
1023         ret = DirectXCreateSurface(vd, &front_surface, fmt, fourcc, true, false, 0);
1024     if (ret)
1025         return VLC_EGENERIC;
1026     msg_Dbg(vd, "YUV overlay surface created successfully");
1027
1028     /* Get the back buffer */
1029     LPDIRECTDRAWSURFACE2 surface;
1030     DDSCAPS dds_caps;
1031     ZeroMemory(&dds_caps, sizeof(dds_caps));
1032     dds_caps.dwCaps = DDSCAPS_BACKBUFFER;
1033     if (IDirectDrawSurface2_GetAttachedSurface(front_surface, &dds_caps, &surface) != DD_OK) {
1034         msg_Warn(vd, "Failed to get surface back buffer");
1035         /* front buffer is the same as back buffer */
1036         surface = front_surface;
1037     }
1038
1039     if (DirectXCheckLockingSurface(front_surface, surface)) {
1040         DirectXDestroySurface(front_surface);
1041         return VLC_EGENERIC;
1042     }
1043
1044     /* */
1045     picture_resource_t *rsc = &sys->resource;
1046     rsc->p_sys->front_surface = front_surface;
1047     rsc->p_sys->surface       = surface;
1048     return VLC_SUCCESS;
1049 }
1050 static int DirectXCreatePictureResourceYuv(vout_display_t *vd,
1051                                            const video_format_t *fmt,
1052                                            DWORD fourcc)
1053 {
1054     vout_display_sys_t *sys = vd->sys;
1055
1056     bool allow_sysmem  = var_InheritBool(vd, "directx-use-sysmem");
1057
1058     /* As we can't have an overlay, we'll try to create a plain offscreen
1059      * surface. This surface will reside in video memory because there's a
1060      * better chance then that we'll be able to use some kind of hardware
1061      * acceleration like rescaling, blitting or YUV->RGB conversions.
1062      * We then only need to blit this surface onto the main display when we
1063      * want to display it */
1064
1065     /* Check if the chroma is supported first. This is required
1066      * because a few buggy drivers don't mind creating the surface
1067      * even if they don't know about the chroma. */
1068     DWORD count;
1069     if (IDirectDraw2_GetFourCCCodes(sys->ddobject, &count, NULL) != DD_OK)
1070         return VLC_EGENERIC;
1071
1072     DWORD *list = calloc(count, sizeof(*list));
1073     if (!list)
1074         return VLC_ENOMEM;
1075     if (IDirectDraw2_GetFourCCCodes(sys->ddobject, &count, list) != DD_OK) {
1076         free(list);
1077         return VLC_EGENERIC;
1078     }
1079     unsigned index;
1080     for (index = 0; index < count; index++) {
1081         if (list[index] == fourcc)
1082             break;
1083     }
1084     free(list);
1085     if (index >= count)
1086         return VLC_EGENERIC;
1087
1088     /* */
1089     LPDIRECTDRAWSURFACE2 surface;
1090     if (DirectXCreateSurface(vd, &surface, fmt, fourcc, false, allow_sysmem, 0))
1091         return VLC_EGENERIC;
1092     msg_Dbg(vd, "YUV plain surface created successfully");
1093
1094     if (DirectXCheckLockingSurface(surface, surface)) {
1095         DirectXDestroySurface(surface);
1096         return VLC_EGENERIC;
1097     }
1098
1099     /* */
1100     picture_resource_t *rsc = &sys->resource;
1101     rsc->p_sys->front_surface = surface;
1102     rsc->p_sys->surface       = surface;
1103     return VLC_SUCCESS;
1104 }
1105 static int DirectXCreatePictureResourceRgb(vout_display_t *vd,
1106                                            video_format_t *fmt)
1107 {
1108     vout_display_sys_t *sys = vd->sys;
1109     bool allow_sysmem  = var_InheritBool(vd, "directx-use-sysmem");
1110
1111     /* Our last choice is to use a plain RGB surface */
1112     DDPIXELFORMAT ddpfPixelFormat;
1113     ZeroMemory(&ddpfPixelFormat, sizeof(ddpfPixelFormat));
1114     ddpfPixelFormat.dwSize = sizeof(ddpfPixelFormat);
1115
1116     IDirectDrawSurface2_GetPixelFormat(sys->display, &ddpfPixelFormat);
1117     if ((ddpfPixelFormat.dwFlags & DDPF_RGB) == 0)
1118         return VLC_EGENERIC;
1119
1120     switch (ddpfPixelFormat.dwRGBBitCount) {
1121     case 8:
1122         fmt->i_chroma = VLC_CODEC_RGB8;
1123         break;
1124     case 15:
1125         fmt->i_chroma = VLC_CODEC_RGB15;
1126         break;
1127     case 16:
1128         fmt->i_chroma = VLC_CODEC_RGB16;
1129         break;
1130     case 24:
1131         fmt->i_chroma = VLC_CODEC_RGB24;
1132         break;
1133     case 32:
1134         fmt->i_chroma = VLC_CODEC_RGB32;
1135         break;
1136     default:
1137         msg_Err(vd, "unknown screen depth");
1138         return VLC_EGENERIC;
1139     }
1140     fmt->i_rmask = ddpfPixelFormat.dwRBitMask;
1141     fmt->i_gmask = ddpfPixelFormat.dwGBitMask;
1142     fmt->i_bmask = ddpfPixelFormat.dwBBitMask;
1143
1144     /* */
1145     LPDIRECTDRAWSURFACE2 surface;
1146     int ret = DirectXCreateSurface(vd, &surface, fmt, 0, false, allow_sysmem, 0);
1147     if (ret && !allow_sysmem)
1148         ret = DirectXCreateSurface(vd, &surface, fmt, 0, false, true, 0);
1149     if (ret)
1150         return VLC_EGENERIC;
1151     msg_Dbg(vd, "RGB plain surface created successfully");
1152
1153     if (DirectXCheckLockingSurface(surface, surface)) {
1154         DirectXDestroySurface(surface);
1155         return VLC_EGENERIC;
1156     }
1157
1158     /* */
1159     picture_resource_t *rsc = &sys->resource;
1160     rsc->p_sys->front_surface = surface;
1161     rsc->p_sys->surface       = surface;
1162     return VLC_SUCCESS;
1163 }
1164
1165 static int DirectXCreatePictureResource(vout_display_t *vd,
1166                                         bool *use_overlay,
1167                                         video_format_t *fmt)
1168 {
1169     vout_display_sys_t *sys = vd->sys;
1170
1171     /* */
1172     picture_resource_t *rsc = &sys->resource;
1173     rsc->p_sys = calloc(1, sizeof(*rsc->p_sys));
1174     if (!rsc->p_sys)
1175         return VLC_ENOMEM;
1176
1177     /* */
1178     bool allow_hw_yuv  = sys->can_blit_fourcc &&
1179                          vlc_fourcc_IsYUV(fmt->i_chroma) &&
1180                          var_InheritBool(vd, "directx-hw-yuv");
1181     bool allow_overlay = var_InheritBool(vd, "overlay");
1182
1183     /* Try to use an yuv surface */
1184     if (allow_hw_yuv) {
1185         const vlc_fourcc_t *list = vlc_fourcc_GetYUVFallback(fmt->i_chroma);
1186         /*  Try with overlay first */
1187         for (unsigned pass = allow_overlay ? 0 : 1; pass < 2; pass++) {
1188             for (unsigned i = 0; list[i] != 0; i++) {
1189                 const DWORD fourcc = DirectXGetFourcc(list[i]);
1190                 if (!fourcc)
1191                     continue;
1192
1193                 if (pass == 0) {
1194                     if (DirectXCreatePictureResourceYuvOverlay(vd, fmt, fourcc))
1195                         continue;
1196                 } else {
1197                     if (DirectXCreatePictureResourceYuv(vd, fmt, fourcc))
1198                         continue;
1199                 }
1200                 /* */
1201                 *use_overlay = pass == 0;
1202                 fmt->i_chroma = list[i];
1203                 return VLC_SUCCESS;
1204             }
1205         }
1206     }
1207
1208     /* Try plain RGB */
1209     return DirectXCreatePictureResourceRgb(vd, fmt);
1210 }
1211 static void DirectXDestroyPictureResource(vout_display_t *vd)
1212 {
1213     vout_display_sys_t *sys = vd->sys;
1214
1215     DirectXDestroySurface(sys->resource.p_sys->front_surface);
1216 }
1217
1218 static int DirectXLock(picture_t *picture)
1219 {
1220     DDSURFACEDESC ddsd;
1221     if (DirectXLockSurface(picture->p_sys->front_surface,
1222                            picture->p_sys->surface, &ddsd))
1223         return VLC_EGENERIC;
1224
1225     /* fill in buffer info in first plane */
1226     picture->p->p_pixels = ddsd.lpSurface;
1227     picture->p->i_pitch  = ddsd.lPitch;
1228     picture->p->i_lines  = picture->format.i_height;
1229
1230     /*  Fill chroma planes for planar YUV */
1231     if (picture->format.i_chroma == VLC_CODEC_I420 ||
1232         picture->format.i_chroma == VLC_CODEC_J420 ||
1233         picture->format.i_chroma == VLC_CODEC_YV12) {
1234
1235         for (int n = 1; n < picture->i_planes; n++) {
1236             const plane_t *o = &picture->p[n-1];
1237             plane_t *p = &picture->p[n];
1238
1239             p->p_pixels = o->p_pixels + o->i_lines * o->i_pitch;
1240             p->i_pitch  = ddsd.lPitch / 2;
1241             p->i_lines  = picture->format.i_height / 2;
1242         }
1243         /* The dx buffer is always allocated as YV12 */
1244         if (vlc_fourcc_AreUVPlanesSwapped(picture->format.i_chroma, VLC_CODEC_YV12)) {
1245             uint8_t *p_tmp = picture->p[1].p_pixels;
1246             picture->p[1].p_pixels = picture->p[2].p_pixels;
1247             picture->p[2].p_pixels = p_tmp;
1248         }
1249     }
1250     return VLC_SUCCESS;
1251 }
1252 static void DirectXUnlock(picture_t *picture)
1253 {
1254     DirectXUnlockSurface(picture->p_sys->front_surface,
1255                          picture->p_sys->surface);
1256 }
1257
1258 static int DirectXCreatePool(vout_display_t *vd,
1259                              bool *use_overlay, video_format_t *fmt)
1260 {
1261     vout_display_sys_t *sys = vd->sys;
1262
1263     /* */
1264     *fmt = vd->source;
1265
1266     if (DirectXCreatePictureResource(vd, use_overlay, fmt))
1267         return VLC_EGENERIC;
1268
1269     /* Create the associated picture */
1270     picture_resource_t *rsc = &sys->resource;
1271     for (int i = 0; i < PICTURE_PLANE_MAX; i++) {
1272         rsc->p[i].p_pixels = NULL;
1273         rsc->p[i].i_pitch  = 0;
1274         rsc->p[i].i_lines  = 0;
1275     }
1276     picture_t *picture = picture_NewFromResource(fmt, rsc);
1277     if (!picture) {
1278         DirectXDestroyPictureResource(vd);
1279         free(rsc->p_sys);
1280         return VLC_ENOMEM;
1281     }
1282
1283     /* Wrap it into a picture pool */
1284     picture_pool_configuration_t cfg;
1285     memset(&cfg, 0, sizeof(cfg));
1286     cfg.picture_count = 1;
1287     cfg.picture       = &picture;
1288     cfg.lock          = DirectXLock;
1289     cfg.unlock        = DirectXUnlock;
1290
1291     sys->pool = picture_pool_NewExtended(&cfg);
1292     if (!sys->pool) {
1293         picture_Release(picture);
1294         DirectXDestroyPictureResource(vd);
1295         return VLC_ENOMEM;
1296     }
1297     return VLC_SUCCESS;
1298 }
1299 static void DirectXDestroyPool(vout_display_t *vd)
1300 {
1301     vout_display_sys_t *sys = vd->sys;
1302
1303     if (sys->pool) {
1304         DirectXDestroyPictureResource(vd);
1305         picture_pool_Delete(sys->pool);
1306     }
1307     sys->pool = NULL;
1308 }
1309
1310 /**
1311  * Move or resize overlay surface on video display.
1312  *
1313  * This function is used to move or resize an overlay surface on the screen.
1314  * Ususally the overlay is moved by the user and thus, by a move or resize
1315  * event.
1316  */
1317 static int DirectXUpdateOverlay(vout_display_t *vd, LPDIRECTDRAWSURFACE2 surface)
1318 {
1319     vout_display_sys_t *sys = vd->sys;
1320
1321     RECT src = sys->rect_src_clipped;
1322     RECT dst = sys->rect_dest_clipped;
1323
1324     if (sys->use_wallpaper) {
1325         src.left   = vd->source.i_x_offset;
1326         src.top    = vd->source.i_y_offset;
1327         src.right  = vd->source.i_x_offset + vd->source.i_visible_width;
1328         src.bottom = vd->source.i_y_offset + vd->source.i_visible_height;
1329         AlignRect(&src, sys->i_align_src_boundary, sys->i_align_src_size);
1330
1331         vout_display_cfg_t cfg = *vd->cfg;
1332         cfg.display.width  = sys->rect_display.right;
1333         cfg.display.height = sys->rect_display.bottom;
1334
1335         vout_display_place_t place;
1336         vout_display_PlacePicture(&place, &vd->source, &cfg, true);
1337
1338         dst.left   = sys->rect_display.left + place.x;
1339         dst.top    = sys->rect_display.top  + place.y;
1340         dst.right  = dst.left + place.width;
1341         dst.bottom = dst.top  + place.height;
1342         AlignRect(&dst, sys->i_align_dest_boundary, sys->i_align_dest_size);
1343     }
1344
1345     if (!surface) {
1346         if (!sys->pool)
1347             return VLC_EGENERIC;
1348         surface = sys->resource.p_sys->front_surface;
1349     }
1350
1351     /* The new window dimensions should already have been computed by the
1352      * caller of this function */
1353
1354     /* Position and show the overlay */
1355     DDOVERLAYFX ddofx;
1356     ZeroMemory(&ddofx, sizeof(ddofx));
1357     ddofx.dwSize = sizeof(ddofx);
1358     ddofx.dckDestColorkey.dwColorSpaceLowValue = sys->i_colorkey;
1359     ddofx.dckDestColorkey.dwColorSpaceHighValue = sys->i_colorkey;
1360
1361     HRESULT hr = IDirectDrawSurface2_UpdateOverlay(surface,
1362                                                    &src, sys->display, &dst,
1363                                                    DDOVER_SHOW | DDOVER_KEYDESTOVERRIDE, &ddofx);
1364     if (hr != DD_OK) {
1365         msg_Warn(vd, "DirectDrawUpdateOverlay cannot move/resize overlay");
1366         return VLC_EGENERIC;
1367     }
1368     return VLC_SUCCESS;
1369 }
1370
1371 /* */
1372 static void WallpaperChange(vout_display_t *vd, bool use_wallpaper)
1373 {
1374     vout_display_sys_t *sys = vd->sys;
1375
1376     if (!sys->use_wallpaper == !use_wallpaper)
1377         return;
1378
1379     HWND hwnd = FindWindow(_T("Progman"), NULL);
1380     if (hwnd)
1381         hwnd = FindWindowEx(hwnd, NULL, _T("SHELLDLL_DefView"), NULL);
1382     if (hwnd)
1383         hwnd = FindWindowEx(hwnd, NULL, _T("SysListView32"), NULL);
1384     if (!hwnd) {
1385         msg_Warn(vd, "couldn't find \"SysListView32\" window, "
1386                      "wallpaper mode not supported");
1387         return;
1388     }
1389
1390     msg_Dbg(vd, "wallpaper mode %s", use_wallpaper ? "enabled" : "disabled");
1391     sys->use_wallpaper = use_wallpaper;
1392
1393     if (sys->use_wallpaper) {
1394         sys->color_bkg    = ListView_GetBkColor(hwnd);
1395         sys->color_bkgtxt = ListView_GetTextBkColor(hwnd);
1396
1397         ListView_SetBkColor(hwnd,     sys->i_rgb_colorkey);
1398         ListView_SetTextBkColor(hwnd, sys->i_rgb_colorkey);
1399     } else {
1400         ListView_SetBkColor(hwnd,     sys->color_bkg);
1401         ListView_SetTextBkColor(hwnd, sys->color_bkgtxt);
1402     }
1403
1404     /* Update desktop */
1405     InvalidateRect(hwnd, NULL, TRUE);
1406     UpdateWindow(hwnd);
1407
1408     if (sys->use_overlay)
1409       DirectXUpdateOverlay(vd, NULL);
1410 }
1411
1412 /* */
1413 static int WallpaperCallback(vlc_object_t *object, char const *cmd,
1414                              vlc_value_t oldval, vlc_value_t newval, void *data)
1415 {
1416     vout_display_t *vd = (vout_display_t *)object;
1417     vout_display_sys_t *sys = vd->sys;
1418     VLC_UNUSED(cmd); VLC_UNUSED(oldval); VLC_UNUSED(data);
1419
1420     vlc_mutex_lock(&sys->lock);
1421     const bool ch_wallpaper = !sys->wallpaper_requested != !newval.b_bool;
1422     sys->ch_wallpaper |= ch_wallpaper;
1423     sys->wallpaper_requested = newval.b_bool;
1424     vlc_mutex_unlock(&sys->lock);
1425
1426     /* FIXME we should have a way to export variable to be saved */
1427     if (ch_wallpaper) {
1428         playlist_t *p_playlist = pl_Get(vd);
1429         /* Modify playlist as well because the vout might have to be
1430          * restarted */
1431         var_Create(p_playlist, "video-wallpaper", VLC_VAR_BOOL);
1432         var_SetBool(p_playlist, "video-wallpaper", newval.b_bool);
1433     }
1434     return VLC_SUCCESS;
1435 }
1436
1437 /*****************************************************************************
1438  * config variable callback
1439  *****************************************************************************/
1440 static BOOL WINAPI DirectXEnumCallback2(GUID *guid, LPTSTR desc,
1441                                         LPTSTR drivername, VOID *context,
1442                                         HMONITOR hmon)
1443 {
1444     VLC_UNUSED(guid); VLC_UNUSED(desc); VLC_UNUSED(hmon);
1445
1446     module_config_t *item = context;
1447
1448     item->ppsz_list = xrealloc(item->ppsz_list,
1449                                (item->i_list+2) * sizeof(char *));
1450     item->ppsz_list_text = xrealloc(item->ppsz_list_text,
1451                                     (item->i_list+2) * sizeof(char *));
1452
1453     item->ppsz_list[item->i_list] = strdup(drivername);
1454     item->ppsz_list_text[item->i_list] = NULL;
1455     item->i_list++;
1456     item->ppsz_list[item->i_list] = NULL;
1457     item->ppsz_list_text[item->i_list] = NULL;
1458
1459     return TRUE; /* Keep enumerating */
1460 }
1461
1462 static int FindDevicesCallback(vlc_object_t *object, char const *name,
1463                                vlc_value_t newval, vlc_value_t oldval, void *data)
1464 {
1465     VLC_UNUSED(newval); VLC_UNUSED(oldval); VLC_UNUSED(data);
1466
1467     module_config_t *item = config_FindConfig(object, name);
1468     if (!item)
1469         return VLC_SUCCESS;
1470
1471     /* Clear-up the current list */
1472     if (item->i_list > 0) {
1473         int i;
1474         /* Keep the first entry */
1475         for (i = 1; i < item->i_list; i++) {
1476             free(item->ppsz_list[i]);
1477             free(item->ppsz_list_text[i]);
1478         }
1479         /* TODO: Remove when no more needed */
1480         item->ppsz_list[i] = NULL;
1481         item->ppsz_list_text[i] = NULL;
1482     }
1483     item->i_list = 1;
1484
1485     /* Load direct draw DLL */
1486     HINSTANCE hddraw_dll = LoadLibrary(_T("DDRAW.DLL"));
1487     if (!hddraw_dll)
1488         return VLC_SUCCESS;
1489
1490     /* Enumerate displays */
1491     HRESULT (WINAPI *OurDirectDrawEnumerateEx)(LPDDENUMCALLBACKEXA,
1492                                                LPVOID, DWORD) =
1493         (void *)GetProcAddress(hddraw_dll, _T("DirectDrawEnumerateExA"));
1494     if (OurDirectDrawEnumerateEx)
1495         OurDirectDrawEnumerateEx(DirectXEnumCallback2, item,
1496                                  DDENUM_ATTACHEDSECONDARYDEVICES);
1497
1498     FreeLibrary(hddraw_dll);
1499
1500     /* Signal change to the interface */
1501     item->b_dirty = true;
1502
1503     return VLC_SUCCESS;
1504 }
1505
1506