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