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