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