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