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