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