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