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