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