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