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