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