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