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