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