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