lua: libs: input: Fix potential input thread leak
[vlc.git] / modules / video_output / msw / directx.c
1 /*****************************************************************************
2  * directx.c: Windows DirectDraw video output
3  *****************************************************************************
4  * Copyright (C) 2001-2009 the VideoLAN team
5  * $Id$
6  *
7  * Authors: Gildas Bazin <gbazin@videolan.org>
8  *
9  * This program is free software; you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License as published by
11  * the Free Software Foundation; either version 2 of the License, or
12  * (at your option) any later version.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  * GNU General Public License for more details.
18  *
19  * You should have received a copy of the GNU General Public License
20  * along with this program; if not, write to the Free Software
21  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
22  *****************************************************************************/
23
24 /*****************************************************************************
25  * Preamble:
26  *
27  * This plugin will use YUV overlay if supported, using overlay will result in
28  * the best video quality (hardware interpolation when rescaling the picture)
29  * and the fastest display as it requires less processing.
30  *
31  * If YUV overlay is not supported this plugin will use RGB offscreen video
32  * surfaces that will be blitted onto the primary surface (display) to
33  * effectively display the pictures. This fallback method also enables us to
34  * display video in window mode.
35  *
36  *****************************************************************************/
37 #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
46 #include <ddraw.h>
47 #include <commctrl.h>       /* ListView_(Get|Set)* */
48
49 #ifndef UNDER_CE
50 #   include <multimon.h>
51 #endif
52 #undef GetSystemMetrics
53
54 #ifndef MONITOR_DEFAULTTONEAREST
55 #   define MONITOR_DEFAULTTONEAREST 2
56 #endif
57
58 #include "vout.h"
59
60 /*****************************************************************************
61  * picture_sys_t: direct buffer method descriptor
62  *****************************************************************************
63  * This structure is part of the picture descriptor, it describes the
64  * DirectX specific properties of a direct buffer.
65  *****************************************************************************/
66 struct picture_sys_t
67 {
68     LPDIRECTDRAWSURFACE2 p_surface;
69     LPDIRECTDRAWSURFACE2 p_front_surface;
70     DDSURFACEDESC        ddsd;
71 };
72
73 /*****************************************************************************
74  * DirectDraw GUIDs.
75  * Defining them here allows us to get rid of the dxguid library during
76  * the linking stage.
77  *****************************************************************************/
78 #include <initguid.h>
79 #undef GUID_EXT
80 #define GUID_EXT
81 DEFINE_GUID( IID_IDirectDraw2, 0xB3A6F3E0,0x2B43,0x11CF,0xA2,0xDE,0x00,0xAA,0x00,0xB9,0x33,0x56 );
82 DEFINE_GUID( IID_IDirectDrawSurface2, 0x57805885,0x6eec,0x11cf,0x94,0x41,0xa8,0x23,0x03,0xc1,0x0e,0x27 );
83
84 /*****************************************************************************
85  * Local prototypes.
86  *****************************************************************************/
87 static int  OpenVideo  ( vlc_object_t * );
88 static void CloseVideo ( vlc_object_t * );
89
90 static int  Init      ( vout_thread_t * );
91 static void End       ( vout_thread_t * );
92 static int  Manage    ( vout_thread_t * );
93 static void Display   ( vout_thread_t *, picture_t * );
94 static void FirstDisplay( vout_thread_t *, picture_t * );
95 static void SetPalette( vout_thread_t *, uint16_t *, uint16_t *, uint16_t * );
96
97 static int  NewPictureVec  ( vout_thread_t *, picture_t * );
98 static void FreePictureVec ( vout_thread_t *, picture_t *, int );
99 static int  UpdatePictureStruct( vout_thread_t *, picture_t * );
100
101 static int  DirectXInitDDraw      ( vout_thread_t *p_vout );
102 static void DirectXCloseDDraw     ( vout_thread_t *p_vout );
103 static int  DirectXCreateDisplay  ( vout_thread_t *p_vout );
104 static void DirectXCloseDisplay   ( vout_thread_t *p_vout );
105 static int  DirectXCreateSurface  ( vout_thread_t *p_vout,
106                                     LPDIRECTDRAWSURFACE2 *, int, int, int );
107 static void DirectXCloseSurface   ( vout_thread_t *p_vout,
108                                     LPDIRECTDRAWSURFACE2 );
109 static int  DirectXCreateClipper  ( vout_thread_t *p_vout );
110 static void DirectXGetDDrawCaps   ( vout_thread_t *p_vout );
111 static int  DirectXLockSurface    ( vout_thread_t *p_vout, picture_t *p_pic );
112 static int  DirectXUnlockSurface  ( vout_thread_t *p_vout, picture_t *p_pic );
113
114 static DWORD DirectXFindColorkey( vout_thread_t *p_vout, uint32_t *i_color );
115
116 void SwitchWallpaperMode( vout_thread_t *, bool );
117
118 /* Object variables callbacks */
119 static int FindDevicesCallback( vlc_object_t *, char const *,
120                                 vlc_value_t, vlc_value_t, void * );
121 static int WallpaperCallback( vlc_object_t *, char const *,
122                               vlc_value_t, vlc_value_t, void * );
123
124 BOOL WINAPI DirectXEnumCallback( GUID* p_guid, LPTSTR psz_desc,
125                                  LPTSTR psz_drivername, VOID* p_context,
126                                  HMONITOR hmon );
127                                  
128 BOOL WINAPI DirectXEnumCallback2( GUID* p_guid, LPTSTR psz_desc,
129                                   LPTSTR psz_drivername, VOID* p_context,
130                                   HMONITOR hmon );
131                                   
132 /*****************************************************************************
133  * Module descriptor
134  *****************************************************************************/
135 #define HW_YUV_TEXT N_("Use hardware YUV->RGB conversions")
136 #define HW_YUV_LONGTEXT N_( \
137     "Try to use hardware acceleration for YUV->RGB conversions. " \
138     "This option doesn't have any effect when using overlays." )
139
140 #define SYSMEM_TEXT N_("Use video buffers in system memory")
141 #define SYSMEM_LONGTEXT N_( \
142     "Create video buffers in system memory instead of video memory. This " \
143     "isn't recommended as usually using video memory allows to benefit from " \
144     "more hardware acceleration (like rescaling or YUV->RGB conversions). " \
145     "This option doesn't have any effect when using overlays." )
146
147 #define TRIPLEBUF_TEXT N_("Use triple buffering for overlays")
148 #define TRIPLEBUF_LONGTEXT N_( \
149     "Try to use triple buffering when using YUV overlays. That results in " \
150     "much better video quality (no flickering)." )
151
152 #define DEVICE_TEXT N_("Name of desired display device")
153 #define DEVICE_LONGTEXT N_("In a multiple monitor configuration, you can " \
154     "specify the Windows device name of the display that you want the video " \
155     "window to open on. For example, \"\\\\.\\DISPLAY1\" or " \
156     "\"\\\\.\\DISPLAY2\"." )
157
158 #define WALLPAPER_TEXT N_("Enable wallpaper mode ")
159 #define WALLPAPER_LONGTEXT N_( \
160     "The wallpaper mode allows you to display the video as the desktop " \
161     "background. Note that this feature only works in overlay mode and " \
162     "the desktop must not already have a wallpaper." )
163
164 static const char *const ppsz_dev[] = { "" };
165 static const char *const ppsz_dev_text[] = { N_("Default") };
166
167 vlc_module_begin ()
168     set_shortname( "DirectX" )
169     set_category( CAT_VIDEO )
170     set_subcategory( SUBCAT_VIDEO_VOUT )
171     add_bool( "directx-hw-yuv", true, NULL, HW_YUV_TEXT, HW_YUV_LONGTEXT,
172               true )
173     add_bool( "directx-use-sysmem", false, NULL, SYSMEM_TEXT, SYSMEM_LONGTEXT,
174               true )
175     add_bool( "directx-3buffering", true, NULL, TRIPLEBUF_TEXT,
176               TRIPLEBUF_LONGTEXT, true )
177
178     add_string( "directx-device", "", NULL, DEVICE_TEXT, DEVICE_LONGTEXT,
179                 true )
180         change_string_list( ppsz_dev, ppsz_dev_text, FindDevicesCallback )
181         change_action_add( FindDevicesCallback, N_("Refresh list") )
182
183     add_bool( "directx-wallpaper", false, NULL, WALLPAPER_TEXT, WALLPAPER_LONGTEXT,
184               true )
185
186     set_description( N_("DirectX (DirectDraw) video output") )
187     set_capability( "video output", 100 )
188     add_shortcut( "directx" )
189     set_callbacks( OpenVideo, CloseVideo )
190
191     /* FIXME: Hack to avoid unregistering our window class */
192     linked_with_a_crap_library_which_uses_atexit ()
193 vlc_module_end ()
194
195 #if 0 /* FIXME */
196     /* check if we registered a window class because we need to
197      * unregister it */
198     WNDCLASS wndclass;
199     if( GetClassInfo( GetModuleHandle(NULL), "VLC DirectX", &wndclass ) )
200         UnregisterClass( "VLC DirectX", GetModuleHandle(NULL) );
201 #endif
202
203 /*****************************************************************************
204  * OpenVideo: allocate DirectX video thread output method
205  *****************************************************************************
206  * This function allocates and initialize the DirectX vout method.
207  *****************************************************************************/
208 static int OpenVideo( vlc_object_t *p_this )
209 {
210     vout_thread_t * p_vout = (vout_thread_t *)p_this;
211     vlc_value_t val;
212     HMODULE huser32;
213
214     /* Allocate structure */
215     p_vout->p_sys = calloc( 1, sizeof( vout_sys_t ) );
216     if( p_vout->p_sys == NULL )
217         return VLC_ENOMEM;
218     vlc_mutex_init( &p_vout->p_sys->lock );
219
220     /* Initialisations */
221     p_vout->pf_init = Init;
222     p_vout->pf_end = End;
223     p_vout->pf_manage = Manage;
224     p_vout->pf_render = NULL;
225     p_vout->pf_display = FirstDisplay;
226     p_vout->pf_control = Control;
227
228     if( CommonInit( p_vout ) )
229         goto error;
230
231     /* */
232     p_vout->p_sys->p_ddobject = NULL;
233     p_vout->p_sys->p_display = NULL;
234     p_vout->p_sys->p_current_surface = NULL;
235     p_vout->p_sys->p_clipper = NULL;
236     p_vout->p_sys->b_wallpaper = 0;
237
238     /* Multimonitor stuff */
239     p_vout->p_sys->hmonitor = NULL;
240     p_vout->p_sys->p_display_driver = NULL;
241     p_vout->p_sys->MonitorFromWindow = NULL;
242     p_vout->p_sys->GetMonitorInfo = NULL;
243     if( (huser32 = GetModuleHandle( _T("USER32") ) ) )
244     {
245         p_vout->p_sys->MonitorFromWindow = (HMONITOR (WINAPI *)( HWND, DWORD ))
246             GetProcAddress( huser32, _T("MonitorFromWindow") );
247         p_vout->p_sys->GetMonitorInfo =
248             GetProcAddress( huser32, _T("GetMonitorInfoW") );
249     }
250
251     var_Create( p_vout, "overlay", VLC_VAR_BOOL | VLC_VAR_DOINHERIT );
252     var_Create( p_vout, "directx-use-sysmem", VLC_VAR_BOOL|VLC_VAR_DOINHERIT );
253     var_Create( p_vout, "directx-hw-yuv", VLC_VAR_BOOL | VLC_VAR_DOINHERIT );
254     var_Create( p_vout, "directx-3buffering", VLC_VAR_BOOL|VLC_VAR_DOINHERIT );
255     var_Create( p_vout, "directx-device", VLC_VAR_STRING | VLC_VAR_DOINHERIT );
256
257     /* Initialise DirectDraw */
258     if( DirectXInitDDraw( p_vout ) )
259     {
260         msg_Err( p_vout, "cannot initialize DirectX DirectDraw" );
261         goto error;
262     }
263
264     /* Create the directx display */
265     if( DirectXCreateDisplay( p_vout ) )
266     {
267         msg_Err( p_vout, "cannot initialize DirectX DirectDraw" );
268         goto error;
269     }
270
271     /* Variable to indicate if the window should be on top of others */
272     /* Trigger a callback right now */
273     var_Create( p_vout, "directx-wallpaper", VLC_VAR_BOOL|VLC_VAR_DOINHERIT );
274     val.psz_string = _("Wallpaper");
275     var_Change( p_vout, "directx-wallpaper", VLC_VAR_SETTEXT, &val, NULL );
276     var_AddCallback( p_vout, "directx-wallpaper", WallpaperCallback, NULL );
277     var_TriggerCallback( p_vout, "directx-wallpaper" );
278
279     return VLC_SUCCESS;
280
281  error:
282     CloseVideo( VLC_OBJECT(p_vout) );
283     return VLC_EGENERIC;
284 }
285
286 /*****************************************************************************
287  * Init: initialize DirectX video thread output method
288  *****************************************************************************
289  * This function create the directx surfaces needed by the output thread.
290  * It is called at the beginning of the thread.
291  *****************************************************************************/
292 static int Init( vout_thread_t *p_vout )
293 {
294     int i_chroma_backup;
295
296     /* Get a few default parameters */
297     p_vout->p_sys->b_using_overlay = var_GetBool( p_vout, "overlay" );
298     p_vout->p_sys->b_use_sysmem = var_GetBool( p_vout, "directx-use-sysmem" );
299     p_vout->p_sys->b_hw_yuv = var_GetBool( p_vout, "directx-hw-yuv" );
300     p_vout->p_sys->b_3buf_overlay = var_GetBool( p_vout, "directx-3buffering" );
301
302     /* Initialise DirectDraw if not already done.
303      * We do this here because on multi-monitor systems we may have to
304      * re-create the directdraw surfaces. */
305     if( !p_vout->p_sys->p_ddobject &&
306         DirectXInitDDraw( p_vout ) != VLC_SUCCESS )
307     {
308         msg_Err( p_vout, "cannot initialize DirectDraw" );
309         return VLC_EGENERIC;
310     }
311
312     /* Create the directx display */
313     if( !p_vout->p_sys->p_display &&
314         DirectXCreateDisplay( p_vout ) != VLC_SUCCESS )
315     {
316         msg_Err( p_vout, "cannot initialize DirectDraw" );
317         return VLC_EGENERIC;
318     }
319
320     /* Initialize the output structure.
321      * Since DirectDraw can do rescaling for us, stick to the default
322      * coordinates and aspect. */
323     p_vout->output.i_width  = p_vout->render.i_width;
324     p_vout->output.i_height = p_vout->render.i_height;
325     p_vout->output.i_aspect = p_vout->render.i_aspect;
326     p_vout->fmt_out = p_vout->fmt_in;
327     UpdateRects( p_vout, true );
328
329 #define MAX_DIRECTBUFFERS 1
330     /* Right now we use only 1 directbuffer because we don't want the
331      * video decoder to decode directly into direct buffers as they are
332      * created into video memory and video memory is _really_ slow */
333
334     /* Choose the chroma we will try first. */
335     switch( p_vout->render.i_chroma )
336     {
337         case VLC_CODEC_YUYV:
338             p_vout->output.i_chroma = VLC_CODEC_YUYV;
339             break;
340         case VLC_CODEC_UYVY:
341             p_vout->output.i_chroma = VLC_CODEC_UYVY;
342             break;
343         case VLC_CODEC_YVYU:
344             p_vout->output.i_chroma = VLC_CODEC_YVYU;
345             break;
346         case VLC_CODEC_I420:
347             p_vout->output.i_chroma = VLC_CODEC_I420;
348             break;
349         default:
350             msg_Dbg( p_vout, "use default chroma YV12 for render " \
351                              "chroma (%4.4s)",
352                              (char *)&p_vout->render.i_chroma);
353             p_vout->output.i_chroma = VLC_CODEC_YV12;
354             break;
355     }
356
357     NewPictureVec( p_vout, p_vout->p_picture );
358
359     i_chroma_backup = p_vout->output.i_chroma;
360
361     if( !I_OUTPUTPICTURES )
362     {
363         /* hmmm, it didn't work! Let's try commonly supported chromas */
364         if( p_vout->output.i_chroma != VLC_CODEC_I420 )
365         {
366             p_vout->output.i_chroma = VLC_CODEC_YV12;
367             NewPictureVec( p_vout, p_vout->p_picture );
368         }
369         if( !I_OUTPUTPICTURES )
370         {
371             /* hmmm, it still didn't work! Let's try another one */
372             p_vout->output.i_chroma = VLC_CODEC_YUYV;
373             NewPictureVec( p_vout, p_vout->p_picture );
374         }
375     }
376
377     if( !I_OUTPUTPICTURES )
378     {
379         /* If it still didn't work then don't try to use an overlay */
380         p_vout->output.i_chroma = i_chroma_backup;
381         p_vout->p_sys->b_using_overlay = false;
382         msg_Warn( p_vout, "Could not initialize directx overlay" ) ;
383         NewPictureVec( p_vout, p_vout->p_picture );
384     }
385
386     p_vout->fmt_out.i_chroma = p_vout->output.i_chroma;
387
388     /* Change the window title bar text */
389     const char *psz_fallback;
390     if( p_vout->p_sys->b_using_overlay )
391         psz_fallback = VOUT_TITLE " (hardware YUV overlay DirectX output)";
392     else if( p_vout->p_sys->b_hw_yuv )
393         psz_fallback = VOUT_TITLE " (hardware YUV DirectX output)";
394     else
395         psz_fallback = VOUT_TITLE " (software RGB DirectX output)";
396     EventThreadUpdateTitle( p_vout->p_sys->p_event, psz_fallback );
397     EventThreadUseOverlay( p_vout->p_sys->p_event, p_vout->p_sys->b_using_overlay );
398
399     return VLC_SUCCESS;
400 }
401
402 /*****************************************************************************
403  * End: terminate Sys video thread output method
404  *****************************************************************************
405  * Terminate an output method created by Create.
406  * It is called at the end of the thread.
407  *****************************************************************************/
408 static void End( vout_thread_t *p_vout )
409 {
410     FreePictureVec( p_vout, p_vout->p_picture, I_OUTPUTPICTURES );
411
412     DirectXCloseDisplay( p_vout );
413     DirectXCloseDDraw( p_vout );
414
415     return;
416 }
417
418 /*****************************************************************************
419  * CloseVideo: destroy Sys video thread output method
420  *****************************************************************************
421  * Terminate an output method created by Create
422  *****************************************************************************/
423 static void CloseVideo( vlc_object_t *p_this )
424 {
425     vout_thread_t * p_vout = (vout_thread_t *)p_this;
426
427     /* Make sure the wallpaper is restored */
428     var_DelCallback( p_vout, "directx-wallpaper", WallpaperCallback, NULL );
429     SwitchWallpaperMode( p_vout, false );
430
431     CommonClean( p_vout );
432
433     vlc_mutex_destroy( &p_vout->p_sys->lock );
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     char *psz_device;
601
602     msg_Dbg( p_vout, "DirectXEnumCallback: %s, %s", psz_desc, psz_drivername );
603
604     if( hmon )
605     {
606         psz_device = var_GetString( p_vout, "directx-device" );
607
608         if( ( !psz_device || !*psz_device ) &&
609             hmon == p_vout->p_sys->hmonitor )
610         {
611             free( psz_device );
612         }
613         else if( strcmp( psz_drivername, psz_device ) == 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( psz_device );
638         }
639         else
640         {
641             free( psz_device );
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         char *psz_device;
693
694         psz_device = var_GetString( p_vout, "directx-device" );
695         if( psz_device )
696         {
697             msg_Dbg( p_vout, "directx-device: %s", psz_device );
698             free( psz_device );
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                 free( pi_codes );
1274             }
1275
1276             if( b_result )
1277                 i_ret = DirectXCreateSurface( p_vout, &p_surface,
1278                                               p_vout->output.i_chroma,
1279                                               0 /* no overlay */,
1280                                               0 /* no back buffers */ );
1281             else
1282                 p_vout->p_sys->b_hw_yuv = false;
1283         }
1284
1285         if( i_ret || !p_vout->p_sys->b_hw_yuv )
1286         {
1287             /* Our last choice is to use a plain RGB surface */
1288             DDPIXELFORMAT ddpfPixelFormat;
1289
1290             ddpfPixelFormat.dwSize = sizeof(DDPIXELFORMAT);
1291             IDirectDrawSurface2_GetPixelFormat( p_vout->p_sys->p_display,
1292                                                 &ddpfPixelFormat );
1293
1294             if( ddpfPixelFormat.dwFlags & DDPF_RGB )
1295             {
1296                 switch( ddpfPixelFormat.dwRGBBitCount )
1297                 {
1298                 case 8:
1299                     p_vout->output.i_chroma = VLC_CODEC_RGB8;
1300                     p_vout->output.pf_setpalette = SetPalette;
1301                     break;
1302                 case 15:
1303                     p_vout->output.i_chroma = VLC_CODEC_RGB15;
1304                     break;
1305                 case 16:
1306                     p_vout->output.i_chroma = VLC_CODEC_RGB16;
1307                     break;
1308                 case 24:
1309                     p_vout->output.i_chroma = VLC_CODEC_RGB24;
1310                     break;
1311                 case 32:
1312                     p_vout->output.i_chroma = VLC_CODEC_RGB32;
1313                     break;
1314                 default:
1315                     msg_Err( p_vout, "unknown screen depth" );
1316                     return VLC_EGENERIC;
1317                 }
1318                 p_vout->output.i_rmask = ddpfPixelFormat.dwRBitMask;
1319                 p_vout->output.i_gmask = ddpfPixelFormat.dwGBitMask;
1320                 p_vout->output.i_bmask = ddpfPixelFormat.dwBBitMask;
1321             }
1322
1323             p_vout->p_sys->b_hw_yuv = 0;
1324
1325             i_ret = DirectXCreateSurface( p_vout, &p_surface,
1326                                           p_vout->output.i_chroma,
1327                                           0 /* no overlay */,
1328                                           0 /* no back buffers */ );
1329
1330             if( i_ret && !p_vout->p_sys->b_use_sysmem )
1331             {
1332                 /* Give it a last try with b_use_sysmem enabled */
1333                 p_vout->p_sys->b_use_sysmem = 1;
1334
1335                 i_ret = DirectXCreateSurface( p_vout, &p_surface,
1336                                               p_vout->output.i_chroma,
1337                                               0 /* no overlay */,
1338                                               0 /* no back buffers */ );
1339             }
1340         }
1341
1342         if( i_ret == VLC_SUCCESS )
1343         {
1344             /* Allocate internal structure */
1345             p_pic[0].p_sys = malloc( sizeof( picture_sys_t ) );
1346             if( p_pic[0].p_sys == NULL )
1347             {
1348                 DirectXCloseSurface( p_vout, p_surface );
1349                 return VLC_ENOMEM;
1350             }
1351
1352             p_pic[0].p_sys->p_surface = p_pic[0].p_sys->p_front_surface
1353                 = p_surface;
1354
1355             I_OUTPUTPICTURES = 1;
1356
1357             msg_Dbg( p_vout, "created plain surface of chroma:%.4s",
1358                      (char *)&p_vout->output.i_chroma );
1359         }
1360     }
1361
1362
1363     /* Now that we've got all our direct-buffers, we can finish filling in the
1364      * picture_t structures */
1365     for( i = 0; i < I_OUTPUTPICTURES; i++ )
1366     {
1367         p_pic[i].i_status = DESTROYED_PICTURE;
1368         p_pic[i].i_type   = DIRECT_PICTURE;
1369         p_pic[i].b_slow   = true;
1370         p_pic[i].pf_lock  = DirectXLockSurface;
1371         p_pic[i].pf_unlock = DirectXUnlockSurface;
1372         PP_OUTPUTPICTURE[i] = &p_pic[i];
1373
1374         if( DirectXLockSurface( p_vout, &p_pic[i] ) != VLC_SUCCESS )
1375         {
1376             /* AAARRGG */
1377             FreePictureVec( p_vout, p_pic, I_OUTPUTPICTURES );
1378             I_OUTPUTPICTURES = 0;
1379             msg_Err( p_vout, "cannot lock surface" );
1380             return VLC_EGENERIC;
1381         }
1382         DirectXUnlockSurface( p_vout, &p_pic[i] );
1383     }
1384
1385     msg_Dbg( p_vout, "End NewPictureVec (%s)",
1386              I_OUTPUTPICTURES ? "succeeded" : "failed" );
1387
1388     return VLC_SUCCESS;
1389 }
1390
1391 /*****************************************************************************
1392  * FreePicture: destroy a picture vector allocated with NewPictureVec
1393  *****************************************************************************
1394  *
1395  *****************************************************************************/
1396 static void FreePictureVec( vout_thread_t *p_vout, picture_t *p_pic,
1397                             int i_num_pics )
1398 {
1399     int i;
1400
1401     vlc_mutex_lock( &p_vout->p_sys->lock );
1402     p_vout->p_sys->p_current_surface = 0;
1403     vlc_mutex_unlock( &p_vout->p_sys->lock );
1404
1405     for( i = 0; i < i_num_pics; i++ )
1406     {
1407         DirectXCloseSurface( p_vout, p_pic[i].p_sys->p_front_surface );
1408
1409         for( i = 0; i < i_num_pics; i++ )
1410         {
1411             free( p_pic[i].p_sys );
1412         }
1413     }
1414 }
1415
1416 /*****************************************************************************
1417  * UpdatePictureStruct: updates the internal data in the picture_t structure
1418  *****************************************************************************
1419  * This will setup stuff for use by the video_output thread
1420  *****************************************************************************/
1421 static int UpdatePictureStruct( vout_thread_t *p_vout, picture_t *p_pic )
1422 {
1423     switch( p_vout->output.i_chroma )
1424     {
1425         case VLC_CODEC_RGB8:
1426         case VLC_CODEC_RGB15:
1427         case VLC_CODEC_RGB16:
1428         case VLC_CODEC_RGB24:
1429         case VLC_CODEC_RGB32:
1430             p_pic->p->p_pixels = p_pic->p_sys->ddsd.lpSurface;
1431             p_pic->p->i_lines = p_vout->output.i_height;
1432             p_pic->p->i_visible_lines = p_vout->output.i_height;
1433             p_pic->p->i_pitch = p_pic->p_sys->ddsd.lPitch;
1434             switch( p_vout->output.i_chroma )
1435             {
1436                 case VLC_CODEC_RGB8:
1437                     p_pic->p->i_pixel_pitch = 1;
1438                     break;
1439                 case VLC_CODEC_RGB15:
1440                 case VLC_CODEC_RGB16:
1441                     p_pic->p->i_pixel_pitch = 2;
1442                     break;
1443                 case VLC_CODEC_RGB24:
1444                     p_pic->p->i_pixel_pitch = 3;
1445                     break;
1446                 case VLC_CODEC_RGB32:
1447                     p_pic->p->i_pixel_pitch = 4;
1448                     break;
1449                 default:
1450                     return VLC_EGENERIC;
1451             }
1452             p_pic->p->i_visible_pitch = p_vout->output.i_width *
1453               p_pic->p->i_pixel_pitch;
1454             p_pic->i_planes = 1;
1455             break;
1456
1457         case VLC_CODEC_YV12:
1458
1459             /* U and V inverted compared to I420
1460              * Fixme: this should be handled by the vout core */
1461             /* could this be right? */
1462             p_vout->output.i_chroma = VLC_CODEC_I420;
1463
1464             p_pic->Y_PIXELS = p_pic->p_sys->ddsd.lpSurface;
1465             p_pic->p[Y_PLANE].i_lines = p_vout->output.i_height;
1466             p_pic->p[Y_PLANE].i_visible_lines = p_vout->output.i_height;
1467             p_pic->p[Y_PLANE].i_pitch = p_pic->p_sys->ddsd.lPitch;
1468             p_pic->p[Y_PLANE].i_pixel_pitch = 1;
1469             p_pic->p[Y_PLANE].i_visible_pitch = p_vout->output.i_width *
1470               p_pic->p[Y_PLANE].i_pixel_pitch;
1471
1472             p_pic->V_PIXELS =  p_pic->Y_PIXELS
1473               + p_pic->p[Y_PLANE].i_lines * p_pic->p[Y_PLANE].i_pitch;
1474             p_pic->p[V_PLANE].i_lines = p_vout->output.i_height / 2;
1475             p_pic->p[V_PLANE].i_visible_lines = p_vout->output.i_height / 2;
1476             p_pic->p[V_PLANE].i_pitch = p_pic->p[Y_PLANE].i_pitch / 2;
1477             p_pic->p[V_PLANE].i_pixel_pitch = 1;
1478             p_pic->p[V_PLANE].i_visible_pitch = p_vout->output.i_width / 2 *
1479               p_pic->p[V_PLANE].i_pixel_pitch;
1480
1481             p_pic->U_PIXELS = p_pic->V_PIXELS
1482               + p_pic->p[V_PLANE].i_lines * p_pic->p[V_PLANE].i_pitch;
1483             p_pic->p[U_PLANE].i_lines = p_vout->output.i_height / 2;
1484             p_pic->p[U_PLANE].i_visible_lines = p_vout->output.i_height / 2;
1485             p_pic->p[U_PLANE].i_pitch = p_pic->p[Y_PLANE].i_pitch / 2;
1486             p_pic->p[U_PLANE].i_pixel_pitch = 1;
1487             p_pic->p[U_PLANE].i_visible_pitch = p_vout->output.i_width / 2 *
1488               p_pic->p[U_PLANE].i_pixel_pitch;
1489
1490             p_pic->i_planes = 3;
1491             break;
1492
1493         case VLC_CODEC_I420:
1494
1495             p_pic->Y_PIXELS = p_pic->p_sys->ddsd.lpSurface;
1496             p_pic->p[Y_PLANE].i_lines = p_vout->output.i_height;
1497             p_pic->p[Y_PLANE].i_visible_lines = p_vout->output.i_height;
1498             p_pic->p[Y_PLANE].i_pitch = p_pic->p_sys->ddsd.lPitch;
1499             p_pic->p[Y_PLANE].i_pixel_pitch = 1;
1500             p_pic->p[Y_PLANE].i_visible_pitch = p_vout->output.i_width *
1501               p_pic->p[Y_PLANE].i_pixel_pitch;
1502
1503             p_pic->U_PIXELS = p_pic->Y_PIXELS
1504               + p_pic->p[Y_PLANE].i_lines * p_pic->p[Y_PLANE].i_pitch;
1505             p_pic->p[U_PLANE].i_lines = p_vout->output.i_height / 2;
1506             p_pic->p[U_PLANE].i_visible_lines = p_vout->output.i_height / 2;
1507             p_pic->p[U_PLANE].i_pitch = p_pic->p[Y_PLANE].i_pitch / 2;
1508             p_pic->p[U_PLANE].i_pixel_pitch = 1;
1509             p_pic->p[U_PLANE].i_visible_pitch = p_vout->output.i_width / 2 *
1510               p_pic->p[U_PLANE].i_pixel_pitch;
1511
1512             p_pic->V_PIXELS =  p_pic->U_PIXELS
1513               + p_pic->p[U_PLANE].i_lines * p_pic->p[U_PLANE].i_pitch;
1514             p_pic->p[V_PLANE].i_lines = p_vout->output.i_height / 2;
1515             p_pic->p[V_PLANE].i_visible_lines = p_vout->output.i_height / 2;
1516             p_pic->p[V_PLANE].i_pitch = p_pic->p[Y_PLANE].i_pitch / 2;
1517             p_pic->p[V_PLANE].i_pixel_pitch = 1;
1518             p_pic->p[V_PLANE].i_visible_pitch = p_vout->output.i_width / 2 *
1519               p_pic->p[V_PLANE].i_pixel_pitch;
1520
1521             p_pic->i_planes = 3;
1522             break;
1523
1524         case VLC_CODEC_UYVY:
1525         case VLC_CODEC_YUYV:
1526
1527             p_pic->p->p_pixels = p_pic->p_sys->ddsd.lpSurface;
1528             p_pic->p->i_lines = p_vout->output.i_height;
1529             p_pic->p->i_visible_lines = p_vout->output.i_height;
1530             p_pic->p->i_pitch = p_pic->p_sys->ddsd.lPitch;
1531             p_pic->p->i_pixel_pitch = 2;
1532             p_pic->p->i_visible_pitch = p_vout->output.i_width *
1533               p_pic->p->i_pixel_pitch;
1534
1535             p_pic->i_planes = 1;
1536             break;
1537
1538         default:
1539             /* Unknown chroma, tell the guy to get lost */
1540             msg_Err( p_vout, "never heard of chroma 0x%.8x (%4.4s)",
1541                      p_vout->output.i_chroma,
1542                      (char*)&p_vout->output.i_chroma );
1543             return VLC_EGENERIC;
1544     }
1545
1546     return VLC_SUCCESS;
1547 }
1548
1549 /*****************************************************************************
1550  * DirectXGetDDrawCaps: Probe the capabilities of the hardware
1551  *****************************************************************************
1552  * It is nice to know which features are supported by the hardware so we can
1553  * find ways to optimize our rendering.
1554  *****************************************************************************/
1555 static void DirectXGetDDrawCaps( vout_thread_t *p_vout )
1556 {
1557     DDCAPS ddcaps;
1558     HRESULT dxresult;
1559
1560     /* This is just an indication of whether or not we'll support overlay,
1561      * but with this test we don't know if we support YUV overlay */
1562     memset( &ddcaps, 0, sizeof( DDCAPS ));
1563     ddcaps.dwSize = sizeof(DDCAPS);
1564     dxresult = IDirectDraw2_GetCaps( p_vout->p_sys->p_ddobject,
1565                                      &ddcaps, NULL );
1566     if(dxresult != DD_OK )
1567     {
1568         msg_Warn( p_vout, "cannot get caps" );
1569     }
1570     else
1571     {
1572         bool bHasOverlay, bHasOverlayFourCC, bCanDeinterlace,
1573              bHasColorKey, bCanStretch, bCanBltFourcc,
1574              bAlignBoundarySrc, bAlignBoundaryDest,
1575              bAlignSizeSrc, bAlignSizeDest;
1576
1577         /* Determine if the hardware supports overlay surfaces */
1578         bHasOverlay = (ddcaps.dwCaps & DDCAPS_OVERLAY) ? 1 : 0;
1579         /* Determine if the hardware supports overlay surfaces */
1580         bHasOverlayFourCC = (ddcaps.dwCaps & DDCAPS_OVERLAYFOURCC) ? 1 : 0;
1581         /* Determine if the hardware supports overlay deinterlacing */
1582         bCanDeinterlace = (ddcaps.dwCaps & DDCAPS2_CANFLIPODDEVEN) ? 1 : 0;
1583         /* Determine if the hardware supports colorkeying */
1584         bHasColorKey = (ddcaps.dwCaps & DDCAPS_COLORKEY) ? 1 : 0;
1585         /* Determine if the hardware supports scaling of the overlay surface */
1586         bCanStretch = (ddcaps.dwCaps & DDCAPS_OVERLAYSTRETCH) ? 1 : 0;
1587         /* Determine if the hardware supports color conversion during a blit */
1588         bCanBltFourcc = (ddcaps.dwCaps & DDCAPS_BLTFOURCC) ? 1 : 0;
1589         /* Determine overlay source boundary alignment */
1590         bAlignBoundarySrc = (ddcaps.dwCaps & DDCAPS_ALIGNBOUNDARYSRC) ? 1 : 0;
1591         /* Determine overlay destination boundary alignment */
1592         bAlignBoundaryDest = (ddcaps.dwCaps & DDCAPS_ALIGNBOUNDARYDEST) ? 1:0;
1593         /* Determine overlay destination size alignment */
1594         bAlignSizeSrc = (ddcaps.dwCaps & DDCAPS_ALIGNSIZESRC) ? 1 : 0;
1595         /* Determine overlay destination size alignment */
1596         bAlignSizeDest = (ddcaps.dwCaps & DDCAPS_ALIGNSIZEDEST) ? 1 : 0;
1597
1598         msg_Dbg( p_vout, "DirectDraw Capabilities: overlay=%i yuvoverlay=%i "
1599                          "can_deinterlace_overlay=%i colorkey=%i stretch=%i "
1600                          "bltfourcc=%i",
1601                          bHasOverlay, bHasOverlayFourCC, bCanDeinterlace,
1602                          bHasColorKey, bCanStretch, bCanBltFourcc );
1603
1604         if( bAlignBoundarySrc || bAlignBoundaryDest ||
1605             bAlignSizeSrc || bAlignSizeDest )
1606         {
1607             if( bAlignBoundarySrc ) p_vout->p_sys->i_align_src_boundary =
1608                 ddcaps.dwAlignBoundarySrc;
1609             if( bAlignBoundaryDest ) p_vout->p_sys->i_align_dest_boundary =
1610                 ddcaps.dwAlignBoundaryDest;
1611             if( bAlignSizeDest ) p_vout->p_sys->i_align_src_size =
1612                 ddcaps.dwAlignSizeSrc;
1613             if( bAlignSizeDest ) p_vout->p_sys->i_align_dest_size =
1614                 ddcaps.dwAlignSizeDest;
1615
1616             msg_Dbg( p_vout, "align_boundary_src=%i,%i "
1617                      "align_boundary_dest=%i,%i "
1618                      "align_size_src=%i,%i align_size_dest=%i,%i",
1619                      bAlignBoundarySrc, p_vout->p_sys->i_align_src_boundary,
1620                      bAlignBoundaryDest, p_vout->p_sys->i_align_dest_boundary,
1621                      bAlignSizeSrc, p_vout->p_sys->i_align_src_size,
1622                      bAlignSizeDest, p_vout->p_sys->i_align_dest_size );
1623         }
1624
1625         /* Don't ask for troubles */
1626         if( !bCanBltFourcc ) p_vout->p_sys->b_hw_yuv = FALSE;
1627     }
1628 }
1629
1630 /*****************************************************************************
1631  * DirectXLockSurface: Lock surface and get picture data pointer
1632  *****************************************************************************
1633  * This function locks a surface and get the surface descriptor which amongst
1634  * other things has the pointer to the picture data.
1635  *****************************************************************************/
1636 static int DirectXLockSurface( vout_thread_t *p_vout, picture_t *p_pic )
1637 {
1638     HRESULT dxresult;
1639
1640     /* Lock the surface to get a valid pointer to the picture buffer */
1641     memset( &p_pic->p_sys->ddsd, 0, sizeof( DDSURFACEDESC ));
1642     p_pic->p_sys->ddsd.dwSize = sizeof(DDSURFACEDESC);
1643     dxresult = IDirectDrawSurface2_Lock( p_pic->p_sys->p_surface,
1644                                          NULL, &p_pic->p_sys->ddsd,
1645                                          DDLOCK_NOSYSLOCK | DDLOCK_WAIT,
1646                                          NULL );
1647     if( dxresult != DD_OK )
1648     {
1649         if( dxresult == DDERR_INVALIDPARAMS )
1650         {
1651             /* DirectX 3 doesn't support the DDLOCK_NOSYSLOCK flag, resulting
1652              * in an invalid params error */
1653             dxresult = IDirectDrawSurface2_Lock( p_pic->p_sys->p_surface, NULL,
1654                                              &p_pic->p_sys->ddsd,
1655                                              DDLOCK_WAIT, NULL);
1656         }
1657         if( dxresult == DDERR_SURFACELOST )
1658         {
1659             /* Your surface can be lost so be sure
1660              * to check this and restore it if needed */
1661
1662             /* When using overlays with back-buffers, we need to restore
1663              * the front buffer so the back-buffers get restored as well. */
1664             if( p_vout->p_sys->b_using_overlay  )
1665                 IDirectDrawSurface2_Restore( p_pic->p_sys->p_front_surface );
1666             else
1667                 IDirectDrawSurface2_Restore( p_pic->p_sys->p_surface );
1668
1669             dxresult = IDirectDrawSurface2_Lock( p_pic->p_sys->p_surface, NULL,
1670                                                  &p_pic->p_sys->ddsd,
1671                                                  DDLOCK_WAIT, NULL);
1672 #ifndef NDEBUG
1673             if( dxresult == DDERR_SURFACELOST )
1674                 msg_Dbg( p_vout, "DirectXLockSurface: DDERR_SURFACELOST" );
1675 #endif
1676         }
1677         if( dxresult != DD_OK )
1678         {
1679             return VLC_EGENERIC;
1680         }
1681     }
1682
1683     /* Now we have a pointer to the surface memory, we can update our picture
1684      * structure. */
1685     if( UpdatePictureStruct( p_vout, p_pic )
1686         != VLC_SUCCESS )
1687     {
1688         DirectXUnlockSurface( p_vout, p_pic );
1689         return VLC_EGENERIC;
1690     }
1691     else
1692         return VLC_SUCCESS;
1693 }
1694
1695 /*****************************************************************************
1696  * DirectXUnlockSurface: Unlock a surface locked by DirectXLockSurface().
1697  *****************************************************************************/
1698 static int DirectXUnlockSurface( vout_thread_t *p_vout, picture_t *p_pic )
1699 {
1700     VLC_UNUSED( p_vout );
1701
1702     /* Unlock the Surface */
1703     if( IDirectDrawSurface2_Unlock( p_pic->p_sys->p_surface, NULL ) == DD_OK )
1704         return VLC_SUCCESS;
1705     else
1706         return VLC_EGENERIC;
1707 }
1708
1709 /*****************************************************************************
1710  * DirectXFindColorkey: Finds out the 32bits RGB pixel value of the colorkey
1711  *****************************************************************************/
1712 static DWORD DirectXFindColorkey( vout_thread_t *p_vout, uint32_t *pi_color )
1713 {
1714     DDSURFACEDESC ddsd;
1715     HRESULT dxresult;
1716     COLORREF i_rgb = 0;
1717     uint32_t i_pixel_backup;
1718     HDC hdc;
1719
1720     ddsd.dwSize = sizeof(ddsd);
1721     dxresult = IDirectDrawSurface2_Lock( p_vout->p_sys->p_display, NULL,
1722                                          &ddsd, DDLOCK_WAIT, NULL );
1723     if( dxresult != DD_OK ) return 0;
1724
1725     i_pixel_backup = *(uint32_t *)ddsd.lpSurface;
1726
1727     switch( ddsd.ddpfPixelFormat.dwRGBBitCount )
1728     {
1729     case 4:
1730         *(uint8_t *)ddsd.lpSurface = *pi_color | (*pi_color << 4);
1731         break;
1732     case 8:
1733         *(uint8_t *)ddsd.lpSurface = *pi_color;
1734         break;
1735     case 15:
1736     case 16:
1737         *(uint16_t *)ddsd.lpSurface = *pi_color;
1738         break;
1739     case 24:
1740         /* Seems to be problematic so we'll just put black as the colorkey */
1741         *pi_color = 0;
1742     default:
1743         *(uint32_t *)ddsd.lpSurface = *pi_color;
1744         break;
1745     }
1746
1747     IDirectDrawSurface2_Unlock( p_vout->p_sys->p_display, NULL );
1748
1749     if( IDirectDrawSurface2_GetDC( p_vout->p_sys->p_display, &hdc ) == DD_OK )
1750     {
1751         i_rgb = GetPixel( hdc, 0, 0 );
1752         IDirectDrawSurface2_ReleaseDC( p_vout->p_sys->p_display, hdc );
1753     }
1754
1755     ddsd.dwSize = sizeof(ddsd);
1756     dxresult = IDirectDrawSurface2_Lock( p_vout->p_sys->p_display, NULL,
1757                                          &ddsd, DDLOCK_WAIT, NULL );
1758     if( dxresult != DD_OK ) return i_rgb;
1759
1760     *(uint32_t *)ddsd.lpSurface = i_pixel_backup;
1761
1762     IDirectDrawSurface2_Unlock( p_vout->p_sys->p_display, NULL );
1763
1764     return i_rgb;
1765 }
1766
1767 /*****************************************************************************
1768  * A few toolbox functions
1769  *****************************************************************************/
1770 void SwitchWallpaperMode( vout_thread_t *p_vout, bool b_on )
1771 {
1772     HWND hwnd;
1773
1774     if( p_vout->p_sys->b_wallpaper == b_on ) return; /* Nothing to do */
1775
1776     hwnd = FindWindow( _T("Progman"), NULL );
1777     if( hwnd ) hwnd = FindWindowEx( hwnd, NULL, _T("SHELLDLL_DefView"), NULL );
1778     if( hwnd ) hwnd = FindWindowEx( hwnd, NULL, _T("SysListView32"), NULL );
1779     if( !hwnd )
1780     {
1781         msg_Warn( p_vout, "couldn't find \"SysListView32\" window, "
1782                   "wallpaper mode not supported" );
1783         return;
1784     }
1785
1786     p_vout->p_sys->b_wallpaper = b_on;
1787
1788     msg_Dbg( p_vout, "wallpaper mode %s", b_on ? "enabled" : "disabled" );
1789
1790     if( p_vout->p_sys->b_wallpaper )
1791     {
1792         p_vout->p_sys->color_bkg = ListView_GetBkColor( hwnd );
1793         p_vout->p_sys->color_bkgtxt = ListView_GetTextBkColor( hwnd );
1794
1795         ListView_SetBkColor( hwnd, p_vout->p_sys->i_rgb_colorkey );
1796         ListView_SetTextBkColor( hwnd, p_vout->p_sys->i_rgb_colorkey );
1797     }
1798     else if( hwnd )
1799     {
1800         ListView_SetBkColor( hwnd, p_vout->p_sys->color_bkg );
1801         ListView_SetTextBkColor( hwnd, p_vout->p_sys->color_bkgtxt );
1802     }
1803
1804     /* Update desktop */
1805     InvalidateRect( hwnd, NULL, TRUE );
1806     UpdateWindow( hwnd );
1807 }
1808
1809 /*****************************************************************************
1810  * config variable callback
1811  *****************************************************************************/
1812 BOOL WINAPI DirectXEnumCallback2( GUID* p_guid, LPTSTR psz_desc,
1813                                   LPTSTR psz_drivername, VOID* p_context,
1814                                   HMONITOR hmon )
1815 {
1816     VLC_UNUSED( p_guid ); VLC_UNUSED( psz_desc ); VLC_UNUSED( hmon );
1817
1818     module_config_t *p_item = (module_config_t *)p_context;
1819
1820     p_item->ppsz_list =
1821         (char **)realloc( p_item->ppsz_list,
1822                           (p_item->i_list+2) * sizeof(char *) );
1823     p_item->ppsz_list_text =
1824         (char **)realloc( p_item->ppsz_list_text,
1825                           (p_item->i_list+2) * sizeof(char *) );
1826
1827     p_item->ppsz_list[p_item->i_list] = strdup( psz_drivername );
1828     p_item->ppsz_list_text[p_item->i_list] = NULL;
1829     p_item->i_list++;
1830     p_item->ppsz_list[p_item->i_list] = NULL;
1831     p_item->ppsz_list_text[p_item->i_list] = NULL;
1832
1833     return TRUE; /* Keep enumerating */
1834 }
1835
1836 static int FindDevicesCallback( vlc_object_t *p_this, char const *psz_name,
1837                                vlc_value_t newval, vlc_value_t oldval, void *d)
1838 {
1839     VLC_UNUSED( newval ); VLC_UNUSED( oldval ); VLC_UNUSED( d );
1840
1841     HRESULT (WINAPI *OurDirectDrawEnumerateEx)( LPDDENUMCALLBACKEXA, LPVOID,
1842                                                 DWORD );
1843     HINSTANCE hddraw_dll;
1844
1845     module_config_t *p_item;
1846     int i;
1847
1848     p_item = config_FindConfig( p_this, psz_name );
1849     if( !p_item ) return VLC_SUCCESS;
1850
1851     /* Clear-up the current list */
1852     if( p_item->i_list )
1853     {
1854         /* Keep the first entry */
1855         for( i = 1; i < p_item->i_list; i++ )
1856         {
1857             free( p_item->ppsz_list[i] );
1858             free( p_item->ppsz_list_text[i] );
1859         }
1860         /* TODO: Remove when no more needed */
1861         p_item->ppsz_list[i] = NULL;
1862         p_item->ppsz_list_text[i] = NULL;
1863     }
1864     p_item->i_list = 1;
1865
1866     /* Load direct draw DLL */
1867     hddraw_dll = LoadLibrary(_T("DDRAW.DLL"));
1868     if( hddraw_dll == NULL ) return VLC_SUCCESS;
1869
1870     OurDirectDrawEnumerateEx =
1871       (void *)GetProcAddress( hddraw_dll, _T("DirectDrawEnumerateExW") );
1872
1873     if( OurDirectDrawEnumerateEx )
1874     {
1875         /* Enumerate displays */
1876         OurDirectDrawEnumerateEx( DirectXEnumCallback2, p_item,
1877                                   DDENUM_ATTACHEDSECONDARYDEVICES );
1878     }
1879
1880     FreeLibrary( hddraw_dll );
1881
1882     /* Signal change to the interface */
1883     p_item->b_dirty = true;
1884
1885     return VLC_SUCCESS;
1886 }
1887
1888 static int WallpaperCallback( vlc_object_t *p_this, char const *psz_cmd,
1889                               vlc_value_t oldval, vlc_value_t newval,
1890                               void *p_data )
1891 {
1892     VLC_UNUSED( psz_cmd ); VLC_UNUSED( oldval ); VLC_UNUSED( p_data );
1893     vout_thread_t *p_vout = (vout_thread_t *)p_this;
1894
1895     if( (newval.b_bool && !p_vout->p_sys->b_wallpaper) ||
1896         (!newval.b_bool && p_vout->p_sys->b_wallpaper) )
1897     {
1898         playlist_t *p_playlist = pl_Hold( p_vout );
1899
1900         if( p_playlist )
1901         {
1902             /* Modify playlist as well because the vout might have to be
1903              * restarted */
1904             var_Create( p_playlist, "directx-wallpaper", VLC_VAR_BOOL );
1905             var_Set( p_playlist, "directx-wallpaper", newval );
1906             pl_Release( p_vout );
1907         }
1908
1909         p_vout->p_sys->i_changes |= DX_WALLPAPER_CHANGE;
1910     }
1911
1912     return VLC_SUCCESS;
1913 }
1914
1915 /*****************************************************************************
1916  * SetPalette: sets an 8 bpp palette
1917  *****************************************************************************/
1918 static void SetPalette( vout_thread_t *p_vout,
1919                         uint16_t *red, uint16_t *green, uint16_t *blue )
1920 {
1921     VLC_UNUSED( red ); VLC_UNUSED( green );VLC_UNUSED( blue );
1922     msg_Err( p_vout, "FIXME: SetPalette unimplemented" );
1923 }