]> git.sesse.net Git - vlc/blob - modules/video_output/msw/directx.c
57330452dbdd4e87bcf770f3262364c27e6a1759
[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
38 #include <errno.h>                                                 /* ENOMEM */
39
40 #ifdef HAVE_CONFIG_H
41 # include "config.h"
42 #endif
43
44 #include <vlc_common.h>
45 #include <vlc_plugin.h>
46 #include <vlc_vout.h>
47 #include <vlc_playlist.h>   /* needed for wallpaper */
48
49 #include <ddraw.h>
50 #include <commctrl.h>       /* ListView_(Get|Set)* */
51
52 #ifndef UNDER_CE
53 #   include <multimon.h>
54 #endif
55 #undef GetSystemMetrics
56
57 #ifndef MONITOR_DEFAULTTONEAREST
58 #   define MONITOR_DEFAULTTONEAREST 2
59 #endif
60
61 #include "vout.h"
62
63 /*****************************************************************************
64  * picture_sys_t: direct buffer method descriptor
65  *****************************************************************************
66  * This structure is part of the picture descriptor, it describes the
67  * DirectX specific properties of a direct buffer.
68  *****************************************************************************/
69 struct picture_sys_t
70 {
71     LPDIRECTDRAWSURFACE2 p_surface;
72     LPDIRECTDRAWSURFACE2 p_front_surface;
73     DDSURFACEDESC        ddsd;
74 };
75
76 /*****************************************************************************
77  * DirectDraw GUIDs.
78  * Defining them here allows us to get rid of the dxguid library during
79  * the linking stage.
80  *****************************************************************************/
81 #include <initguid.h>
82 #undef GUID_EXT
83 #define GUID_EXT
84 DEFINE_GUID( IID_IDirectDraw2, 0xB3A6F3E0,0x2B43,0x11CF,0xA2,0xDE,0x00,0xAA,0x00,0xB9,0x33,0x56 );
85 DEFINE_GUID( IID_IDirectDrawSurface2, 0x57805885,0x6eec,0x11cf,0x94,0x41,0xa8,0x23,0x03,0xc1,0x0e,0x27 );
86
87 /*****************************************************************************
88  * Local prototypes.
89  *****************************************************************************/
90 static int  OpenVideo  ( vlc_object_t * );
91 static void CloseVideo ( vlc_object_t * );
92
93 static int  Init      ( vout_thread_t * );
94 static void End       ( vout_thread_t * );
95 static int  Manage    ( vout_thread_t * );
96 static void Display   ( vout_thread_t *, picture_t * );
97 static void FirstDisplay( vout_thread_t *, picture_t * );
98 static void SetPalette( vout_thread_t *, uint16_t *, uint16_t *, uint16_t * );
99
100 static int  NewPictureVec  ( vout_thread_t *, picture_t * );
101 static void FreePictureVec ( vout_thread_t *, picture_t *, int );
102 static int  UpdatePictureStruct( vout_thread_t *, picture_t * );
103
104 static int  DirectXInitDDraw      ( vout_thread_t *p_vout );
105 static void DirectXCloseDDraw     ( vout_thread_t *p_vout );
106 static int  DirectXCreateDisplay  ( vout_thread_t *p_vout );
107 static void DirectXCloseDisplay   ( vout_thread_t *p_vout );
108 static int  DirectXCreateSurface  ( vout_thread_t *p_vout,
109                                     LPDIRECTDRAWSURFACE2 *, int, int, int );
110 static void DirectXCloseSurface   ( vout_thread_t *p_vout,
111                                     LPDIRECTDRAWSURFACE2 );
112 static int  DirectXCreateClipper  ( vout_thread_t *p_vout );
113 static void DirectXGetDDrawCaps   ( vout_thread_t *p_vout );
114 static int  DirectXLockSurface    ( vout_thread_t *p_vout, picture_t *p_pic );
115 static int  DirectXUnlockSurface  ( vout_thread_t *p_vout, picture_t *p_pic );
116
117 static DWORD DirectXFindColorkey( vout_thread_t *p_vout, uint32_t *i_color );
118
119 void SwitchWallpaperMode( vout_thread_t *, bool );
120
121 /* Object variables callbacks */
122 static int FindDevicesCallback( vlc_object_t *, char const *,
123                                 vlc_value_t, vlc_value_t, void * );
124 static int WallpaperCallback( vlc_object_t *, char const *,
125                               vlc_value_t, vlc_value_t, void * );
126
127 BOOL WINAPI DirectXEnumCallback( GUID* p_guid, LPTSTR psz_desc,
128                                  LPTSTR psz_drivername, VOID* p_context,
129                                  HMONITOR hmon );
130                                  
131 BOOL WINAPI DirectXEnumCallback2( GUID* p_guid, LPTSTR psz_desc,
132                                   LPTSTR psz_drivername, VOID* p_context,
133                                   HMONITOR hmon );
134                                   
135 /*****************************************************************************
136  * Module descriptor
137  *****************************************************************************/
138 #define HW_YUV_TEXT N_("Use hardware YUV->RGB conversions")
139 #define HW_YUV_LONGTEXT N_( \
140     "Try to use hardware acceleration for YUV->RGB conversions. " \
141     "This option doesn't have any effect when using overlays." )
142
143 #define SYSMEM_TEXT N_("Use video buffers in system memory")
144 #define SYSMEM_LONGTEXT N_( \
145     "Create video buffers in system memory instead of video memory. This " \
146     "isn't recommended as usually using video memory allows to benefit from " \
147     "more hardware acceleration (like rescaling or YUV->RGB conversions). " \
148     "This option doesn't have any effect when using overlays." )
149
150 #define TRIPLEBUF_TEXT N_("Use triple buffering for overlays")
151 #define TRIPLEBUF_LONGTEXT N_( \
152     "Try to use triple buffering when using YUV overlays. That results in " \
153     "much better video quality (no flickering)." )
154
155 #define DEVICE_TEXT N_("Name of desired display device")
156 #define DEVICE_LONGTEXT N_("In a multiple monitor configuration, you can " \
157     "specify the Windows device name of the display that you want the video " \
158     "window to open on. For example, \"\\\\.\\DISPLAY1\" or " \
159     "\"\\\\.\\DISPLAY2\"." )
160
161 #define WALLPAPER_TEXT N_("Enable wallpaper mode ")
162 #define WALLPAPER_LONGTEXT N_( \
163     "The wallpaper mode allows you to display the video as the desktop " \
164     "background. Note that this feature only works in overlay mode and " \
165     "the desktop must not already have a wallpaper." )
166
167 static const char *const ppsz_dev[] = { "" };
168 static const char *const ppsz_dev_text[] = { N_("Default") };
169
170 vlc_module_begin ()
171     set_shortname( "DirectX" )
172     set_category( CAT_VIDEO )
173     set_subcategory( SUBCAT_VIDEO_VOUT )
174     add_bool( "directx-hw-yuv", true, NULL, HW_YUV_TEXT, HW_YUV_LONGTEXT,
175               true )
176     add_bool( "directx-use-sysmem", false, NULL, SYSMEM_TEXT, SYSMEM_LONGTEXT,
177               true )
178     add_bool( "directx-3buffering", true, NULL, TRIPLEBUF_TEXT,
179               TRIPLEBUF_LONGTEXT, true )
180
181     add_string( "directx-device", "", NULL, DEVICE_TEXT, DEVICE_LONGTEXT,
182                 true )
183         change_string_list( ppsz_dev, ppsz_dev_text, FindDevicesCallback )
184         change_action_add( FindDevicesCallback, N_("Refresh list") )
185
186     add_bool( "directx-wallpaper", false, NULL, WALLPAPER_TEXT, WALLPAPER_LONGTEXT,
187               true )
188
189     set_description( N_("DirectX (DirectDraw) video output") )
190     set_capability( "video output", 100 )
191     add_shortcut( "directx" )
192     set_callbacks( OpenVideo, CloseVideo )
193
194     /* FIXME: Hack to avoid unregistering our window class */
195     linked_with_a_crap_library_which_uses_atexit ()
196 vlc_module_end ()
197
198 #if 0 /* FIXME */
199     /* check if we registered a window class because we need to
200      * unregister it */
201     WNDCLASS wndclass;
202     if( GetClassInfo( GetModuleHandle(NULL), "VLC DirectX", &wndclass ) )
203         UnregisterClass( "VLC DirectX", GetModuleHandle(NULL) );
204 #endif
205
206 /*****************************************************************************
207  * OpenVideo: allocate DirectX video thread output method
208  *****************************************************************************
209  * This function allocates and initialize the DirectX vout method.
210  *****************************************************************************/
211 static int OpenVideo( vlc_object_t *p_this )
212 {
213     vout_thread_t * p_vout = (vout_thread_t *)p_this;
214     vlc_value_t val;
215     HMODULE huser32;
216
217     /* Allocate structure */
218     p_vout->p_sys = calloc( 1, sizeof( vout_sys_t ) );
219     if( p_vout->p_sys == NULL )
220         return VLC_ENOMEM;
221
222     /* Initialisations */
223     p_vout->pf_init = Init;
224     p_vout->pf_end = End;
225     p_vout->pf_manage = Manage;
226     p_vout->pf_render = NULL;
227     p_vout->pf_display = FirstDisplay;
228
229     p_vout->p_sys->p_ddobject = NULL;
230     p_vout->p_sys->p_display = NULL;
231     p_vout->p_sys->p_current_surface = NULL;
232     p_vout->p_sys->p_clipper = NULL;
233     p_vout->p_sys->hwnd = p_vout->p_sys->hvideownd = NULL;
234     p_vout->p_sys->hparent = p_vout->p_sys->hfswnd = NULL;
235     p_vout->p_sys->i_changes = 0;
236     p_vout->p_sys->b_wallpaper = 0;
237     vlc_mutex_init( &p_vout->p_sys->lock );
238     SetRectEmpty( &p_vout->p_sys->rect_display );
239     SetRectEmpty( &p_vout->p_sys->rect_parent );
240
241     /* Multimonitor stuff */
242     p_vout->p_sys->hmonitor = NULL;
243     p_vout->p_sys->p_display_driver = NULL;
244     p_vout->p_sys->MonitorFromWindow = NULL;
245     p_vout->p_sys->GetMonitorInfo = NULL;
246     if( (huser32 = GetModuleHandle( _T("USER32") ) ) )
247     {
248         p_vout->p_sys->MonitorFromWindow = (HMONITOR (WINAPI *)( HWND, DWORD ))
249             GetProcAddress( huser32, _T("MonitorFromWindow") );
250         p_vout->p_sys->GetMonitorInfo =
251             GetProcAddress( huser32, _T("GetMonitorInfoW") );
252     }
253
254     var_Create( p_vout, "overlay", VLC_VAR_BOOL | VLC_VAR_DOINHERIT );
255     var_Create( p_vout, "directx-use-sysmem", VLC_VAR_BOOL|VLC_VAR_DOINHERIT );
256     var_Create( p_vout, "directx-hw-yuv", VLC_VAR_BOOL | VLC_VAR_DOINHERIT );
257     var_Create( p_vout, "directx-3buffering", VLC_VAR_BOOL|VLC_VAR_DOINHERIT );
258     var_Create( p_vout, "directx-device", VLC_VAR_STRING | VLC_VAR_DOINHERIT );
259     var_Create( p_vout, "video-title", VLC_VAR_STRING | VLC_VAR_DOINHERIT );
260     var_Create( p_vout, "disable-screensaver", VLC_VAR_BOOL | VLC_VAR_DOINHERIT );
261
262     p_vout->p_sys->b_cursor_hidden = 0;
263     p_vout->p_sys->i_lastmoved = mdate();
264     p_vout->p_sys->i_mouse_hide_timeout =
265         var_GetInteger(p_vout, "mouse-hide-timeout") * 1000;
266
267     /* Set main window's size */
268     p_vout->p_sys->i_window_width = p_vout->i_window_width;
269     p_vout->p_sys->i_window_height = p_vout->i_window_height;
270
271     if ( !CreateEventThread( p_vout ) )
272         goto error;
273
274     /* Initialise DirectDraw */
275     if( DirectXInitDDraw( p_vout ) )
276     {
277         msg_Err( p_vout, "cannot initialize DirectX DirectDraw" );
278         goto error;
279     }
280
281     /* Create the directx display */
282     if( DirectXCreateDisplay( p_vout ) )
283     {
284         msg_Err( p_vout, "cannot initialize DirectX DirectDraw" );
285         goto error;
286     }
287
288     /* Variable to indicate if the window should be on top of others */
289     /* Trigger a callback right now */
290     var_TriggerCallback( p_vout, "video-on-top" );
291
292     /* Variable to indicate if the window should be on top of others */
293     /* Trigger a callback right now */
294     var_Create( p_vout, "directx-wallpaper", VLC_VAR_BOOL|VLC_VAR_DOINHERIT );
295     val.psz_string = _("Wallpaper");
296     var_Change( p_vout, "directx-wallpaper", VLC_VAR_SETTEXT, &val, NULL );
297     var_AddCallback( p_vout, "directx-wallpaper", WallpaperCallback, NULL );
298     var_TriggerCallback( p_vout, "directx-wallpaper" );
299
300     DisableScreensaver ( p_vout );
301
302     return VLC_SUCCESS;
303
304  error:
305     CloseVideo( VLC_OBJECT(p_vout) );
306     return VLC_EGENERIC;
307 }
308
309 /*****************************************************************************
310  * Init: initialize DirectX video thread output method
311  *****************************************************************************
312  * This function create the directx surfaces needed by the output thread.
313  * It is called at the beginning of the thread.
314  *****************************************************************************/
315 static int Init( vout_thread_t *p_vout )
316 {
317     int i_chroma_backup;
318
319     /* Get a few default parameters */
320     p_vout->p_sys->b_using_overlay = var_GetBool( p_vout, "overlay" );
321     p_vout->p_sys->b_use_sysmem = var_GetBool( p_vout, "directx-use-sysmem" );
322     p_vout->p_sys->b_hw_yuv = var_GetBool( p_vout, "directx-hw-yuv" );
323     p_vout->p_sys->b_3buf_overlay = var_GetBool( p_vout, "directx-3buffering" );
324
325     /* Initialise DirectDraw if not already done.
326      * We do this here because on multi-monitor systems we may have to
327      * re-create the directdraw surfaces. */
328     if( !p_vout->p_sys->p_ddobject &&
329         DirectXInitDDraw( p_vout ) != VLC_SUCCESS )
330     {
331         msg_Err( p_vout, "cannot initialize DirectDraw" );
332         return VLC_EGENERIC;
333     }
334
335     /* Create the directx display */
336     if( !p_vout->p_sys->p_display &&
337         DirectXCreateDisplay( p_vout ) != VLC_SUCCESS )
338     {
339         msg_Err( p_vout, "cannot initialize DirectDraw" );
340         return VLC_EGENERIC;
341     }
342
343     /* Initialize the output structure.
344      * Since DirectDraw can do rescaling for us, stick to the default
345      * coordinates and aspect. */
346     p_vout->output.i_width  = p_vout->render.i_width;
347     p_vout->output.i_height = p_vout->render.i_height;
348     p_vout->output.i_aspect = p_vout->render.i_aspect;
349     p_vout->fmt_out = p_vout->fmt_in;
350     UpdateRects( p_vout, true );
351
352 #define MAX_DIRECTBUFFERS 1
353     /* Right now we use only 1 directbuffer because we don't want the
354      * video decoder to decode directly into direct buffers as they are
355      * created into video memory and video memory is _really_ slow */
356
357     /* Choose the chroma we will try first. */
358     switch( p_vout->render.i_chroma )
359     {
360         case VLC_CODEC_YUYV:
361             p_vout->output.i_chroma = VLC_CODEC_YUYV;
362             break;
363         case VLC_CODEC_UYVY:
364             p_vout->output.i_chroma = VLC_CODEC_UYVY;
365             break;
366         case VLC_CODEC_YVYU:
367             p_vout->output.i_chroma = VLC_CODEC_YVYU;
368             break;
369         default:
370             p_vout->output.i_chroma = VLC_CODEC_YV12;
371             break;
372     }
373
374     NewPictureVec( p_vout, p_vout->p_picture );
375
376     i_chroma_backup = p_vout->output.i_chroma;
377
378     if( !I_OUTPUTPICTURES )
379     {
380         /* hmmm, it didn't work! Let's try commonly supported chromas */
381         if( p_vout->output.i_chroma != VLC_CODEC_I420 )
382         {
383             p_vout->output.i_chroma = VLC_CODEC_YV12;
384             NewPictureVec( p_vout, p_vout->p_picture );
385         }
386         if( !I_OUTPUTPICTURES )
387         {
388             /* hmmm, it still didn't work! Let's try another one */
389             p_vout->output.i_chroma = VLC_CODEC_YUYV;
390             NewPictureVec( p_vout, p_vout->p_picture );
391         }
392     }
393
394     if( !I_OUTPUTPICTURES )
395     {
396         /* If it still didn't work then don't try to use an overlay */
397         p_vout->output.i_chroma = i_chroma_backup;
398         p_vout->p_sys->b_using_overlay = 0;
399         msg_Warn( p_vout, "Could not initialize directx overlay" ) ;
400         NewPictureVec( p_vout, p_vout->p_picture );
401     }
402
403     /* Change the window title bar text */
404     PostMessage( p_vout->p_sys->hwnd, WM_VLC_CHANGE_TEXT, 0, 0 );
405
406     p_vout->fmt_out.i_chroma = p_vout->output.i_chroma;
407     return VLC_SUCCESS;
408 }
409
410 /*****************************************************************************
411  * End: terminate Sys video thread output method
412  *****************************************************************************
413  * Terminate an output method created by Create.
414  * It is called at the end of the thread.
415  *****************************************************************************/
416 static void End( vout_thread_t *p_vout )
417 {
418     FreePictureVec( p_vout, p_vout->p_picture, I_OUTPUTPICTURES );
419
420     DirectXCloseDisplay( p_vout );
421     DirectXCloseDDraw( p_vout );
422
423     return;
424 }
425
426 /*****************************************************************************
427  * CloseVideo: destroy Sys video thread output method
428  *****************************************************************************
429  * Terminate an output method created by Create
430  *****************************************************************************/
431 static void CloseVideo( vlc_object_t *p_this )
432 {
433     vout_thread_t * p_vout = (vout_thread_t *)p_this;
434
435     StopEventThread( p_vout );
436
437     /* Make sure the wallpaper is restored */
438     var_DelCallback( p_vout, "directx-wallpaper", WallpaperCallback, NULL );
439     SwitchWallpaperMode( p_vout, false );
440
441     RestoreScreensaver( p_vout );
442
443     free( p_vout->p_sys );
444 }
445
446 /*****************************************************************************
447  * Manage: handle Sys events
448  *****************************************************************************
449  * This function should be called regularly by the video output thread.
450  * It returns a non null value if an error occurred.
451  *****************************************************************************/
452 static int Manage( vout_thread_t *p_vout )
453 {
454     /* If we do not control our window, we check for geometry changes
455      * ourselves because the parent might not send us its events. */
456     vlc_mutex_lock( &p_vout->p_sys->lock );
457     if( p_vout->p_sys->hparent && !p_vout->b_fullscreen )
458     {
459         RECT rect_parent;
460         POINT point;
461
462         vlc_mutex_unlock( &p_vout->p_sys->lock );
463
464         GetClientRect( p_vout->p_sys->hparent, &rect_parent );
465         point.x = point.y = 0;
466         ClientToScreen( p_vout->p_sys->hparent, &point );
467         OffsetRect( &rect_parent, point.x, point.y );
468
469         if( !EqualRect( &rect_parent, &p_vout->p_sys->rect_parent ) )
470         {
471             p_vout->p_sys->rect_parent = rect_parent;
472
473             /* This one is to force the update even if only
474              * the position has changed */
475             SetWindowPos( p_vout->p_sys->hwnd, 0, 1, 1,
476                           rect_parent.right - rect_parent.left,
477                           rect_parent.bottom - rect_parent.top, 0 );
478
479             SetWindowPos( p_vout->p_sys->hwnd, 0, 0, 0,
480                           rect_parent.right - rect_parent.left,
481                           rect_parent.bottom - rect_parent.top, 0 );
482         }
483     }
484     else
485     {
486         vlc_mutex_unlock( &p_vout->p_sys->lock );
487     }
488
489     /*
490      * Position Change
491      */
492     if( p_vout->p_sys->i_changes & DX_POSITION_CHANGE )
493     {
494         p_vout->p_sys->i_changes &= ~DX_POSITION_CHANGE;
495
496         /* Check if we are still on the same monitor */
497         if( p_vout->p_sys->MonitorFromWindow &&
498             p_vout->p_sys->hmonitor !=
499                 p_vout->p_sys->MonitorFromWindow( p_vout->p_sys->hwnd,
500                                                   MONITOR_DEFAULTTONEAREST ) )
501         {
502             /* This will force the vout core to recreate the picture buffers */
503             p_vout->i_changes |= VOUT_PICTURE_BUFFERS_CHANGE;
504         }
505     }
506
507     /* autoscale toggle */
508     if( p_vout->i_changes & VOUT_SCALE_CHANGE )
509     {
510         p_vout->i_changes &= ~VOUT_SCALE_CHANGE;
511
512         p_vout->b_autoscale = var_GetBool( p_vout, "autoscale" );
513         p_vout->i_zoom = (int) ZOOM_FP_FACTOR;
514
515         UpdateRects( p_vout, true );
516     }
517
518     /* scaling factor */
519     if( p_vout->i_changes & VOUT_ZOOM_CHANGE )
520     {
521         p_vout->i_changes &= ~VOUT_ZOOM_CHANGE;
522
523         p_vout->b_autoscale = false;
524         p_vout->i_zoom =
525             (int)( ZOOM_FP_FACTOR * var_GetFloat( p_vout, "scale" ) );
526         UpdateRects( p_vout, true );
527     }
528
529     /* Check for cropping / aspect changes */
530     if( p_vout->i_changes & VOUT_CROP_CHANGE ||
531         p_vout->i_changes & VOUT_ASPECT_CHANGE )
532     {
533         p_vout->i_changes &= ~VOUT_CROP_CHANGE;
534         p_vout->i_changes &= ~VOUT_ASPECT_CHANGE;
535
536         p_vout->fmt_out.i_x_offset = p_vout->fmt_in.i_x_offset;
537         p_vout->fmt_out.i_y_offset = p_vout->fmt_in.i_y_offset;
538         p_vout->fmt_out.i_visible_width = p_vout->fmt_in.i_visible_width;
539         p_vout->fmt_out.i_visible_height = p_vout->fmt_in.i_visible_height;
540         p_vout->fmt_out.i_aspect = p_vout->fmt_in.i_aspect;
541         p_vout->fmt_out.i_sar_num = p_vout->fmt_in.i_sar_num;
542         p_vout->fmt_out.i_sar_den = p_vout->fmt_in.i_sar_den;
543         p_vout->output.i_aspect = p_vout->fmt_in.i_aspect;
544         UpdateRects( p_vout, true );
545     }
546
547     /* We used to call the Win32 PeekMessage function here to read the window
548      * messages. But since window can stay blocked into this function for a
549      * long time (for example when you move your window on the screen), I
550      * decided to isolate PeekMessage in another thread. */
551
552     if( p_vout->p_sys->i_changes & DX_WALLPAPER_CHANGE )
553     {
554         SwitchWallpaperMode( p_vout, !p_vout->p_sys->b_wallpaper );
555         p_vout->p_sys->i_changes &= ~DX_WALLPAPER_CHANGE;
556         DirectDrawUpdateOverlay( p_vout );
557     }
558
559     /*
560      * Fullscreen change
561      */
562     if( p_vout->i_changes & VOUT_FULLSCREEN_CHANGE
563         || p_vout->p_sys->i_changes & VOUT_FULLSCREEN_CHANGE )
564     {
565         Win32ToggleFullscreen( p_vout );
566
567         p_vout->i_changes &= ~VOUT_FULLSCREEN_CHANGE;
568         p_vout->p_sys->i_changes &= ~VOUT_FULLSCREEN_CHANGE;
569     }
570
571     /*
572      * Pointer change
573      */
574     if( p_vout->b_fullscreen && !p_vout->p_sys->b_cursor_hidden &&
575         (mdate() - p_vout->p_sys->i_lastmoved) >
576             p_vout->p_sys->i_mouse_hide_timeout )
577     {
578         POINT point;
579         HWND hwnd;
580
581         /* Hide the cursor only if it is inside our window */
582         GetCursorPos( &point );
583         hwnd = WindowFromPoint(point);
584         if( hwnd == p_vout->p_sys->hwnd || hwnd == p_vout->p_sys->hvideownd )
585         {
586             PostMessage( p_vout->p_sys->hwnd, WM_VLC_HIDE_MOUSE, 0, 0 );
587         }
588         else
589         {
590             p_vout->p_sys->i_lastmoved = mdate();
591         }
592     }
593
594     /*
595      * "Always on top" status change
596      */
597     if( p_vout->p_sys->b_on_top_change )
598     {
599         vlc_value_t val;
600         HMENU hMenu = GetSystemMenu( p_vout->p_sys->hwnd, FALSE );
601
602         var_Get( p_vout, "video-on-top", &val );
603
604         /* Set the window on top if necessary */
605         if( val.b_bool && !( GetWindowLong( p_vout->p_sys->hwnd, GWL_EXSTYLE )
606                            & WS_EX_TOPMOST ) )
607         {
608             CheckMenuItem( hMenu, IDM_TOGGLE_ON_TOP,
609                            MF_BYCOMMAND | MFS_CHECKED );
610             SetWindowPos( p_vout->p_sys->hwnd, HWND_TOPMOST, 0, 0, 0, 0,
611                           SWP_NOSIZE | SWP_NOMOVE );
612         }
613         else
614         /* The window shouldn't be on top */
615         if( !val.b_bool && ( GetWindowLong( p_vout->p_sys->hwnd, GWL_EXSTYLE )
616                            & WS_EX_TOPMOST ) )
617         {
618             CheckMenuItem( hMenu, IDM_TOGGLE_ON_TOP,
619                            MF_BYCOMMAND | MFS_UNCHECKED );
620             SetWindowPos( p_vout->p_sys->hwnd, HWND_NOTOPMOST, 0, 0, 0, 0,
621                           SWP_NOSIZE | SWP_NOMOVE );
622         }
623
624         p_vout->p_sys->b_on_top_change = false;
625     }
626
627     /* Check if the event thread is still running */
628     if( !vlc_object_alive (p_vout->p_sys->p_event) )
629     {
630         return VLC_EGENERIC; /* exit */
631     }
632
633     return VLC_SUCCESS;
634 }
635
636 /*****************************************************************************
637  * Display: displays previously rendered output
638  *****************************************************************************
639  * This function sends the currently rendered image to the display, wait until
640  * it is displayed and switch the two rendering buffers, preparing next frame.
641  *****************************************************************************/
642 static void Display( vout_thread_t *p_vout, picture_t *p_pic )
643 {
644     HRESULT dxresult;
645
646     if( (p_vout->p_sys->p_display == NULL) )
647     {
648         msg_Warn( p_vout, "no display!" );
649         return;
650     }
651
652     /* Our surface can be lost so be sure to check this
653      * and restore it if need be */
654     if( IDirectDrawSurface2_IsLost( p_vout->p_sys->p_display )
655         == DDERR_SURFACELOST )
656     {
657         if( IDirectDrawSurface2_Restore( p_vout->p_sys->p_display ) == DD_OK &&
658             p_vout->p_sys->b_using_overlay )
659             DirectDrawUpdateOverlay( p_vout );
660     }
661
662     if( !p_vout->p_sys->b_using_overlay )
663     {
664         DDBLTFX  ddbltfx;
665
666         /* We ask for the "NOTEARING" option */
667         memset( &ddbltfx, 0, sizeof(DDBLTFX) );
668         ddbltfx.dwSize = sizeof(DDBLTFX);
669         ddbltfx.dwDDFX = DDBLTFX_NOTEARING;
670
671         /* Blit video surface to display */
672         dxresult = IDirectDrawSurface2_Blt( p_vout->p_sys->p_display,
673                                             &p_vout->p_sys->rect_dest_clipped,
674                                             p_pic->p_sys->p_surface,
675                                             &p_vout->p_sys->rect_src_clipped,
676                                             DDBLT_ASYNC, &ddbltfx );
677         if( dxresult != DD_OK )
678         {
679             msg_Warn( p_vout, "could not blit surface (error %li)", dxresult );
680             return;
681         }
682     }
683     else /* using overlay */
684     {
685         /* Flip the overlay buffers if we are using back buffers */
686         if( p_pic->p_sys->p_front_surface == p_pic->p_sys->p_surface )
687         {
688             return;
689         }
690
691         dxresult = IDirectDrawSurface2_Flip( p_pic->p_sys->p_front_surface,
692                                              NULL, DDFLIP_WAIT );
693         if( dxresult != DD_OK )
694         {
695             msg_Warn( p_vout, "could not flip overlay (error %li)", dxresult );
696         }
697
698         /* set currently displayed pic */
699         p_vout->p_sys->p_current_surface = p_pic->p_sys->p_front_surface;
700
701         /* Lock surface to get all the required info */
702         if( DirectXLockSurface( p_vout, p_pic ) )
703         {
704             /* AAARRGG */
705             msg_Warn( p_vout, "cannot lock surface" );
706             return;
707         }
708         DirectXUnlockSurface( p_vout, p_pic );
709     }
710 }
711
712 /*
713 ** this function is only used once when the first picture is received
714 ** this function will show the video window once video is ready for
715 ** display.
716 */
717
718 static void FirstDisplay( vout_thread_t *p_vout, picture_t *p_pic )
719 {
720     /* get initial picture rendered on overlay surface */
721     Display(p_vout, p_pic);
722
723     IDirectDraw_WaitForVerticalBlank(p_vout->p_sys->p_ddobject,
724             DDWAITVB_BLOCKBEGIN, NULL);
725
726     if( p_vout->p_sys->b_using_overlay )
727     {
728         HBRUSH brush = CreateSolidBrush( p_vout->p_sys->i_rgb_colorkey );
729         /* set the colorkey as the backgound brush for the video window */
730         SetClassLongPtr( p_vout->p_sys->hvideownd, GCLP_HBRBACKGROUND, (LONG_PTR)brush );
731     }
732     /*
733     ** Video window is initially hidden, show it now since we got a
734     ** picture to show.
735     */
736     SetWindowPos( p_vout->p_sys->hvideownd, NULL, 0, 0, 0, 0,
737         SWP_ASYNCWINDOWPOS|
738         SWP_FRAMECHANGED|
739         SWP_SHOWWINDOW|
740         SWP_NOMOVE|
741         SWP_NOSIZE|
742         SWP_NOZORDER );
743
744     /* use and restores proper display function for further pictures */
745     p_vout->pf_display = Display;
746 }
747
748 /* following functions are local */
749
750 /*****************************************************************************
751  * DirectXEnumCallback: Device enumeration
752  *****************************************************************************
753  * This callback function is called by DirectDraw once for each
754  * available DirectDraw device.
755  *****************************************************************************/
756 BOOL WINAPI DirectXEnumCallback( GUID* p_guid, LPTSTR psz_desc,
757                                  LPTSTR psz_drivername, VOID* p_context,
758                                  HMONITOR hmon )
759 {
760     vout_thread_t *p_vout = (vout_thread_t *)p_context;
761     vlc_value_t device;
762
763     msg_Dbg( p_vout, "DirectXEnumCallback: %s, %s", psz_desc, psz_drivername );
764
765     if( hmon )
766     {
767         var_Get( p_vout, "directx-device", &device );
768
769         if( ( !device.psz_string || !*device.psz_string ) &&
770             hmon == p_vout->p_sys->hmonitor )
771         {
772             free( device.psz_string );
773         }
774         else if( strcmp( psz_drivername, device.psz_string ) == 0 )
775         {
776             MONITORINFO monitor_info;
777             monitor_info.cbSize = sizeof( MONITORINFO );
778
779             if( p_vout->p_sys->GetMonitorInfo( hmon, &monitor_info ) )
780             {
781                 RECT rect;
782
783                 /* Move window to the right screen */
784                 GetWindowRect( p_vout->p_sys->hwnd, &rect );
785                 if( !IntersectRect( &rect, &rect, &monitor_info.rcWork ) )
786                 {
787                     rect.left = monitor_info.rcWork.left;
788                     rect.top = monitor_info.rcWork.top;
789                     msg_Dbg( p_vout, "DirectXEnumCallback: setting window "
790                              "position to %ld,%ld", rect.left, rect.top );
791                     SetWindowPos( p_vout->p_sys->hwnd, NULL,
792                                   rect.left, rect.top, 0, 0,
793                                   SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE );
794                 }
795             }
796
797             p_vout->p_sys->hmonitor = hmon;
798             free( device.psz_string );
799         }
800         else
801         {
802             free( device.psz_string );
803             return TRUE; /* Keep enumerating */
804         }
805
806         msg_Dbg( p_vout, "selecting %s, %s", psz_desc, psz_drivername );
807         p_vout->p_sys->p_display_driver = malloc( sizeof(GUID) );
808         if( p_vout->p_sys->p_display_driver )
809             memcpy( p_vout->p_sys->p_display_driver, p_guid, sizeof(GUID) );
810     }
811
812     return TRUE; /* Keep enumerating */
813 }
814
815 /*****************************************************************************
816  * DirectXInitDDraw: Takes care of all the DirectDraw initialisations
817  *****************************************************************************
818  * This function initialise and allocate resources for DirectDraw.
819  *****************************************************************************/
820 static int DirectXInitDDraw( vout_thread_t *p_vout )
821 {
822     HRESULT dxresult;
823     HRESULT (WINAPI *OurDirectDrawCreate)(GUID *,LPDIRECTDRAW *,IUnknown *);
824     HRESULT (WINAPI *OurDirectDrawEnumerateEx)( LPDDENUMCALLBACKEXA, LPVOID,
825                                                 DWORD );
826     LPDIRECTDRAW p_ddobject;
827
828     msg_Dbg( p_vout, "DirectXInitDDraw" );
829
830     /* Load direct draw DLL */
831     p_vout->p_sys->hddraw_dll = LoadLibrary(_T("DDRAW.DLL"));
832     if( p_vout->p_sys->hddraw_dll == NULL )
833     {
834         msg_Warn( p_vout, "DirectXInitDDraw failed loading ddraw.dll" );
835         goto error;
836     }
837
838     OurDirectDrawCreate =
839       (void *)GetProcAddress( p_vout->p_sys->hddraw_dll,
840                               _T("DirectDrawCreate") );
841     if( OurDirectDrawCreate == NULL )
842     {
843         msg_Err( p_vout, "DirectXInitDDraw failed GetProcAddress" );
844         goto error;
845     }
846
847     OurDirectDrawEnumerateEx =
848       (void *)GetProcAddress( p_vout->p_sys->hddraw_dll,
849                               _T("DirectDrawEnumerateExW") );
850
851     if( OurDirectDrawEnumerateEx && p_vout->p_sys->MonitorFromWindow )
852     {
853         vlc_value_t device;
854
855         var_Get( p_vout, "directx-device", &device );
856         if( device.psz_string )
857         {
858             msg_Dbg( p_vout, "directx-device: %s", device.psz_string );
859             free( device.psz_string );
860         }
861
862         p_vout->p_sys->hmonitor =
863             p_vout->p_sys->MonitorFromWindow( p_vout->p_sys->hwnd,
864                                               MONITOR_DEFAULTTONEAREST );
865
866         /* Enumerate displays */
867         OurDirectDrawEnumerateEx( DirectXEnumCallback, p_vout,
868                                   DDENUM_ATTACHEDSECONDARYDEVICES );
869     }
870
871     /* Initialize DirectDraw now */
872     dxresult = OurDirectDrawCreate( p_vout->p_sys->p_display_driver,
873                                     &p_ddobject, NULL );
874     if( dxresult != DD_OK )
875     {
876         msg_Err( p_vout, "DirectXInitDDraw cannot initialize DDraw" );
877         goto error;
878     }
879
880     /* Get the IDirectDraw2 interface */
881     dxresult = IDirectDraw_QueryInterface( p_ddobject, &IID_IDirectDraw2,
882                                         &p_vout->p_sys->p_ddobject );
883     /* Release the unused interface */
884     IDirectDraw_Release( p_ddobject );
885     if( dxresult != DD_OK )
886     {
887         msg_Err( p_vout, "cannot get IDirectDraw2 interface" );
888         goto error;
889     }
890
891     /* Set DirectDraw Cooperative level, ie what control we want over Windows
892      * display */
893     dxresult = IDirectDraw2_SetCooperativeLevel( p_vout->p_sys->p_ddobject,
894                                                  NULL, DDSCL_NORMAL );
895     if( dxresult != DD_OK )
896     {
897         msg_Err( p_vout, "cannot set direct draw cooperative level" );
898         goto error;
899     }
900
901     /* Get the size of the current display device */
902     if( p_vout->p_sys->hmonitor && p_vout->p_sys->GetMonitorInfo )
903     {
904         MONITORINFO monitor_info;
905         monitor_info.cbSize = sizeof( MONITORINFO );
906         p_vout->p_sys->GetMonitorInfo( p_vout->p_sys->hmonitor,
907                                        &monitor_info );
908         p_vout->p_sys->rect_display = monitor_info.rcMonitor;
909     }
910     else
911     {
912         p_vout->p_sys->rect_display.left = 0;
913         p_vout->p_sys->rect_display.top = 0;
914         p_vout->p_sys->rect_display.right  = GetSystemMetrics(SM_CXSCREEN);
915         p_vout->p_sys->rect_display.bottom = GetSystemMetrics(SM_CYSCREEN);
916     }
917
918     msg_Dbg( p_vout, "screen dimensions (%lix%li,%lix%li)",
919              p_vout->p_sys->rect_display.left,
920              p_vout->p_sys->rect_display.top,
921              p_vout->p_sys->rect_display.right,
922              p_vout->p_sys->rect_display.bottom );
923
924     /* Probe the capabilities of the hardware */
925     DirectXGetDDrawCaps( p_vout );
926
927     msg_Dbg( p_vout, "End DirectXInitDDraw" );
928     return VLC_SUCCESS;
929
930  error:
931     if( p_vout->p_sys->p_ddobject )
932         IDirectDraw2_Release( p_vout->p_sys->p_ddobject );
933     if( p_vout->p_sys->hddraw_dll )
934         FreeLibrary( p_vout->p_sys->hddraw_dll );
935     p_vout->p_sys->hddraw_dll = NULL;
936     p_vout->p_sys->p_ddobject = NULL;
937     return VLC_EGENERIC;
938 }
939
940 /*****************************************************************************
941  * DirectXCreateDisplay: create the DirectDraw display.
942  *****************************************************************************
943  * Create and initialize display according to preferences specified in the vout
944  * thread fields.
945  *****************************************************************************/
946 static int DirectXCreateDisplay( vout_thread_t *p_vout )
947 {
948     HRESULT              dxresult;
949     DDSURFACEDESC        ddsd;
950     LPDIRECTDRAWSURFACE  p_display;
951
952     msg_Dbg( p_vout, "DirectXCreateDisplay" );
953
954     /* Now get the primary surface. This surface is what you actually see
955      * on your screen */
956     memset( &ddsd, 0, sizeof( DDSURFACEDESC ));
957     ddsd.dwSize = sizeof(DDSURFACEDESC);
958     ddsd.dwFlags = DDSD_CAPS;
959     ddsd.ddsCaps.dwCaps = DDSCAPS_PRIMARYSURFACE;
960
961     dxresult = IDirectDraw2_CreateSurface( p_vout->p_sys->p_ddobject,
962                                            &ddsd, &p_display, NULL );
963     if( dxresult != DD_OK )
964     {
965         msg_Err( p_vout, "cannot get primary surface (error %li)", dxresult );
966         return VLC_EGENERIC;
967     }
968
969     dxresult = IDirectDrawSurface_QueryInterface( p_display,
970                                          &IID_IDirectDrawSurface2,
971                                          &p_vout->p_sys->p_display );
972     /* Release the old interface */
973     IDirectDrawSurface_Release( p_display );
974     if ( dxresult != DD_OK )
975     {
976         msg_Err( p_vout, "cannot query IDirectDrawSurface2 interface "
977                          "(error %li)", dxresult );
978         return VLC_EGENERIC;
979     }
980
981     /* The clipper will be used only in non-overlay mode */
982     DirectXCreateClipper( p_vout );
983
984     /* Make sure the colorkey will be painted */
985     p_vout->p_sys->i_colorkey = 1;
986     p_vout->p_sys->i_rgb_colorkey =
987         DirectXFindColorkey( p_vout, &p_vout->p_sys->i_colorkey );
988
989     UpdateRects( p_vout, true );
990
991     return VLC_SUCCESS;
992 }
993
994 /*****************************************************************************
995  * DirectXCreateClipper: Create a clipper that will be used when blitting the
996  *                       RGB surface to the main display.
997  *****************************************************************************
998  * This clipper prevents us to modify by mistake anything on the screen
999  * which doesn't belong to our window. For example when a part of our video
1000  * window is hidden by another window.
1001  *****************************************************************************/
1002 static int DirectXCreateClipper( vout_thread_t *p_vout )
1003 {
1004     HRESULT dxresult;
1005
1006     msg_Dbg( p_vout, "DirectXCreateClipper" );
1007
1008     /* Create the clipper */
1009     dxresult = IDirectDraw2_CreateClipper( p_vout->p_sys->p_ddobject, 0,
1010                                            &p_vout->p_sys->p_clipper, NULL );
1011     if( dxresult != DD_OK )
1012     {
1013         msg_Warn( p_vout, "cannot create clipper (error %li)", dxresult );
1014         goto error;
1015     }
1016
1017     /* Associate the clipper to the window */
1018     dxresult = IDirectDrawClipper_SetHWnd( p_vout->p_sys->p_clipper, 0,
1019                                            p_vout->p_sys->hvideownd );
1020     if( dxresult != DD_OK )
1021     {
1022         msg_Warn( p_vout, "cannot attach clipper to window (error %li)",
1023                           dxresult );
1024         goto error;
1025     }
1026
1027     /* associate the clipper with the surface */
1028     dxresult = IDirectDrawSurface_SetClipper(p_vout->p_sys->p_display,
1029                                              p_vout->p_sys->p_clipper);
1030     if( dxresult != DD_OK )
1031     {
1032         msg_Warn( p_vout, "cannot attach clipper to surface (error %li)",
1033                           dxresult );
1034         goto error;
1035     }
1036
1037     return VLC_SUCCESS;
1038
1039  error:
1040     if( p_vout->p_sys->p_clipper )
1041     {
1042         IDirectDrawClipper_Release( p_vout->p_sys->p_clipper );
1043     }
1044     p_vout->p_sys->p_clipper = NULL;
1045     return VLC_EGENERIC;
1046 }
1047
1048 /*****************************************************************************
1049  * DirectXCreateSurface: create an YUV overlay or RGB surface for the video.
1050  *****************************************************************************
1051  * The best method of display is with an YUV overlay because the YUV->RGB
1052  * conversion is done in hardware.
1053  * You can also create a plain RGB surface.
1054  * ( Maybe we could also try an RGB overlay surface, which could have hardware
1055  * scaling and which would also be faster in window mode because you don't
1056  * need to do any blitting to the main display...)
1057  *****************************************************************************/
1058 static int DirectXCreateSurface( vout_thread_t *p_vout,
1059                                  LPDIRECTDRAWSURFACE2 *pp_surface_final,
1060                                  int i_chroma, int b_overlay,
1061                                  int i_backbuffers )
1062 {
1063     HRESULT dxresult;
1064     LPDIRECTDRAWSURFACE p_surface;
1065     DDSURFACEDESC ddsd;
1066
1067     /* Create the video surface */
1068     if( b_overlay )
1069     {
1070         /* Now try to create the YUV overlay surface.
1071          * This overlay will be displayed on top of the primary surface.
1072          * A color key is used to determine whether or not the overlay will be
1073          * displayed, ie the overlay will be displayed in place of the primary
1074          * surface wherever the primary surface will have this color.
1075          * The video window has been created with a background of this color so
1076          * the overlay will be only displayed on top of this window */
1077
1078         memset( &ddsd, 0, sizeof( DDSURFACEDESC ));
1079         ddsd.dwSize = sizeof(DDSURFACEDESC);
1080         ddsd.ddpfPixelFormat.dwSize = sizeof(DDPIXELFORMAT);
1081         ddsd.ddpfPixelFormat.dwFlags = DDPF_FOURCC;
1082         ddsd.ddpfPixelFormat.dwFourCC = i_chroma;
1083         ddsd.dwFlags = DDSD_CAPS | DDSD_HEIGHT | DDSD_WIDTH | DDSD_PIXELFORMAT;
1084         ddsd.dwFlags |= (i_backbuffers ? DDSD_BACKBUFFERCOUNT : 0);
1085         ddsd.ddsCaps.dwCaps = DDSCAPS_OVERLAY | DDSCAPS_VIDEOMEMORY;
1086         ddsd.ddsCaps.dwCaps |= (i_backbuffers ? DDSCAPS_COMPLEX | DDSCAPS_FLIP
1087                                 : 0 );
1088         ddsd.dwHeight = p_vout->render.i_height;
1089         ddsd.dwWidth = p_vout->render.i_width;
1090         ddsd.dwBackBufferCount = i_backbuffers;
1091
1092         dxresult = IDirectDraw2_CreateSurface( p_vout->p_sys->p_ddobject,
1093                                                &ddsd, &p_surface, NULL );
1094         if( dxresult != DD_OK )
1095         {
1096             *pp_surface_final = NULL;
1097             return VLC_EGENERIC;
1098         }
1099     }
1100
1101     if( !b_overlay )
1102     {
1103         bool b_rgb_surface =
1104             ( i_chroma == VLC_CODEC_RGB8 )
1105           || ( i_chroma == VLC_CODEC_RGB15 )
1106            || ( i_chroma == VLC_CODEC_RGB16 )
1107             || ( i_chroma == VLC_CODEC_RGB24 )
1108              || ( i_chroma == VLC_CODEC_RGB32 );
1109
1110         memset( &ddsd, 0, sizeof( DDSURFACEDESC ) );
1111         ddsd.dwSize = sizeof(DDSURFACEDESC);
1112         ddsd.ddpfPixelFormat.dwSize = sizeof(DDPIXELFORMAT);
1113         ddsd.dwFlags = DDSD_HEIGHT | DDSD_WIDTH | DDSD_CAPS;
1114         ddsd.ddsCaps.dwCaps = DDSCAPS_OFFSCREENPLAIN;
1115         ddsd.dwHeight = p_vout->render.i_height;
1116         ddsd.dwWidth = p_vout->render.i_width;
1117
1118         if( p_vout->p_sys->b_use_sysmem )
1119             ddsd.ddsCaps.dwCaps |= DDSCAPS_SYSTEMMEMORY;
1120         else
1121             ddsd.ddsCaps.dwCaps |= DDSCAPS_VIDEOMEMORY;
1122
1123         if( !b_rgb_surface )
1124         {
1125             ddsd.dwFlags |= DDSD_PIXELFORMAT;
1126             ddsd.ddpfPixelFormat.dwFlags = DDPF_FOURCC;
1127             ddsd.ddpfPixelFormat.dwFourCC = i_chroma;
1128         }
1129
1130         dxresult = IDirectDraw2_CreateSurface( p_vout->p_sys->p_ddobject,
1131                                                &ddsd, &p_surface, NULL );
1132         if( dxresult != DD_OK )
1133         {
1134             *pp_surface_final = NULL;
1135             return VLC_EGENERIC;
1136         }
1137     }
1138
1139     /* Now that the surface is created, try to get a newer DirectX interface */
1140     dxresult = IDirectDrawSurface_QueryInterface( p_surface,
1141                                      &IID_IDirectDrawSurface2,
1142                                      (LPVOID *)pp_surface_final );
1143     IDirectDrawSurface_Release( p_surface );    /* Release the old interface */
1144     if ( dxresult != DD_OK )
1145     {
1146         msg_Err( p_vout, "cannot query IDirectDrawSurface2 interface "
1147                          "(error %li)", dxresult );
1148         *pp_surface_final = NULL;
1149         return VLC_EGENERIC;
1150     }
1151
1152     if( b_overlay )
1153     {
1154         /* Check the overlay is useable as some graphics cards allow creating
1155          * several overlays but only one can be used at one time. */
1156         p_vout->p_sys->p_current_surface = *pp_surface_final;
1157         if( DirectDrawUpdateOverlay( p_vout ) != VLC_SUCCESS )
1158         {
1159             IDirectDrawSurface2_Release( *pp_surface_final );
1160             *pp_surface_final = NULL;
1161             msg_Err( p_vout, "overlay unuseable (might already be in use)" );
1162             return VLC_EGENERIC;
1163         }
1164     }
1165
1166     return VLC_SUCCESS;
1167 }
1168
1169 /*****************************************************************************
1170  * DirectDrawUpdateOverlay: Move or resize overlay surface on video display.
1171  *****************************************************************************
1172  * This function is used to move or resize an overlay surface on the screen.
1173  * Ususally the overlay is moved by the user and thus, by a move or resize
1174  * event (in Manage).
1175  *****************************************************************************/
1176 int DirectDrawUpdateOverlay( vout_thread_t *p_vout )
1177 {
1178     DDOVERLAYFX     ddofx;
1179     DWORD           dwFlags;
1180     HRESULT         dxresult;
1181     RECT            rect_src = p_vout->p_sys->rect_src_clipped;
1182     RECT            rect_dest = p_vout->p_sys->rect_dest_clipped;
1183
1184     if( !p_vout->p_sys->b_using_overlay ) return VLC_EGENERIC;
1185
1186     if( p_vout->p_sys->b_wallpaper )
1187     {
1188         unsigned i_x, i_y, i_width, i_height;
1189
1190         rect_src.left = p_vout->fmt_out.i_x_offset;
1191         rect_src.top = p_vout->fmt_out.i_y_offset;
1192         rect_src.right = rect_src.left + p_vout->fmt_out.i_visible_width;
1193         rect_src.bottom = rect_src.top + p_vout->fmt_out.i_visible_height;
1194
1195         rect_dest = p_vout->p_sys->rect_display;
1196         vout_PlacePicture( p_vout, rect_dest.right, rect_dest.bottom,
1197                            &i_x, &i_y, &i_width, &i_height );
1198
1199         rect_dest.left += i_x;
1200         rect_dest.right = rect_dest.left + i_width;
1201         rect_dest.top += i_y;
1202         rect_dest.bottom = rect_dest.top + i_height;
1203     }
1204
1205     vlc_mutex_lock( &p_vout->p_sys->lock );
1206     if( p_vout->p_sys->p_current_surface == NULL )
1207     {
1208         vlc_mutex_unlock( &p_vout->p_sys->lock );
1209         return VLC_EGENERIC;
1210     }
1211
1212     /* The new window dimensions should already have been computed by the
1213      * caller of this function */
1214
1215     /* Position and show the overlay */
1216     memset(&ddofx, 0, sizeof(DDOVERLAYFX));
1217     ddofx.dwSize = sizeof(DDOVERLAYFX);
1218     ddofx.dckDestColorkey.dwColorSpaceLowValue = p_vout->p_sys->i_colorkey;
1219     ddofx.dckDestColorkey.dwColorSpaceHighValue = p_vout->p_sys->i_colorkey;
1220
1221     dwFlags = DDOVER_SHOW | DDOVER_KEYDESTOVERRIDE;
1222
1223     dxresult = IDirectDrawSurface2_UpdateOverlay(
1224                    p_vout->p_sys->p_current_surface,
1225                    &rect_src, p_vout->p_sys->p_display, &rect_dest,
1226                    dwFlags, &ddofx );
1227
1228     vlc_mutex_unlock( &p_vout->p_sys->lock );
1229
1230     if(dxresult != DD_OK)
1231     {
1232         msg_Warn( p_vout, "DirectDrawUpdateOverlay cannot move/resize overlay" );
1233         return VLC_EGENERIC;
1234     }
1235
1236     return VLC_SUCCESS;
1237 }
1238
1239 /*****************************************************************************
1240  * DirectXCloseDDraw: Release the DDraw object allocated by DirectXInitDDraw
1241  *****************************************************************************
1242  * This function returns all resources allocated by DirectXInitDDraw.
1243  *****************************************************************************/
1244 static void DirectXCloseDDraw( vout_thread_t *p_vout )
1245 {
1246     msg_Dbg( p_vout, "DirectXCloseDDraw" );
1247     if( p_vout->p_sys->p_ddobject != NULL )
1248     {
1249         IDirectDraw2_Release(p_vout->p_sys->p_ddobject);
1250         p_vout->p_sys->p_ddobject = NULL;
1251     }
1252
1253     if( p_vout->p_sys->hddraw_dll != NULL )
1254     {
1255         FreeLibrary( p_vout->p_sys->hddraw_dll );
1256         p_vout->p_sys->hddraw_dll = NULL;
1257     }
1258
1259     free( p_vout->p_sys->p_display_driver );
1260     p_vout->p_sys->p_display_driver = NULL;
1261
1262     p_vout->p_sys->hmonitor = NULL;
1263 }
1264
1265 /*****************************************************************************
1266  * DirectXCloseDisplay: close and reset the DirectX display device
1267  *****************************************************************************
1268  * This function returns all resources allocated by DirectXCreateDisplay.
1269  *****************************************************************************/
1270 static void DirectXCloseDisplay( vout_thread_t *p_vout )
1271 {
1272     msg_Dbg( p_vout, "DirectXCloseDisplay" );
1273
1274     if( p_vout->p_sys->p_clipper != NULL )
1275     {
1276         msg_Dbg( p_vout, "DirectXCloseDisplay clipper" );
1277         IDirectDrawClipper_Release( p_vout->p_sys->p_clipper );
1278         p_vout->p_sys->p_clipper = NULL;
1279     }
1280
1281     if( p_vout->p_sys->p_display != NULL )
1282     {
1283         msg_Dbg( p_vout, "DirectXCloseDisplay display" );
1284         IDirectDrawSurface2_Release( p_vout->p_sys->p_display );
1285         p_vout->p_sys->p_display = NULL;
1286     }
1287 }
1288
1289 /*****************************************************************************
1290  * DirectXCloseSurface: close the YUV overlay or RGB surface.
1291  *****************************************************************************
1292  * This function returns all resources allocated for the surface.
1293  *****************************************************************************/
1294 static void DirectXCloseSurface( vout_thread_t *p_vout,
1295                                  LPDIRECTDRAWSURFACE2 p_surface )
1296 {
1297     msg_Dbg( p_vout, "DirectXCloseSurface" );
1298     if( p_surface != NULL )
1299     {
1300         IDirectDrawSurface2_Release( p_surface );
1301     }
1302 }
1303
1304 /*****************************************************************************
1305  * NewPictureVec: allocate a picture
1306  * FIXME? make it work for i_num_pic pictures...
1307  *****************************************************************************
1308  * Returns 0 on success, -1 otherwise
1309  *****************************************************************************/
1310 static int NewPictureVec( vout_thread_t *p_vout, picture_t *p_pic )
1311 {
1312     int i;
1313     int i_ret = VLC_SUCCESS;
1314     LPDIRECTDRAWSURFACE2 p_surface;
1315
1316     msg_Dbg( p_vout, "NewPictureVec overlay:%s chroma:%.4s",
1317              p_vout->p_sys->b_using_overlay ? "yes" : "no",
1318              (char *)&p_vout->output.i_chroma );
1319
1320     I_OUTPUTPICTURES = 0;
1321
1322     /* First we try to use an YUV overlay surface.
1323      * The overlay surface that we create won't be used to decode directly
1324      * into it because accessing video memory directly is way to slow (remember
1325      * that pictures are decoded macroblock per macroblock). Instead the video
1326      * will be decoded in picture buffers in system memory which will then be
1327      * memcpy() to the overlay surface. */
1328     if( p_vout->p_sys->b_using_overlay )
1329     {
1330         /* Triple buffering rocks! it doesn't have any processing overhead
1331          * (you don't have to wait for the vsync) and provides for a very nice
1332          * video quality (no tearing). */
1333         if( p_vout->p_sys->b_3buf_overlay )
1334             i_ret = DirectXCreateSurface( p_vout, &p_surface,
1335                                           p_vout->output.i_chroma,
1336                                           p_vout->p_sys->b_using_overlay,
1337                                           2 /* number of backbuffers */ );
1338
1339         if( !p_vout->p_sys->b_3buf_overlay || i_ret != VLC_SUCCESS )
1340         {
1341             /* Try to reduce the number of backbuffers */
1342             i_ret = DirectXCreateSurface( p_vout, &p_surface,
1343                                           p_vout->output.i_chroma,
1344                                           p_vout->p_sys->b_using_overlay,
1345                                           0 /* number of backbuffers */ );
1346         }
1347
1348         if( i_ret == VLC_SUCCESS )
1349         {
1350             DDSCAPS dds_caps;
1351             picture_t front_pic;
1352             picture_sys_t front_pic_sys;
1353             front_pic.p_sys = &front_pic_sys;
1354
1355             /* Allocate internal structure */
1356             p_pic[0].p_sys = malloc( sizeof( picture_sys_t ) );
1357             if( p_pic[0].p_sys == NULL )
1358             {
1359                 DirectXCloseSurface( p_vout, p_surface );
1360                 return VLC_ENOMEM;
1361             }
1362
1363             /* set front buffer */
1364             p_pic[0].p_sys->p_front_surface = p_surface;
1365
1366             /* Get the back buffer */
1367             memset( &dds_caps, 0, sizeof( DDSCAPS ) );
1368             dds_caps.dwCaps = DDSCAPS_BACKBUFFER;
1369             if( DD_OK != IDirectDrawSurface2_GetAttachedSurface(
1370                                                 p_surface, &dds_caps,
1371                                                 &p_pic[0].p_sys->p_surface ) )
1372             {
1373                 msg_Warn( p_vout, "NewPictureVec could not get back buffer" );
1374                 /* front buffer is the same as back buffer */
1375                 p_pic[0].p_sys->p_surface = p_surface;
1376             }
1377
1378
1379             p_vout->p_sys->p_current_surface = front_pic.p_sys->p_surface =
1380                 p_pic[0].p_sys->p_front_surface;
1381
1382             /* Reset the front buffer memory */
1383             if( DirectXLockSurface( p_vout, &front_pic ) == VLC_SUCCESS )
1384             {
1385                 int i,j;
1386                 for( i = 0; i < front_pic.i_planes; i++ )
1387                     for( j = 0; j < front_pic.p[i].i_visible_lines; j++)
1388                         memset( front_pic.p[i].p_pixels + j *
1389                                 front_pic.p[i].i_pitch, 127,
1390                                 front_pic.p[i].i_visible_pitch );
1391
1392                 DirectXUnlockSurface( p_vout, &front_pic );
1393             }
1394
1395             DirectDrawUpdateOverlay( p_vout );
1396             I_OUTPUTPICTURES = 1;
1397             msg_Dbg( p_vout, "YUV overlay created successfully" );
1398         }
1399     }
1400
1401     /* As we can't have an overlay, we'll try to create a plain offscreen
1402      * surface. This surface will reside in video memory because there's a
1403      * better chance then that we'll be able to use some kind of hardware
1404      * acceleration like rescaling, blitting or YUV->RGB conversions.
1405      * We then only need to blit this surface onto the main display when we
1406      * want to display it */
1407     if( !p_vout->p_sys->b_using_overlay )
1408     {
1409         if( p_vout->p_sys->b_hw_yuv )
1410         {
1411             DWORD i_codes;
1412             DWORD *pi_codes;
1413             bool b_result = false;
1414
1415             /* Check if the chroma is supported first. This is required
1416              * because a few buggy drivers don't mind creating the surface
1417              * even if they don't know about the chroma. */
1418             if( IDirectDraw2_GetFourCCCodes( p_vout->p_sys->p_ddobject,
1419                                              &i_codes, NULL ) == DD_OK )
1420             {
1421                 pi_codes = malloc( i_codes * sizeof(DWORD) );
1422                 if( pi_codes && IDirectDraw2_GetFourCCCodes(
1423                     p_vout->p_sys->p_ddobject, &i_codes, pi_codes ) == DD_OK )
1424                 {
1425                     for( i = 0; i < (int)i_codes; i++ )
1426                     {
1427                         if( p_vout->output.i_chroma == pi_codes[i] )
1428                         {
1429                             b_result = true;
1430                             break;
1431                         }
1432                     }
1433                 }
1434             }
1435
1436             if( b_result )
1437                 i_ret = DirectXCreateSurface( p_vout, &p_surface,
1438                                               p_vout->output.i_chroma,
1439                                               0 /* no overlay */,
1440                                               0 /* no back buffers */ );
1441             else
1442                 p_vout->p_sys->b_hw_yuv = false;
1443         }
1444
1445         if( i_ret || !p_vout->p_sys->b_hw_yuv )
1446         {
1447             /* Our last choice is to use a plain RGB surface */
1448             DDPIXELFORMAT ddpfPixelFormat;
1449
1450             ddpfPixelFormat.dwSize = sizeof(DDPIXELFORMAT);
1451             IDirectDrawSurface2_GetPixelFormat( p_vout->p_sys->p_display,
1452                                                 &ddpfPixelFormat );
1453
1454             if( ddpfPixelFormat.dwFlags & DDPF_RGB )
1455             {
1456                 switch( ddpfPixelFormat.dwRGBBitCount )
1457                 {
1458                 case 8:
1459                     p_vout->output.i_chroma = VLC_CODEC_RGB8;
1460                     p_vout->output.pf_setpalette = SetPalette;
1461                     break;
1462                 case 15:
1463                     p_vout->output.i_chroma = VLC_CODEC_RGB15;
1464                     break;
1465                 case 16:
1466                     p_vout->output.i_chroma = VLC_CODEC_RGB16;
1467                     break;
1468                 case 24:
1469                     p_vout->output.i_chroma = VLC_CODEC_RGB24;
1470                     break;
1471                 case 32:
1472                     p_vout->output.i_chroma = VLC_CODEC_RGB32;
1473                     break;
1474                 default:
1475                     msg_Err( p_vout, "unknown screen depth" );
1476                     return VLC_EGENERIC;
1477                 }
1478                 p_vout->output.i_rmask = ddpfPixelFormat.dwRBitMask;
1479                 p_vout->output.i_gmask = ddpfPixelFormat.dwGBitMask;
1480                 p_vout->output.i_bmask = ddpfPixelFormat.dwBBitMask;
1481             }
1482
1483             p_vout->p_sys->b_hw_yuv = 0;
1484
1485             i_ret = DirectXCreateSurface( p_vout, &p_surface,
1486                                           p_vout->output.i_chroma,
1487                                           0 /* no overlay */,
1488                                           0 /* no back buffers */ );
1489
1490             if( i_ret && !p_vout->p_sys->b_use_sysmem )
1491             {
1492                 /* Give it a last try with b_use_sysmem enabled */
1493                 p_vout->p_sys->b_use_sysmem = 1;
1494
1495                 i_ret = DirectXCreateSurface( p_vout, &p_surface,
1496                                               p_vout->output.i_chroma,
1497                                               0 /* no overlay */,
1498                                               0 /* no back buffers */ );
1499             }
1500         }
1501
1502         if( i_ret == VLC_SUCCESS )
1503         {
1504             /* Allocate internal structure */
1505             p_pic[0].p_sys = malloc( sizeof( picture_sys_t ) );
1506             if( p_pic[0].p_sys == NULL )
1507             {
1508                 DirectXCloseSurface( p_vout, p_surface );
1509                 return VLC_ENOMEM;
1510             }
1511
1512             p_pic[0].p_sys->p_surface = p_pic[0].p_sys->p_front_surface
1513                 = p_surface;
1514
1515             I_OUTPUTPICTURES = 1;
1516
1517             msg_Dbg( p_vout, "created plain surface of chroma:%.4s",
1518                      (char *)&p_vout->output.i_chroma );
1519         }
1520     }
1521
1522
1523     /* Now that we've got all our direct-buffers, we can finish filling in the
1524      * picture_t structures */
1525     for( i = 0; i < I_OUTPUTPICTURES; i++ )
1526     {
1527         p_pic[i].i_status = DESTROYED_PICTURE;
1528         p_pic[i].i_type   = DIRECT_PICTURE;
1529         p_pic[i].b_slow   = true;
1530         p_pic[i].pf_lock  = DirectXLockSurface;
1531         p_pic[i].pf_unlock = DirectXUnlockSurface;
1532         PP_OUTPUTPICTURE[i] = &p_pic[i];
1533
1534         if( DirectXLockSurface( p_vout, &p_pic[i] ) != VLC_SUCCESS )
1535         {
1536             /* AAARRGG */
1537             FreePictureVec( p_vout, p_pic, I_OUTPUTPICTURES );
1538             I_OUTPUTPICTURES = 0;
1539             msg_Err( p_vout, "cannot lock surface" );
1540             return VLC_EGENERIC;
1541         }
1542         DirectXUnlockSurface( p_vout, &p_pic[i] );
1543     }
1544
1545     msg_Dbg( p_vout, "End NewPictureVec (%s)",
1546              I_OUTPUTPICTURES ? "succeeded" : "failed" );
1547
1548     return VLC_SUCCESS;
1549 }
1550
1551 /*****************************************************************************
1552  * FreePicture: destroy a picture vector allocated with NewPictureVec
1553  *****************************************************************************
1554  *
1555  *****************************************************************************/
1556 static void FreePictureVec( vout_thread_t *p_vout, picture_t *p_pic,
1557                             int i_num_pics )
1558 {
1559     int i;
1560
1561     vlc_mutex_lock( &p_vout->p_sys->lock );
1562     p_vout->p_sys->p_current_surface = 0;
1563     vlc_mutex_unlock( &p_vout->p_sys->lock );
1564
1565     for( i = 0; i < i_num_pics; i++ )
1566     {
1567         DirectXCloseSurface( p_vout, p_pic[i].p_sys->p_front_surface );
1568
1569         for( i = 0; i < i_num_pics; i++ )
1570         {
1571             free( p_pic[i].p_sys );
1572         }
1573     }
1574 }
1575
1576 /*****************************************************************************
1577  * UpdatePictureStruct: updates the internal data in the picture_t structure
1578  *****************************************************************************
1579  * This will setup stuff for use by the video_output thread
1580  *****************************************************************************/
1581 static int UpdatePictureStruct( vout_thread_t *p_vout, picture_t *p_pic )
1582 {
1583     switch( p_vout->output.i_chroma )
1584     {
1585         case VLC_CODEC_RGB8:
1586         case VLC_CODEC_RGB15:
1587         case VLC_CODEC_RGB16:
1588         case VLC_CODEC_RGB24:
1589         case VLC_CODEC_RGB32:
1590             p_pic->p->p_pixels = p_pic->p_sys->ddsd.lpSurface;
1591             p_pic->p->i_lines = p_vout->output.i_height;
1592             p_pic->p->i_visible_lines = p_vout->output.i_height;
1593             p_pic->p->i_pitch = p_pic->p_sys->ddsd.lPitch;
1594             switch( p_vout->output.i_chroma )
1595             {
1596                 case VLC_CODEC_RGB8:
1597                     p_pic->p->i_pixel_pitch = 1;
1598                     break;
1599                 case VLC_CODEC_RGB15:
1600                 case VLC_CODEC_RGB16:
1601                     p_pic->p->i_pixel_pitch = 2;
1602                     break;
1603                 case VLC_CODEC_RGB24:
1604                     p_pic->p->i_pixel_pitch = 3;
1605                     break;
1606                 case VLC_CODEC_RGB32:
1607                     p_pic->p->i_pixel_pitch = 4;
1608                     break;
1609                 default:
1610                     return VLC_EGENERIC;
1611             }
1612             p_pic->p->i_visible_pitch = p_vout->output.i_width *
1613               p_pic->p->i_pixel_pitch;
1614             p_pic->i_planes = 1;
1615             break;
1616
1617         case VLC_CODEC_YV12:
1618
1619             /* U and V inverted compared to I420
1620              * Fixme: this should be handled by the vout core */
1621             p_vout->output.i_chroma = VLC_CODEC_I420;
1622
1623             p_pic->Y_PIXELS = p_pic->p_sys->ddsd.lpSurface;
1624             p_pic->p[Y_PLANE].i_lines = p_vout->output.i_height;
1625             p_pic->p[Y_PLANE].i_visible_lines = p_vout->output.i_height;
1626             p_pic->p[Y_PLANE].i_pitch = p_pic->p_sys->ddsd.lPitch;
1627             p_pic->p[Y_PLANE].i_pixel_pitch = 1;
1628             p_pic->p[Y_PLANE].i_visible_pitch = p_vout->output.i_width *
1629               p_pic->p[Y_PLANE].i_pixel_pitch;
1630
1631             p_pic->V_PIXELS =  p_pic->Y_PIXELS
1632               + p_pic->p[Y_PLANE].i_lines * p_pic->p[Y_PLANE].i_pitch;
1633             p_pic->p[V_PLANE].i_lines = p_vout->output.i_height / 2;
1634             p_pic->p[V_PLANE].i_visible_lines = p_vout->output.i_height / 2;
1635             p_pic->p[V_PLANE].i_pitch = p_pic->p[Y_PLANE].i_pitch / 2;
1636             p_pic->p[V_PLANE].i_pixel_pitch = 1;
1637             p_pic->p[V_PLANE].i_visible_pitch = p_vout->output.i_width / 2 *
1638               p_pic->p[V_PLANE].i_pixel_pitch;
1639
1640             p_pic->U_PIXELS = p_pic->V_PIXELS
1641               + p_pic->p[V_PLANE].i_lines * p_pic->p[V_PLANE].i_pitch;
1642             p_pic->p[U_PLANE].i_lines = p_vout->output.i_height / 2;
1643             p_pic->p[U_PLANE].i_visible_lines = p_vout->output.i_height / 2;
1644             p_pic->p[U_PLANE].i_pitch = p_pic->p[Y_PLANE].i_pitch / 2;
1645             p_pic->p[U_PLANE].i_pixel_pitch = 1;
1646             p_pic->p[U_PLANE].i_visible_pitch = p_vout->output.i_width / 2 *
1647               p_pic->p[U_PLANE].i_pixel_pitch;
1648
1649             p_pic->i_planes = 3;
1650             break;
1651
1652         case VLC_CODEC_I420:
1653
1654             p_pic->Y_PIXELS = p_pic->p_sys->ddsd.lpSurface;
1655             p_pic->p[Y_PLANE].i_lines = p_vout->output.i_height;
1656             p_pic->p[Y_PLANE].i_visible_lines = p_vout->output.i_height;
1657             p_pic->p[Y_PLANE].i_pitch = p_pic->p_sys->ddsd.lPitch;
1658             p_pic->p[Y_PLANE].i_pixel_pitch = 1;
1659             p_pic->p[Y_PLANE].i_visible_pitch = p_vout->output.i_width *
1660               p_pic->p[Y_PLANE].i_pixel_pitch;
1661
1662             p_pic->U_PIXELS = p_pic->Y_PIXELS
1663               + p_pic->p[Y_PLANE].i_lines * p_pic->p[Y_PLANE].i_pitch;
1664             p_pic->p[U_PLANE].i_lines = p_vout->output.i_height / 2;
1665             p_pic->p[U_PLANE].i_visible_lines = p_vout->output.i_height / 2;
1666             p_pic->p[U_PLANE].i_pitch = p_pic->p[Y_PLANE].i_pitch / 2;
1667             p_pic->p[U_PLANE].i_pixel_pitch = 1;
1668             p_pic->p[U_PLANE].i_visible_pitch = p_vout->output.i_width / 2 *
1669               p_pic->p[U_PLANE].i_pixel_pitch;
1670
1671             p_pic->V_PIXELS =  p_pic->U_PIXELS
1672               + p_pic->p[U_PLANE].i_lines * p_pic->p[U_PLANE].i_pitch;
1673             p_pic->p[V_PLANE].i_lines = p_vout->output.i_height / 2;
1674             p_pic->p[V_PLANE].i_visible_lines = p_vout->output.i_height / 2;
1675             p_pic->p[V_PLANE].i_pitch = p_pic->p[Y_PLANE].i_pitch / 2;
1676             p_pic->p[V_PLANE].i_pixel_pitch = 1;
1677             p_pic->p[V_PLANE].i_visible_pitch = p_vout->output.i_width / 2 *
1678               p_pic->p[V_PLANE].i_pixel_pitch;
1679
1680             p_pic->i_planes = 3;
1681             break;
1682
1683         case VLC_CODEC_UYVY:
1684         case VLC_CODEC_YUYV:
1685
1686             p_pic->p->p_pixels = p_pic->p_sys->ddsd.lpSurface;
1687             p_pic->p->i_lines = p_vout->output.i_height;
1688             p_pic->p->i_visible_lines = p_vout->output.i_height;
1689             p_pic->p->i_pitch = p_pic->p_sys->ddsd.lPitch;
1690             p_pic->p->i_pixel_pitch = 2;
1691             p_pic->p->i_visible_pitch = p_vout->output.i_width *
1692               p_pic->p->i_pixel_pitch;
1693
1694             p_pic->i_planes = 1;
1695             break;
1696
1697         default:
1698             /* Unknown chroma, tell the guy to get lost */
1699             msg_Err( p_vout, "never heard of chroma 0x%.8x (%4.4s)",
1700                      p_vout->output.i_chroma,
1701                      (char*)&p_vout->output.i_chroma );
1702             return VLC_EGENERIC;
1703     }
1704
1705     return VLC_SUCCESS;
1706 }
1707
1708 /*****************************************************************************
1709  * DirectXGetDDrawCaps: Probe the capabilities of the hardware
1710  *****************************************************************************
1711  * It is nice to know which features are supported by the hardware so we can
1712  * find ways to optimize our rendering.
1713  *****************************************************************************/
1714 static void DirectXGetDDrawCaps( vout_thread_t *p_vout )
1715 {
1716     DDCAPS ddcaps;
1717     HRESULT dxresult;
1718
1719     /* This is just an indication of whether or not we'll support overlay,
1720      * but with this test we don't know if we support YUV overlay */
1721     memset( &ddcaps, 0, sizeof( DDCAPS ));
1722     ddcaps.dwSize = sizeof(DDCAPS);
1723     dxresult = IDirectDraw2_GetCaps( p_vout->p_sys->p_ddobject,
1724                                      &ddcaps, NULL );
1725     if(dxresult != DD_OK )
1726     {
1727         msg_Warn( p_vout, "cannot get caps" );
1728     }
1729     else
1730     {
1731         bool bHasOverlay, bHasOverlayFourCC, bCanDeinterlace,
1732              bHasColorKey, bCanStretch, bCanBltFourcc,
1733              bAlignBoundarySrc, bAlignBoundaryDest,
1734              bAlignSizeSrc, bAlignSizeDest;
1735
1736         /* Determine if the hardware supports overlay surfaces */
1737         bHasOverlay = (ddcaps.dwCaps & DDCAPS_OVERLAY) ? 1 : 0;
1738         /* Determine if the hardware supports overlay surfaces */
1739         bHasOverlayFourCC = (ddcaps.dwCaps & DDCAPS_OVERLAYFOURCC) ? 1 : 0;
1740         /* Determine if the hardware supports overlay deinterlacing */
1741         bCanDeinterlace = (ddcaps.dwCaps & DDCAPS2_CANFLIPODDEVEN) ? 1 : 0;
1742         /* Determine if the hardware supports colorkeying */
1743         bHasColorKey = (ddcaps.dwCaps & DDCAPS_COLORKEY) ? 1 : 0;
1744         /* Determine if the hardware supports scaling of the overlay surface */
1745         bCanStretch = (ddcaps.dwCaps & DDCAPS_OVERLAYSTRETCH) ? 1 : 0;
1746         /* Determine if the hardware supports color conversion during a blit */
1747         bCanBltFourcc = (ddcaps.dwCaps & DDCAPS_BLTFOURCC) ? 1 : 0;
1748         /* Determine overlay source boundary alignment */
1749         bAlignBoundarySrc = (ddcaps.dwCaps & DDCAPS_ALIGNBOUNDARYSRC) ? 1 : 0;
1750         /* Determine overlay destination boundary alignment */
1751         bAlignBoundaryDest = (ddcaps.dwCaps & DDCAPS_ALIGNBOUNDARYDEST) ? 1:0;
1752         /* Determine overlay destination size alignment */
1753         bAlignSizeSrc = (ddcaps.dwCaps & DDCAPS_ALIGNSIZESRC) ? 1 : 0;
1754         /* Determine overlay destination size alignment */
1755         bAlignSizeDest = (ddcaps.dwCaps & DDCAPS_ALIGNSIZEDEST) ? 1 : 0;
1756
1757         msg_Dbg( p_vout, "DirectDraw Capabilities: overlay=%i yuvoverlay=%i "
1758                          "can_deinterlace_overlay=%i colorkey=%i stretch=%i "
1759                          "bltfourcc=%i",
1760                          bHasOverlay, bHasOverlayFourCC, bCanDeinterlace,
1761                          bHasColorKey, bCanStretch, bCanBltFourcc );
1762
1763         if( bAlignBoundarySrc || bAlignBoundaryDest ||
1764             bAlignSizeSrc || bAlignSizeDest )
1765         {
1766             if( bAlignBoundarySrc ) p_vout->p_sys->i_align_src_boundary =
1767                 ddcaps.dwAlignBoundarySrc;
1768             if( bAlignBoundaryDest ) p_vout->p_sys->i_align_dest_boundary =
1769                 ddcaps.dwAlignBoundaryDest;
1770             if( bAlignSizeDest ) p_vout->p_sys->i_align_src_size =
1771                 ddcaps.dwAlignSizeSrc;
1772             if( bAlignSizeDest ) p_vout->p_sys->i_align_dest_size =
1773                 ddcaps.dwAlignSizeDest;
1774
1775             msg_Dbg( p_vout, "align_boundary_src=%i,%i "
1776                      "align_boundary_dest=%i,%i "
1777                      "align_size_src=%i,%i align_size_dest=%i,%i",
1778                      bAlignBoundarySrc, p_vout->p_sys->i_align_src_boundary,
1779                      bAlignBoundaryDest, p_vout->p_sys->i_align_dest_boundary,
1780                      bAlignSizeSrc, p_vout->p_sys->i_align_src_size,
1781                      bAlignSizeDest, p_vout->p_sys->i_align_dest_size );
1782         }
1783
1784         /* Don't ask for troubles */
1785         if( !bCanBltFourcc ) p_vout->p_sys->b_hw_yuv = FALSE;
1786     }
1787 }
1788
1789 /*****************************************************************************
1790  * DirectXLockSurface: Lock surface and get picture data pointer
1791  *****************************************************************************
1792  * This function locks a surface and get the surface descriptor which amongst
1793  * other things has the pointer to the picture data.
1794  *****************************************************************************/
1795 static int DirectXLockSurface( vout_thread_t *p_vout, picture_t *p_pic )
1796 {
1797     HRESULT dxresult;
1798
1799     /* Lock the surface to get a valid pointer to the picture buffer */
1800     memset( &p_pic->p_sys->ddsd, 0, sizeof( DDSURFACEDESC ));
1801     p_pic->p_sys->ddsd.dwSize = sizeof(DDSURFACEDESC);
1802     dxresult = IDirectDrawSurface2_Lock( p_pic->p_sys->p_surface,
1803                                          NULL, &p_pic->p_sys->ddsd,
1804                                          DDLOCK_NOSYSLOCK | DDLOCK_WAIT,
1805                                          NULL );
1806     if( dxresult != DD_OK )
1807     {
1808         if( dxresult == DDERR_INVALIDPARAMS )
1809         {
1810             /* DirectX 3 doesn't support the DDLOCK_NOSYSLOCK flag, resulting
1811              * in an invalid params error */
1812             dxresult = IDirectDrawSurface2_Lock( p_pic->p_sys->p_surface, NULL,
1813                                              &p_pic->p_sys->ddsd,
1814                                              DDLOCK_WAIT, NULL);
1815         }
1816         if( dxresult == DDERR_SURFACELOST )
1817         {
1818             /* Your surface can be lost so be sure
1819              * to check this and restore it if needed */
1820
1821             /* When using overlays with back-buffers, we need to restore
1822              * the front buffer so the back-buffers get restored as well. */
1823             if( p_vout->p_sys->b_using_overlay  )
1824                 IDirectDrawSurface2_Restore( p_pic->p_sys->p_front_surface );
1825             else
1826                 IDirectDrawSurface2_Restore( p_pic->p_sys->p_surface );
1827
1828             dxresult = IDirectDrawSurface2_Lock( p_pic->p_sys->p_surface, NULL,
1829                                                  &p_pic->p_sys->ddsd,
1830                                                  DDLOCK_WAIT, NULL);
1831 #ifndef NDEBUG
1832             if( dxresult == DDERR_SURFACELOST )
1833                 msg_Dbg( p_vout, "DirectXLockSurface: DDERR_SURFACELOST" );
1834 #endif
1835         }
1836         if( dxresult != DD_OK )
1837         {
1838             return VLC_EGENERIC;
1839         }
1840     }
1841
1842     /* Now we have a pointer to the surface memory, we can update our picture
1843      * structure. */
1844     if( UpdatePictureStruct( p_vout, p_pic )
1845         != VLC_SUCCESS )
1846     {
1847         DirectXUnlockSurface( p_vout, p_pic );
1848         return VLC_EGENERIC;
1849     }
1850     else
1851         return VLC_SUCCESS;
1852 }
1853
1854 /*****************************************************************************
1855  * DirectXUnlockSurface: Unlock a surface locked by DirectXLockSurface().
1856  *****************************************************************************/
1857 static int DirectXUnlockSurface( vout_thread_t *p_vout, picture_t *p_pic )
1858 {
1859     VLC_UNUSED( p_vout );
1860
1861     /* Unlock the Surface */
1862     if( IDirectDrawSurface2_Unlock( p_pic->p_sys->p_surface, NULL ) == DD_OK )
1863         return VLC_SUCCESS;
1864     else
1865         return VLC_EGENERIC;
1866 }
1867
1868 /*****************************************************************************
1869  * DirectXFindColorkey: Finds out the 32bits RGB pixel value of the colorkey
1870  *****************************************************************************/
1871 static DWORD DirectXFindColorkey( vout_thread_t *p_vout, uint32_t *pi_color )
1872 {
1873     DDSURFACEDESC ddsd;
1874     HRESULT dxresult;
1875     COLORREF i_rgb = 0;
1876     uint32_t i_pixel_backup;
1877     HDC hdc;
1878
1879     ddsd.dwSize = sizeof(ddsd);
1880     dxresult = IDirectDrawSurface2_Lock( p_vout->p_sys->p_display, NULL,
1881                                          &ddsd, DDLOCK_WAIT, NULL );
1882     if( dxresult != DD_OK ) return 0;
1883
1884     i_pixel_backup = *(uint32_t *)ddsd.lpSurface;
1885
1886     switch( ddsd.ddpfPixelFormat.dwRGBBitCount )
1887     {
1888     case 4:
1889         *(uint8_t *)ddsd.lpSurface = *pi_color | (*pi_color << 4);
1890         break;
1891     case 8:
1892         *(uint8_t *)ddsd.lpSurface = *pi_color;
1893         break;
1894     case 15:
1895     case 16:
1896         *(uint16_t *)ddsd.lpSurface = *pi_color;
1897         break;
1898     case 24:
1899         /* Seems to be problematic so we'll just put black as the colorkey */
1900         *pi_color = 0;
1901     default:
1902         *(uint32_t *)ddsd.lpSurface = *pi_color;
1903         break;
1904     }
1905
1906     IDirectDrawSurface2_Unlock( p_vout->p_sys->p_display, NULL );
1907
1908     if( IDirectDrawSurface2_GetDC( p_vout->p_sys->p_display, &hdc ) == DD_OK )
1909     {
1910         i_rgb = GetPixel( hdc, 0, 0 );
1911         IDirectDrawSurface2_ReleaseDC( p_vout->p_sys->p_display, hdc );
1912     }
1913
1914     ddsd.dwSize = sizeof(ddsd);
1915     dxresult = IDirectDrawSurface2_Lock( p_vout->p_sys->p_display, NULL,
1916                                          &ddsd, DDLOCK_WAIT, NULL );
1917     if( dxresult != DD_OK ) return i_rgb;
1918
1919     *(uint32_t *)ddsd.lpSurface = i_pixel_backup;
1920
1921     IDirectDrawSurface2_Unlock( p_vout->p_sys->p_display, NULL );
1922
1923     return i_rgb;
1924 }
1925
1926 /*****************************************************************************
1927  * A few toolbox functions
1928  *****************************************************************************/
1929 void SwitchWallpaperMode( vout_thread_t *p_vout, bool b_on )
1930 {
1931     HWND hwnd;
1932
1933     if( p_vout->p_sys->b_wallpaper == b_on ) return; /* Nothing to do */
1934
1935     hwnd = FindWindow( _T("Progman"), NULL );
1936     if( hwnd ) hwnd = FindWindowEx( hwnd, NULL, _T("SHELLDLL_DefView"), NULL );
1937     if( hwnd ) hwnd = FindWindowEx( hwnd, NULL, _T("SysListView32"), NULL );
1938     if( !hwnd )
1939     {
1940         msg_Warn( p_vout, "couldn't find \"SysListView32\" window, "
1941                   "wallpaper mode not supported" );
1942         return;
1943     }
1944
1945     p_vout->p_sys->b_wallpaper = b_on;
1946
1947     msg_Dbg( p_vout, "wallpaper mode %s", b_on ? "enabled" : "disabled" );
1948
1949     if( p_vout->p_sys->b_wallpaper )
1950     {
1951         p_vout->p_sys->color_bkg = ListView_GetBkColor( hwnd );
1952         p_vout->p_sys->color_bkgtxt = ListView_GetTextBkColor( hwnd );
1953
1954         ListView_SetBkColor( hwnd, p_vout->p_sys->i_rgb_colorkey );
1955         ListView_SetTextBkColor( hwnd, p_vout->p_sys->i_rgb_colorkey );
1956     }
1957     else if( hwnd )
1958     {
1959         ListView_SetBkColor( hwnd, p_vout->p_sys->color_bkg );
1960         ListView_SetTextBkColor( hwnd, p_vout->p_sys->color_bkgtxt );
1961     }
1962
1963     /* Update desktop */
1964     InvalidateRect( hwnd, NULL, TRUE );
1965     UpdateWindow( hwnd );
1966 }
1967
1968 /*****************************************************************************
1969  * config variable callback
1970  *****************************************************************************/
1971 BOOL WINAPI DirectXEnumCallback2( GUID* p_guid, LPTSTR psz_desc,
1972                                   LPTSTR psz_drivername, VOID* p_context,
1973                                   HMONITOR hmon )
1974 {
1975     VLC_UNUSED( p_guid ); VLC_UNUSED( psz_desc ); VLC_UNUSED( hmon );
1976
1977     module_config_t *p_item = (module_config_t *)p_context;
1978
1979     p_item->ppsz_list =
1980         (char **)realloc( p_item->ppsz_list,
1981                           (p_item->i_list+2) * sizeof(char *) );
1982     p_item->ppsz_list_text =
1983         (char **)realloc( p_item->ppsz_list_text,
1984                           (p_item->i_list+2) * sizeof(char *) );
1985
1986     p_item->ppsz_list[p_item->i_list] = strdup( psz_drivername );
1987     p_item->ppsz_list_text[p_item->i_list] = NULL;
1988     p_item->i_list++;
1989     p_item->ppsz_list[p_item->i_list] = NULL;
1990     p_item->ppsz_list_text[p_item->i_list] = NULL;
1991
1992     return TRUE; /* Keep enumerating */
1993 }
1994
1995 static int FindDevicesCallback( vlc_object_t *p_this, char const *psz_name,
1996                                vlc_value_t newval, vlc_value_t oldval, void *d)
1997 {
1998     VLC_UNUSED( newval ); VLC_UNUSED( oldval ); VLC_UNUSED( d );
1999
2000     HRESULT (WINAPI *OurDirectDrawEnumerateEx)( LPDDENUMCALLBACKEXA, LPVOID,
2001                                                 DWORD );
2002     HINSTANCE hddraw_dll;
2003
2004     module_config_t *p_item;
2005     int i;
2006
2007     p_item = config_FindConfig( p_this, psz_name );
2008     if( !p_item ) return VLC_SUCCESS;
2009
2010     /* Clear-up the current list */
2011     if( p_item->i_list )
2012     {
2013         /* Keep the first entry */
2014         for( i = 1; i < p_item->i_list; i++ )
2015         {
2016             free( p_item->ppsz_list[i] );
2017             free( p_item->ppsz_list_text[i] );
2018         }
2019         /* TODO: Remove when no more needed */
2020         p_item->ppsz_list[i] = NULL;
2021         p_item->ppsz_list_text[i] = NULL;
2022     }
2023     p_item->i_list = 1;
2024
2025     /* Load direct draw DLL */
2026     hddraw_dll = LoadLibrary(_T("DDRAW.DLL"));
2027     if( hddraw_dll == NULL ) return VLC_SUCCESS;
2028
2029     OurDirectDrawEnumerateEx =
2030       (void *)GetProcAddress( hddraw_dll, _T("DirectDrawEnumerateExW") );
2031
2032     if( OurDirectDrawEnumerateEx )
2033     {
2034         /* Enumerate displays */
2035         OurDirectDrawEnumerateEx( DirectXEnumCallback2, p_item,
2036                                   DDENUM_ATTACHEDSECONDARYDEVICES );
2037     }
2038
2039     FreeLibrary( hddraw_dll );
2040
2041     /* Signal change to the interface */
2042     p_item->b_dirty = true;
2043
2044     return VLC_SUCCESS;
2045 }
2046
2047 static int WallpaperCallback( vlc_object_t *p_this, char const *psz_cmd,
2048                               vlc_value_t oldval, vlc_value_t newval,
2049                               void *p_data )
2050 {
2051     VLC_UNUSED( psz_cmd ); VLC_UNUSED( oldval ); VLC_UNUSED( p_data );
2052     vout_thread_t *p_vout = (vout_thread_t *)p_this;
2053
2054     if( (newval.b_bool && !p_vout->p_sys->b_wallpaper) ||
2055         (!newval.b_bool && p_vout->p_sys->b_wallpaper) )
2056     {
2057         playlist_t *p_playlist = pl_Hold( p_vout );
2058
2059         if( p_playlist )
2060         {
2061             /* Modify playlist as well because the vout might have to be
2062              * restarted */
2063             var_Create( p_playlist, "directx-wallpaper", VLC_VAR_BOOL );
2064             var_Set( p_playlist, "directx-wallpaper", newval );
2065             pl_Release( p_vout );
2066         }
2067
2068         p_vout->p_sys->i_changes |= DX_WALLPAPER_CHANGE;
2069     }
2070
2071     return VLC_SUCCESS;
2072 }
2073
2074 /*****************************************************************************
2075  * SetPalette: sets an 8 bpp palette
2076  *****************************************************************************/
2077 static void SetPalette( vout_thread_t *p_vout,
2078                         uint16_t *red, uint16_t *green, uint16_t *blue )
2079 {
2080     VLC_UNUSED( red ); VLC_UNUSED( green );VLC_UNUSED( blue );
2081     msg_Err( p_vout, "FIXME: SetPalette unimplemented" );
2082 }