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