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