* modules/video_output/directx/directx.c: I think I finally have the mouse autohiding...
[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         HWND hwnd;
570
571         /* Hide the cursor only if it is inside our window */
572         GetCursorPos( &point );
573         hwnd = WindowFromPoint(point);
574         if( hwnd == p_vout->p_sys->hwnd || hwnd == p_vout->p_sys->hvideownd )
575         {
576             PostMessage( p_vout->p_sys->hwnd, WM_VLC_HIDE_MOUSE, 0, 0 );
577         }
578         else
579         {
580             p_vout->p_sys->i_lastmoved = mdate();
581         }
582     }
583
584     /*
585      * "Always on top" status change
586      */
587     if( p_vout->p_sys->b_on_top_change )
588     {
589         vlc_value_t val;
590         HMENU hMenu = GetSystemMenu( p_vout->p_sys->hwnd, FALSE );
591
592         var_Get( p_vout, "video-on-top", &val );
593
594         /* Set the window on top if necessary */
595         if( val.b_bool && !( GetWindowLong( p_vout->p_sys->hwnd, GWL_EXSTYLE )
596                            & WS_EX_TOPMOST ) )
597         {
598             CheckMenuItem( hMenu, IDM_TOGGLE_ON_TOP,
599                            MF_BYCOMMAND | MFS_CHECKED );
600             SetWindowPos( p_vout->p_sys->hwnd, HWND_TOPMOST, 0, 0, 0, 0,
601                           SWP_NOSIZE | SWP_NOMOVE );
602         }
603         else
604         /* The window shouldn't be on top */
605         if( !val.b_bool && ( GetWindowLong( p_vout->p_sys->hwnd, GWL_EXSTYLE )
606                            & WS_EX_TOPMOST ) )
607         {
608             CheckMenuItem( hMenu, IDM_TOGGLE_ON_TOP,
609                            MF_BYCOMMAND | MFS_UNCHECKED );
610             SetWindowPos( p_vout->p_sys->hwnd, HWND_NOTOPMOST, 0, 0, 0, 0,
611                           SWP_NOSIZE | SWP_NOMOVE );
612         }
613
614         p_vout->p_sys->b_on_top_change = VLC_FALSE;
615     }
616
617     /* Check if the event thread is still running */
618     if( p_vout->p_sys->p_event->b_die )
619     {
620         return VLC_EGENERIC; /* exit */
621     }
622
623     return VLC_SUCCESS;
624 }
625
626 /*****************************************************************************
627  * Display: displays previously rendered output
628  *****************************************************************************
629  * This function sends the currently rendered image to the display, wait until
630  * it is displayed and switch the two rendering buffers, preparing next frame.
631  *****************************************************************************/
632 static void Display( vout_thread_t *p_vout, picture_t *p_pic )
633 {
634     HRESULT dxresult;
635
636     if( (p_vout->p_sys->p_display == NULL) )
637     {
638         msg_Warn( p_vout, "no display!" );
639         return;
640     }
641
642     /* Our surface can be lost so be sure to check this
643      * and restore it if need be */
644     if( IDirectDrawSurface2_IsLost( p_vout->p_sys->p_display )
645         == DDERR_SURFACELOST )
646     {
647         if( IDirectDrawSurface2_Restore( p_vout->p_sys->p_display ) == DD_OK &&
648             p_vout->p_sys->b_using_overlay )
649             DirectXUpdateOverlay( p_vout );
650     }
651
652     if( !p_vout->p_sys->b_using_overlay )
653     {
654         DDBLTFX  ddbltfx;
655
656         /* We ask for the "NOTEARING" option */
657         memset( &ddbltfx, 0, sizeof(DDBLTFX) );
658         ddbltfx.dwSize = sizeof(DDBLTFX);
659         ddbltfx.dwDDFX = DDBLTFX_NOTEARING;
660
661         /* Blit video surface to display */
662         dxresult = IDirectDrawSurface2_Blt( p_vout->p_sys->p_display,
663                                             &p_vout->p_sys->rect_dest_clipped,
664                                             p_pic->p_sys->p_surface,
665                                             &p_vout->p_sys->rect_src_clipped,
666                                             DDBLT_ASYNC, &ddbltfx );
667         if( dxresult != DD_OK )
668         {
669             msg_Warn( p_vout, "could not blit surface (error %li)", dxresult );
670             return;
671         }
672
673     }
674     else /* using overlay */
675     {
676         /* Flip the overlay buffers if we are using back buffers */
677         if( p_pic->p_sys->p_front_surface == p_pic->p_sys->p_surface )
678         {
679             return;
680         }
681
682         dxresult = IDirectDrawSurface2_Flip( p_pic->p_sys->p_front_surface,
683                                              NULL, DDFLIP_WAIT );
684         if( dxresult != DD_OK )
685         {
686             msg_Warn( p_vout, "could not flip overlay (error %li)", dxresult );
687         }
688
689         /* set currently displayed pic */
690         p_vout->p_sys->p_current_surface = p_pic->p_sys->p_front_surface;
691
692         /* Lock surface to get all the required info */
693         if( DirectXLockSurface( p_vout, p_pic ) )
694         {
695             /* AAARRGG */
696             msg_Warn( p_vout, "cannot lock surface" );
697             return;
698         }
699         DirectXUnlockSurface( p_vout, p_pic );
700     }
701 }
702
703 /* following functions are local */
704
705 /*****************************************************************************
706  * DirectXEnumCallback: Device enumeration
707  *****************************************************************************
708  * This callback function is called by DirectDraw once for each
709  * available DirectDraw device.
710  *****************************************************************************/
711 BOOL WINAPI DirectXEnumCallback( GUID* p_guid, LPTSTR psz_desc,
712                                  LPTSTR psz_drivername, VOID* p_context,
713                                  HMONITOR hmon )
714 {
715     vout_thread_t *p_vout = (vout_thread_t *)p_context;
716     vlc_value_t device;
717
718     msg_Dbg( p_vout, "DirectXEnumCallback: %s, %s", psz_desc, psz_drivername );
719
720     if( hmon )
721     {
722         var_Get( p_vout, "directx-device", &device );
723
724         if( ( !device.psz_string || !*device.psz_string ) &&
725             hmon == p_vout->p_sys->hmonitor )
726         {
727             if( device.psz_string ) free( device.psz_string );
728         }
729         else if( strcmp( psz_drivername, device.psz_string ) == 0 )
730         {
731             MONITORINFO monitor_info;
732             monitor_info.cbSize = sizeof( MONITORINFO );
733
734             if( p_vout->p_sys->GetMonitorInfo( hmon, &monitor_info ) )
735             {
736                 RECT rect;
737
738                 /* Move window to the right screen */
739                 GetWindowRect( p_vout->p_sys->hwnd, &rect );
740                 if( !IntersectRect( &rect, &rect, &monitor_info.rcWork ) )
741                 {
742                     rect.left = monitor_info.rcWork.left;
743                     rect.top = monitor_info.rcWork.top;
744                     msg_Dbg( p_vout, "DirectXEnumCallback: Setting window "
745                              "position to %d,%d", rect.left, rect.top );
746                     SetWindowPos( p_vout->p_sys->hwnd, NULL,
747                                   rect.left, rect.top, 0, 0,
748                                   SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE );
749                 }
750             }
751
752             p_vout->p_sys->hmonitor = hmon;
753             if( device.psz_string ) free( device.psz_string );
754         }
755         else
756         {
757             if( device.psz_string ) free( device.psz_string );
758             return TRUE; /* Keep enumerating */
759         }
760
761         msg_Dbg( p_vout, "selecting %s, %s", psz_desc, psz_drivername );
762         p_vout->p_sys->p_display_driver = malloc( sizeof(GUID) );
763         if( p_vout->p_sys->p_display_driver )
764             memcpy( p_vout->p_sys->p_display_driver, p_guid, sizeof(GUID) );
765     }
766
767     return TRUE; /* Keep enumerating */
768 }
769
770 /*****************************************************************************
771  * DirectXInitDDraw: Takes care of all the DirectDraw initialisations
772  *****************************************************************************
773  * This function initialise and allocate resources for DirectDraw.
774  *****************************************************************************/
775 static int DirectXInitDDraw( vout_thread_t *p_vout )
776 {
777     HRESULT dxresult;
778     HRESULT (WINAPI *OurDirectDrawCreate)(GUID *,LPDIRECTDRAW *,IUnknown *);
779     HRESULT (WINAPI *OurDirectDrawEnumerateEx)( LPDDENUMCALLBACKEXA, LPVOID,
780                                                 DWORD );
781     LPDIRECTDRAW p_ddobject;
782
783     msg_Dbg( p_vout, "DirectXInitDDraw" );
784
785     /* Load direct draw DLL */
786     p_vout->p_sys->hddraw_dll = LoadLibrary("DDRAW.DLL");
787     if( p_vout->p_sys->hddraw_dll == NULL )
788     {
789         msg_Warn( p_vout, "DirectXInitDDraw failed loading ddraw.dll" );
790         goto error;
791     }
792
793     OurDirectDrawCreate =
794       (void *)GetProcAddress(p_vout->p_sys->hddraw_dll, "DirectDrawCreate");
795     if( OurDirectDrawCreate == NULL )
796     {
797         msg_Err( p_vout, "DirectXInitDDraw failed GetProcAddress" );
798         goto error;
799     }
800
801     OurDirectDrawEnumerateEx =
802       (void *)GetProcAddress( p_vout->p_sys->hddraw_dll,
803                               "DirectDrawEnumerateExA" );
804
805     if( OurDirectDrawEnumerateEx && p_vout->p_sys->MonitorFromWindow )
806     {
807         vlc_value_t device;
808
809         var_Get( p_vout, "directx-device", &device );
810         if( device.psz_string )
811         {
812             msg_Dbg( p_vout, "directx-device: %s", device.psz_string );
813             free( device.psz_string );
814         }
815
816         p_vout->p_sys->hmonitor =
817             p_vout->p_sys->MonitorFromWindow( p_vout->p_sys->hwnd,
818                                               MONITOR_DEFAULTTONEAREST );
819
820         /* Enumerate displays */
821         OurDirectDrawEnumerateEx( DirectXEnumCallback, p_vout,
822                                   DDENUM_ATTACHEDSECONDARYDEVICES );
823     }
824
825     /* Initialize DirectDraw now */
826     dxresult = OurDirectDrawCreate( p_vout->p_sys->p_display_driver,
827                                     &p_ddobject, NULL );
828     if( dxresult != DD_OK )
829     {
830         msg_Err( p_vout, "DirectXInitDDraw cannot initialize DDraw" );
831         goto error;
832     }
833
834     /* Get the IDirectDraw2 interface */
835     dxresult = IDirectDraw_QueryInterface( p_ddobject, &IID_IDirectDraw2,
836                                         (LPVOID *)&p_vout->p_sys->p_ddobject );
837     /* Release the unused interface */
838     IDirectDraw_Release( p_ddobject );
839     if( dxresult != DD_OK )
840     {
841         msg_Err( p_vout, "cannot get IDirectDraw2 interface" );
842         goto error;
843     }
844
845     /* Set DirectDraw Cooperative level, ie what control we want over Windows
846      * display */
847     dxresult = IDirectDraw2_SetCooperativeLevel( p_vout->p_sys->p_ddobject,
848                                                  NULL, DDSCL_NORMAL );
849     if( dxresult != DD_OK )
850     {
851         msg_Err( p_vout, "cannot set direct draw cooperative level" );
852         goto error;
853     }
854
855     /* Get the size of the current display device */
856     if( p_vout->p_sys->hmonitor && p_vout->p_sys->GetMonitorInfo )
857     {
858         MONITORINFO monitor_info;
859         monitor_info.cbSize = sizeof( MONITORINFO );
860         p_vout->p_sys->GetMonitorInfo( p_vout->p_sys->hmonitor,
861                                        &monitor_info );
862         p_vout->p_sys->rect_display = monitor_info.rcMonitor;
863     }
864     else
865     {
866         p_vout->p_sys->rect_display.left = 0;
867         p_vout->p_sys->rect_display.top = 0;
868         p_vout->p_sys->rect_display.right  = GetSystemMetrics(SM_CXSCREEN);
869         p_vout->p_sys->rect_display.bottom = GetSystemMetrics(SM_CYSCREEN);
870     }
871
872     msg_Dbg( p_vout, "screen dimensions (%ix%i,%ix%i)",
873              p_vout->p_sys->rect_display.left,
874              p_vout->p_sys->rect_display.top,
875              p_vout->p_sys->rect_display.right,
876              p_vout->p_sys->rect_display.bottom );
877
878     /* Probe the capabilities of the hardware */
879     DirectXGetDDrawCaps( p_vout );
880
881     msg_Dbg( p_vout, "End DirectXInitDDraw" );
882     return VLC_SUCCESS;
883
884  error:
885     if( p_vout->p_sys->p_ddobject )
886         IDirectDraw2_Release( p_vout->p_sys->p_ddobject );
887     if( p_vout->p_sys->hddraw_dll )
888         FreeLibrary( p_vout->p_sys->hddraw_dll );
889     p_vout->p_sys->hddraw_dll = NULL;
890     p_vout->p_sys->p_ddobject = NULL;
891     return VLC_EGENERIC;
892 }
893
894 /*****************************************************************************
895  * DirectXCreateDisplay: create the DirectDraw display.
896  *****************************************************************************
897  * Create and initialize display according to preferences specified in the vout
898  * thread fields.
899  *****************************************************************************/
900 static int DirectXCreateDisplay( vout_thread_t *p_vout )
901 {
902     HRESULT              dxresult;
903     DDSURFACEDESC        ddsd;
904     LPDIRECTDRAWSURFACE  p_display;
905
906     msg_Dbg( p_vout, "DirectXCreateDisplay" );
907
908     /* Now get the primary surface. This surface is what you actually see
909      * on your screen */
910     memset( &ddsd, 0, sizeof( DDSURFACEDESC ));
911     ddsd.dwSize = sizeof(DDSURFACEDESC);
912     ddsd.dwFlags = DDSD_CAPS;
913     ddsd.ddsCaps.dwCaps = DDSCAPS_PRIMARYSURFACE;
914
915     dxresult = IDirectDraw2_CreateSurface( p_vout->p_sys->p_ddobject,
916                                            &ddsd, &p_display, NULL );
917     if( dxresult != DD_OK )
918     {
919         msg_Err( p_vout, "cannot get primary surface (error %li)", dxresult );
920         return VLC_EGENERIC;
921     }
922
923     dxresult = IDirectDrawSurface_QueryInterface( p_display,
924                                          &IID_IDirectDrawSurface2,
925                                          (LPVOID *)&p_vout->p_sys->p_display );
926     /* Release the old interface */
927     IDirectDrawSurface_Release( p_display );
928     if ( dxresult != DD_OK )
929     {
930         msg_Err( p_vout, "cannot query IDirectDrawSurface2 interface "
931                          "(error %li)", dxresult );
932         return VLC_EGENERIC;
933     }
934
935     /* The clipper will be used only in non-overlay mode */
936     DirectXCreateClipper( p_vout );
937
938     /* Make sure the colorkey will be painted */
939     p_vout->p_sys->i_colorkey = 1;
940     p_vout->p_sys->i_rgb_colorkey =
941         DirectXFindColorkey( p_vout, p_vout->p_sys->i_colorkey );
942
943     /* Create the actual brush */
944     SetClassLong( p_vout->p_sys->hvideownd, GCL_HBRBACKGROUND,
945                   (LONG)CreateSolidBrush( p_vout->p_sys->i_rgb_colorkey ) );
946     InvalidateRect( p_vout->p_sys->hvideownd, NULL, TRUE );
947     DirectXUpdateRects( p_vout, VLC_TRUE );
948
949     return VLC_SUCCESS;
950 }
951
952 /*****************************************************************************
953  * DirectXCreateClipper: Create a clipper that will be used when blitting the
954  *                       RGB surface to the main display.
955  *****************************************************************************
956  * This clipper prevents us to modify by mistake anything on the screen
957  * which doesn't belong to our window. For example when a part of our video
958  * window is hidden by another window.
959  *****************************************************************************/
960 static int DirectXCreateClipper( vout_thread_t *p_vout )
961 {
962     HRESULT dxresult;
963
964     msg_Dbg( p_vout, "DirectXCreateClipper" );
965
966     /* Create the clipper */
967     dxresult = IDirectDraw2_CreateClipper( p_vout->p_sys->p_ddobject, 0,
968                                            &p_vout->p_sys->p_clipper, NULL );
969     if( dxresult != DD_OK )
970     {
971         msg_Warn( p_vout, "cannot create clipper (error %li)", dxresult );
972         goto error;
973     }
974
975     /* Associate the clipper to the window */
976     dxresult = IDirectDrawClipper_SetHWnd( p_vout->p_sys->p_clipper, 0,
977                                            p_vout->p_sys->hvideownd );
978     if( dxresult != DD_OK )
979     {
980         msg_Warn( p_vout, "cannot attach clipper to window (error %li)",
981                           dxresult );
982         goto error;
983     }
984
985     /* associate the clipper with the surface */
986     dxresult = IDirectDrawSurface_SetClipper(p_vout->p_sys->p_display,
987                                              p_vout->p_sys->p_clipper);
988     if( dxresult != DD_OK )
989     {
990         msg_Warn( p_vout, "cannot attach clipper to surface (error %li)",
991                           dxresult );
992         goto error;
993     }
994
995     return VLC_SUCCESS;
996
997  error:
998     if( p_vout->p_sys->p_clipper )
999     {
1000         IDirectDrawClipper_Release( p_vout->p_sys->p_clipper );
1001     }
1002     p_vout->p_sys->p_clipper = NULL;
1003     return VLC_EGENERIC;
1004 }
1005
1006 /*****************************************************************************
1007  * DirectXCreateSurface: create an YUV overlay or RGB surface for the video.
1008  *****************************************************************************
1009  * The best method of display is with an YUV overlay because the YUV->RGB
1010  * conversion is done in hardware.
1011  * You can also create a plain RGB surface.
1012  * ( Maybe we could also try an RGB overlay surface, which could have hardware
1013  * scaling and which would also be faster in window mode because you don't
1014  * need to do any blitting to the main display...)
1015  *****************************************************************************/
1016 static int DirectXCreateSurface( vout_thread_t *p_vout,
1017                                  LPDIRECTDRAWSURFACE2 *pp_surface_final,
1018                                  int i_chroma, int b_overlay,
1019                                  int i_backbuffers )
1020 {
1021     HRESULT dxresult;
1022     LPDIRECTDRAWSURFACE p_surface;
1023     DDSURFACEDESC ddsd;
1024
1025     /* Create the video surface */
1026     if( b_overlay )
1027     {
1028         /* Now try to create the YUV overlay surface.
1029          * This overlay will be displayed on top of the primary surface.
1030          * A color key is used to determine whether or not the overlay will be
1031          * displayed, ie the overlay will be displayed in place of the primary
1032          * surface wherever the primary surface will have this color.
1033          * The video window has been created with a background of this color so
1034          * the overlay will be only displayed on top of this window */
1035
1036         memset( &ddsd, 0, sizeof( DDSURFACEDESC ));
1037         ddsd.dwSize = sizeof(DDSURFACEDESC);
1038         ddsd.ddpfPixelFormat.dwSize = sizeof(DDPIXELFORMAT);
1039         ddsd.ddpfPixelFormat.dwFlags = DDPF_FOURCC;
1040         ddsd.ddpfPixelFormat.dwFourCC = i_chroma;
1041         ddsd.dwFlags = DDSD_CAPS | DDSD_HEIGHT | DDSD_WIDTH | DDSD_PIXELFORMAT;
1042         ddsd.dwFlags |= (i_backbuffers ? DDSD_BACKBUFFERCOUNT : 0);
1043         ddsd.ddsCaps.dwCaps = DDSCAPS_OVERLAY | DDSCAPS_VIDEOMEMORY;
1044         ddsd.ddsCaps.dwCaps |= (i_backbuffers ? DDSCAPS_COMPLEX | DDSCAPS_FLIP
1045                                 : 0 );
1046         ddsd.dwHeight = p_vout->render.i_height;
1047         ddsd.dwWidth = p_vout->render.i_width;
1048         ddsd.dwBackBufferCount = i_backbuffers;
1049
1050         dxresult = IDirectDraw2_CreateSurface( p_vout->p_sys->p_ddobject,
1051                                                &ddsd, &p_surface, NULL );
1052         if( dxresult != DD_OK )
1053         {
1054             *pp_surface_final = NULL;
1055             return VLC_EGENERIC;
1056         }
1057     }
1058
1059     if( !b_overlay )
1060     {
1061         vlc_bool_t b_rgb_surface =
1062             ( i_chroma == VLC_FOURCC('R','G','B','2') )
1063           || ( i_chroma == VLC_FOURCC('R','V','1','5') )
1064            || ( i_chroma == VLC_FOURCC('R','V','1','6') )
1065             || ( i_chroma == VLC_FOURCC('R','V','2','4') )
1066              || ( i_chroma == VLC_FOURCC('R','V','3','2') );
1067
1068         memset( &ddsd, 0, sizeof( DDSURFACEDESC ) );
1069         ddsd.dwSize = sizeof(DDSURFACEDESC);
1070         ddsd.ddpfPixelFormat.dwSize = sizeof(DDPIXELFORMAT);
1071         ddsd.dwFlags = DDSD_HEIGHT | DDSD_WIDTH | DDSD_CAPS;
1072         ddsd.ddsCaps.dwCaps = DDSCAPS_OFFSCREENPLAIN;
1073         ddsd.dwHeight = p_vout->render.i_height;
1074         ddsd.dwWidth = p_vout->render.i_width;
1075
1076         if( p_vout->p_sys->b_use_sysmem )
1077             ddsd.ddsCaps.dwCaps |= DDSCAPS_SYSTEMMEMORY;
1078         else
1079             ddsd.ddsCaps.dwCaps |= DDSCAPS_VIDEOMEMORY;
1080
1081         if( !b_rgb_surface )
1082         {
1083             ddsd.dwFlags |= DDSD_PIXELFORMAT;
1084             ddsd.ddpfPixelFormat.dwFlags = DDPF_FOURCC;
1085             ddsd.ddpfPixelFormat.dwFourCC = i_chroma;
1086         }
1087
1088         dxresult = IDirectDraw2_CreateSurface( p_vout->p_sys->p_ddobject,
1089                                                &ddsd, &p_surface, NULL );
1090         if( dxresult != DD_OK )
1091         {
1092             *pp_surface_final = NULL;
1093             return VLC_EGENERIC;
1094         }
1095     }
1096
1097     /* Now that the surface is created, try to get a newer DirectX interface */
1098     dxresult = IDirectDrawSurface_QueryInterface( p_surface,
1099                                      &IID_IDirectDrawSurface2,
1100                                      (LPVOID *)pp_surface_final );
1101     IDirectDrawSurface_Release( p_surface );    /* Release the old interface */
1102     if ( dxresult != DD_OK )
1103     {
1104         msg_Err( p_vout, "cannot query IDirectDrawSurface2 interface "
1105                          "(error %li)", dxresult );
1106         *pp_surface_final = NULL;
1107         return VLC_EGENERIC;
1108     }
1109
1110     if( b_overlay )
1111     {
1112         /* Check the overlay is useable as some graphics cards allow creating
1113          * several overlays but only one can be used at one time. */
1114         p_vout->p_sys->p_current_surface = *pp_surface_final;
1115         if( DirectXUpdateOverlay( p_vout ) != VLC_SUCCESS )
1116         {
1117             IDirectDrawSurface2_Release( *pp_surface_final );
1118             *pp_surface_final = NULL;
1119             msg_Err( p_vout, "overlay unuseable (might already be in use)" );
1120             return VLC_EGENERIC;
1121         }
1122     }
1123
1124     return VLC_SUCCESS;
1125 }
1126
1127 /*****************************************************************************
1128  * DirectXUpdateOverlay: Move or resize overlay surface on video display.
1129  *****************************************************************************
1130  * This function is used to move or resize an overlay surface on the screen.
1131  * Ususally the overlay is moved by the user and thus, by a move or resize
1132  * event (in Manage).
1133  *****************************************************************************/
1134 int DirectXUpdateOverlay( vout_thread_t *p_vout )
1135 {
1136     DDOVERLAYFX     ddofx;
1137     DWORD           dwFlags;
1138     HRESULT         dxresult;
1139     RECT            rect_src = p_vout->p_sys->rect_src_clipped;
1140     RECT            rect_dest = p_vout->p_sys->rect_dest_clipped;
1141
1142     if( !p_vout->p_sys->b_using_overlay ) return VLC_EGENERIC;
1143
1144     vlc_mutex_lock( &p_vout->p_sys->lock );
1145     if( p_vout->p_sys->p_current_surface == NULL )
1146     {
1147         vlc_mutex_unlock( &p_vout->p_sys->lock );
1148         return VLC_EGENERIC;
1149     }
1150
1151     /* The new window dimensions should already have been computed by the
1152      * caller of this function */
1153
1154     /* Position and show the overlay */
1155     memset(&ddofx, 0, sizeof(DDOVERLAYFX));
1156     ddofx.dwSize = sizeof(DDOVERLAYFX);
1157     ddofx.dckDestColorkey.dwColorSpaceLowValue = p_vout->p_sys->i_colorkey;
1158     ddofx.dckDestColorkey.dwColorSpaceHighValue = p_vout->p_sys->i_colorkey;
1159
1160     dwFlags = DDOVER_SHOW | DDOVER_KEYDESTOVERRIDE;
1161
1162     dxresult = IDirectDrawSurface2_UpdateOverlay(
1163                    p_vout->p_sys->p_current_surface,
1164                    &rect_src, p_vout->p_sys->p_display, &rect_dest,
1165                    dwFlags, &ddofx );
1166
1167     vlc_mutex_unlock( &p_vout->p_sys->lock );
1168
1169     if(dxresult != DD_OK)
1170     {
1171         msg_Warn( p_vout, "DirectXUpdateOverlay cannot move/resize overlay" );
1172         return VLC_EGENERIC;
1173     }
1174
1175     return VLC_SUCCESS;
1176 }
1177
1178 /*****************************************************************************
1179  * DirectXCloseDDraw: Release the DDraw object allocated by DirectXInitDDraw
1180  *****************************************************************************
1181  * This function returns all resources allocated by DirectXInitDDraw.
1182  *****************************************************************************/
1183 static void DirectXCloseDDraw( vout_thread_t *p_vout )
1184 {
1185     msg_Dbg( p_vout, "DirectXCloseDDraw" );
1186     if( p_vout->p_sys->p_ddobject != NULL )
1187     {
1188         IDirectDraw2_Release(p_vout->p_sys->p_ddobject);
1189         p_vout->p_sys->p_ddobject = NULL;
1190     }
1191
1192     if( p_vout->p_sys->hddraw_dll != NULL )
1193     {
1194         FreeLibrary( p_vout->p_sys->hddraw_dll );
1195         p_vout->p_sys->hddraw_dll = NULL;
1196     }
1197
1198     if( p_vout->p_sys->p_display_driver != NULL )
1199     {
1200         free( p_vout->p_sys->p_display_driver );
1201         p_vout->p_sys->p_display_driver = NULL;
1202     }
1203
1204     p_vout->p_sys->hmonitor = NULL;
1205 }
1206
1207 /*****************************************************************************
1208  * DirectXCloseDisplay: close and reset the DirectX display device
1209  *****************************************************************************
1210  * This function returns all resources allocated by DirectXCreateDisplay.
1211  *****************************************************************************/
1212 static void DirectXCloseDisplay( vout_thread_t *p_vout )
1213 {
1214     msg_Dbg( p_vout, "DirectXCloseDisplay" );
1215
1216     if( p_vout->p_sys->p_clipper != NULL )
1217     {
1218         msg_Dbg( p_vout, "DirectXCloseDisplay clipper" );
1219         IDirectDrawClipper_Release( p_vout->p_sys->p_clipper );
1220         p_vout->p_sys->p_clipper = NULL;
1221     }
1222
1223     if( p_vout->p_sys->p_display != NULL )
1224     {
1225         msg_Dbg( p_vout, "DirectXCloseDisplay display" );
1226         IDirectDrawSurface2_Release( p_vout->p_sys->p_display );
1227         p_vout->p_sys->p_display = NULL;
1228     }
1229 }
1230
1231 /*****************************************************************************
1232  * DirectXCloseSurface: close the YUV overlay or RGB surface.
1233  *****************************************************************************
1234  * This function returns all resources allocated for the surface.
1235  *****************************************************************************/
1236 static void DirectXCloseSurface( vout_thread_t *p_vout,
1237                                  LPDIRECTDRAWSURFACE2 p_surface )
1238 {
1239     msg_Dbg( p_vout, "DirectXCloseSurface" );
1240     if( p_surface != NULL )
1241     {
1242         IDirectDrawSurface2_Release( p_surface );
1243     }
1244 }
1245
1246 /*****************************************************************************
1247  * NewPictureVec: allocate a vector of identical pictures
1248  *****************************************************************************
1249  * Returns 0 on success, -1 otherwise
1250  *****************************************************************************/
1251 static int NewPictureVec( vout_thread_t *p_vout, picture_t *p_pic,
1252                           int i_num_pics )
1253 {
1254     int i;
1255     int i_ret = VLC_SUCCESS;
1256     LPDIRECTDRAWSURFACE2 p_surface;
1257
1258     msg_Dbg( p_vout, "NewPictureVec overlay:%s chroma:%.4s",
1259              p_vout->p_sys->b_using_overlay ? "yes" : "no",
1260              (char *)&p_vout->output.i_chroma );
1261
1262     I_OUTPUTPICTURES = 0;
1263
1264     /* First we try to use an YUV overlay surface.
1265      * The overlay surface that we create won't be used to decode directly
1266      * into it because accessing video memory directly is way to slow (remember
1267      * that pictures are decoded macroblock per macroblock). Instead the video
1268      * will be decoded in picture buffers in system memory which will then be
1269      * memcpy() to the overlay surface. */
1270     if( p_vout->p_sys->b_using_overlay )
1271     {
1272         /* Triple buffering rocks! it doesn't have any processing overhead
1273          * (you don't have to wait for the vsync) and provides for a very nice
1274          * video quality (no tearing). */
1275         if( p_vout->p_sys->b_3buf_overlay )
1276             i_ret = DirectXCreateSurface( p_vout, &p_surface,
1277                                           p_vout->output.i_chroma,
1278                                           p_vout->p_sys->b_using_overlay,
1279                                           2 /* number of backbuffers */ );
1280
1281         if( !p_vout->p_sys->b_3buf_overlay || i_ret != VLC_SUCCESS )
1282         {
1283             /* Try to reduce the number of backbuffers */
1284             i_ret = DirectXCreateSurface( p_vout, &p_surface,
1285                                           p_vout->output.i_chroma,
1286                                           p_vout->p_sys->b_using_overlay,
1287                                           0 /* number of backbuffers */ );
1288         }
1289
1290         if( i_ret == VLC_SUCCESS )
1291         {
1292             DDSCAPS dds_caps;
1293             picture_t front_pic;
1294             picture_sys_t front_pic_sys;
1295             front_pic.p_sys = &front_pic_sys;
1296
1297             /* Allocate internal structure */
1298             p_pic[0].p_sys = malloc( sizeof( picture_sys_t ) );
1299             if( p_pic[0].p_sys == NULL )
1300             {
1301                 DirectXCloseSurface( p_vout, p_surface );
1302                 return VLC_ENOMEM;
1303             }
1304
1305             /* set front buffer */
1306             p_pic[0].p_sys->p_front_surface = p_surface;
1307
1308             /* Get the back buffer */
1309             memset( &dds_caps, 0, sizeof( DDSCAPS ) );
1310             dds_caps.dwCaps = DDSCAPS_BACKBUFFER;
1311             if( DD_OK != IDirectDrawSurface2_GetAttachedSurface(
1312                                                 p_surface, &dds_caps,
1313                                                 &p_pic[0].p_sys->p_surface ) )
1314             {
1315                 msg_Warn( p_vout, "NewPictureVec could not get back buffer" );
1316                 /* front buffer is the same as back buffer */
1317                 p_pic[0].p_sys->p_surface = p_surface;
1318             }
1319
1320
1321             p_vout->p_sys->p_current_surface = front_pic.p_sys->p_surface =
1322                 p_pic[0].p_sys->p_front_surface;
1323
1324             /* Reset the front buffer memory */
1325             if( DirectXLockSurface( p_vout, &front_pic ) == VLC_SUCCESS )
1326             {
1327                 int i,j;
1328                 for( i = 0; i < front_pic.i_planes; i++ )
1329                     for( j = 0; j < front_pic.p[i].i_lines; j++)
1330                         memset( front_pic.p[i].p_pixels + j *
1331                                 front_pic.p[i].i_pitch, 127,
1332                                 front_pic.p[i].i_visible_pitch );
1333
1334                 DirectXUnlockSurface( p_vout, &front_pic );
1335             }
1336
1337             DirectXUpdateOverlay( p_vout );
1338             I_OUTPUTPICTURES = 1;
1339             msg_Dbg( p_vout, "YUV overlay created successfully" );
1340         }
1341     }
1342
1343     /* As we can't have an overlay, we'll try to create a plain offscreen
1344      * surface. This surface will reside in video memory because there's a
1345      * better chance then that we'll be able to use some kind of hardware
1346      * acceleration like rescaling, blitting or YUV->RGB conversions.
1347      * We then only need to blit this surface onto the main display when we
1348      * want to display it */
1349     if( !p_vout->p_sys->b_using_overlay )
1350     {
1351         if( p_vout->p_sys->b_hw_yuv )
1352         {
1353             DWORD i_codes;
1354             DWORD *pi_codes;
1355             vlc_bool_t b_result = VLC_FALSE;
1356
1357             /* Check if the chroma is supported first. This is required
1358              * because a few buggy drivers don't mind creating the surface
1359              * even if they don't know about the chroma. */
1360             if( IDirectDraw2_GetFourCCCodes( p_vout->p_sys->p_ddobject,
1361                                              &i_codes, NULL ) == DD_OK )
1362             {
1363                 pi_codes = malloc( i_codes * sizeof(DWORD) );
1364                 if( pi_codes && IDirectDraw2_GetFourCCCodes(
1365                     p_vout->p_sys->p_ddobject, &i_codes, pi_codes ) == DD_OK )
1366                 {
1367                     for( i = 0; i < (int)i_codes; i++ )
1368                     {
1369                         if( p_vout->output.i_chroma == pi_codes[i] )
1370                         {
1371                             b_result = VLC_TRUE;
1372                             break;
1373                         }
1374                     }
1375                 }
1376             }
1377
1378             if( b_result )
1379                 i_ret = DirectXCreateSurface( p_vout, &p_surface,
1380                                               p_vout->output.i_chroma,
1381                                               0 /* no overlay */,
1382                                               0 /* no back buffers */ );
1383             else
1384                 p_vout->p_sys->b_hw_yuv = VLC_FALSE;
1385         }
1386
1387         if( i_ret || !p_vout->p_sys->b_hw_yuv )
1388         {
1389             /* Our last choice is to use a plain RGB surface */
1390             DDPIXELFORMAT ddpfPixelFormat;
1391
1392             ddpfPixelFormat.dwSize = sizeof(DDPIXELFORMAT);
1393             IDirectDrawSurface2_GetPixelFormat( p_vout->p_sys->p_display,
1394                                                 &ddpfPixelFormat );
1395
1396             if( ddpfPixelFormat.dwFlags & DDPF_RGB )
1397             {
1398                 switch( ddpfPixelFormat.dwRGBBitCount )
1399                 {
1400                 case 8: /* FIXME: set the palette */
1401                     p_vout->output.i_chroma = VLC_FOURCC('R','G','B','2');
1402                     break;
1403                 case 15:
1404                     p_vout->output.i_chroma = VLC_FOURCC('R','V','1','5');
1405                     break;
1406                 case 16:
1407                     p_vout->output.i_chroma = VLC_FOURCC('R','V','1','6');
1408                     break;
1409                 case 24:
1410                     p_vout->output.i_chroma = VLC_FOURCC('R','V','2','4');
1411                     break;
1412                 case 32:
1413                     p_vout->output.i_chroma = VLC_FOURCC('R','V','3','2');
1414                     break;
1415                 default:
1416                     msg_Err( p_vout, "unknown screen depth" );
1417                     return VLC_EGENERIC;
1418                 }
1419                 p_vout->output.i_rmask = ddpfPixelFormat.dwRBitMask;
1420                 p_vout->output.i_gmask = ddpfPixelFormat.dwGBitMask;
1421                 p_vout->output.i_bmask = ddpfPixelFormat.dwBBitMask;
1422             }
1423
1424             p_vout->p_sys->b_hw_yuv = 0;
1425
1426             i_ret = DirectXCreateSurface( p_vout, &p_surface,
1427                                           p_vout->output.i_chroma,
1428                                           0 /* no overlay */,
1429                                           0 /* no back buffers */ );
1430
1431             if( i_ret && !p_vout->p_sys->b_use_sysmem )
1432             {
1433                 /* Give it a last try with b_use_sysmem enabled */
1434                 p_vout->p_sys->b_use_sysmem = 1;
1435
1436                 i_ret = DirectXCreateSurface( p_vout, &p_surface,
1437                                               p_vout->output.i_chroma,
1438                                               0 /* no overlay */,
1439                                               0 /* no back buffers */ );
1440             }
1441         }
1442
1443         if( i_ret == VLC_SUCCESS )
1444         {
1445             /* Allocate internal structure */
1446             p_pic[0].p_sys = malloc( sizeof( picture_sys_t ) );
1447             if( p_pic[0].p_sys == NULL )
1448             {
1449                 DirectXCloseSurface( p_vout, p_surface );
1450                 return VLC_ENOMEM;
1451             }
1452
1453             p_pic[0].p_sys->p_surface = p_pic[0].p_sys->p_front_surface
1454                 = p_surface;
1455
1456             I_OUTPUTPICTURES = 1;
1457
1458             msg_Dbg( p_vout, "created plain surface of chroma:%.4s",
1459                      (char *)&p_vout->output.i_chroma );
1460         }
1461     }
1462
1463
1464     /* Now that we've got all our direct-buffers, we can finish filling in the
1465      * picture_t structures */
1466     for( i = 0; i < I_OUTPUTPICTURES; i++ )
1467     {
1468         p_pic[i].i_status = DESTROYED_PICTURE;
1469         p_pic[i].i_type   = DIRECT_PICTURE;
1470         p_pic[i].pf_lock  = DirectXLockSurface;
1471         p_pic[i].pf_unlock = DirectXUnlockSurface;
1472         PP_OUTPUTPICTURE[i] = &p_pic[i];
1473
1474         if( DirectXLockSurface( p_vout, &p_pic[i] ) != VLC_SUCCESS )
1475         {
1476             /* AAARRGG */
1477             FreePictureVec( p_vout, p_pic, I_OUTPUTPICTURES );
1478             I_OUTPUTPICTURES = 0;
1479             msg_Err( p_vout, "cannot lock surface" );
1480             return VLC_EGENERIC;
1481         }
1482         DirectXUnlockSurface( p_vout, &p_pic[i] );
1483     }
1484
1485     msg_Dbg( p_vout, "End NewPictureVec (%s)",
1486              I_OUTPUTPICTURES ? "succeeded" : "failed" );
1487
1488     return VLC_SUCCESS;
1489 }
1490
1491 /*****************************************************************************
1492  * FreePicture: destroy a picture vector allocated with NewPictureVec
1493  *****************************************************************************
1494  *
1495  *****************************************************************************/
1496 static void FreePictureVec( vout_thread_t *p_vout, picture_t *p_pic,
1497                             int i_num_pics )
1498 {
1499     int i;
1500
1501     vlc_mutex_lock( &p_vout->p_sys->lock );
1502     p_vout->p_sys->p_current_surface = 0;
1503     vlc_mutex_unlock( &p_vout->p_sys->lock );
1504
1505     for( i = 0; i < i_num_pics; i++ )
1506     {
1507         DirectXCloseSurface( p_vout, p_pic[i].p_sys->p_front_surface );
1508
1509         for( i = 0; i < i_num_pics; i++ )
1510         {
1511             free( p_pic[i].p_sys );
1512         }
1513     }
1514 }
1515
1516 /*****************************************************************************
1517  * UpdatePictureStruct: updates the internal data in the picture_t structure
1518  *****************************************************************************
1519  * This will setup stuff for use by the video_output thread
1520  *****************************************************************************/
1521 static int UpdatePictureStruct( vout_thread_t *p_vout, picture_t *p_pic,
1522                                 int i_chroma )
1523 {
1524     switch( p_vout->output.i_chroma )
1525     {
1526         case VLC_FOURCC('R','G','B','2'):
1527         case VLC_FOURCC('R','V','1','5'):
1528         case VLC_FOURCC('R','V','1','6'):
1529         case VLC_FOURCC('R','V','2','4'):
1530         case VLC_FOURCC('R','V','3','2'):
1531             p_pic->p->p_pixels = p_pic->p_sys->ddsd.lpSurface;
1532             p_pic->p->i_lines = p_vout->output.i_height;
1533             p_pic->p->i_pitch = p_pic->p_sys->ddsd.lPitch;
1534             switch( p_vout->output.i_chroma )
1535             {
1536                 case VLC_FOURCC('R','G','B','2'):
1537                     p_pic->p->i_pixel_pitch = 1;
1538                     break;
1539                 case VLC_FOURCC('R','V','1','5'):
1540                 case VLC_FOURCC('R','V','1','6'):
1541                     p_pic->p->i_pixel_pitch = 2;
1542                     break;
1543                 case VLC_FOURCC('R','V','2','4'):
1544                     p_pic->p->i_pixel_pitch = 3;
1545                     break;
1546                 case VLC_FOURCC('R','V','3','2'):
1547                     p_pic->p->i_pixel_pitch = 4;
1548                     break;
1549                 default:
1550                     return VLC_EGENERIC;
1551             }
1552             p_pic->p->i_visible_pitch = p_vout->output.i_width *
1553               p_pic->p->i_pixel_pitch;
1554             p_pic->i_planes = 1;
1555             break;
1556
1557         case VLC_FOURCC('Y','V','1','2'):
1558
1559             p_pic->Y_PIXELS = p_pic->p_sys->ddsd.lpSurface;
1560             p_pic->p[Y_PLANE].i_lines = p_vout->output.i_height;
1561             p_pic->p[Y_PLANE].i_pitch = p_pic->p_sys->ddsd.lPitch;
1562             p_pic->p[Y_PLANE].i_pixel_pitch = 1;
1563             p_pic->p[Y_PLANE].i_visible_pitch = p_vout->output.i_width *
1564               p_pic->p[Y_PLANE].i_pixel_pitch;
1565
1566             p_pic->V_PIXELS =  p_pic->Y_PIXELS
1567               + p_pic->p[Y_PLANE].i_lines * p_pic->p[Y_PLANE].i_pitch;
1568             p_pic->p[V_PLANE].i_lines = p_vout->output.i_height / 2;
1569             p_pic->p[V_PLANE].i_pitch = p_pic->p[Y_PLANE].i_pitch / 2;
1570             p_pic->p[V_PLANE].i_pixel_pitch = 1;
1571             p_pic->p[V_PLANE].i_visible_pitch = p_vout->output.i_width / 2 *
1572               p_pic->p[V_PLANE].i_pixel_pitch;
1573
1574             p_pic->U_PIXELS = p_pic->V_PIXELS
1575               + p_pic->p[V_PLANE].i_lines * p_pic->p[V_PLANE].i_pitch;
1576             p_pic->p[U_PLANE].i_lines = p_vout->output.i_height / 2;
1577             p_pic->p[U_PLANE].i_pitch = p_pic->p[Y_PLANE].i_pitch / 2;
1578             p_pic->p[U_PLANE].i_pixel_pitch = 1;
1579             p_pic->p[U_PLANE].i_visible_pitch = p_vout->output.i_width / 2 *
1580               p_pic->p[U_PLANE].i_pixel_pitch;
1581
1582             p_pic->i_planes = 3;
1583             break;
1584
1585         case VLC_FOURCC('I','Y','U','V'):
1586
1587             p_pic->Y_PIXELS = p_pic->p_sys->ddsd.lpSurface;
1588             p_pic->p[Y_PLANE].i_lines = p_vout->output.i_height;
1589             p_pic->p[Y_PLANE].i_pitch = p_pic->p_sys->ddsd.lPitch;
1590             p_pic->p[Y_PLANE].i_pixel_pitch = 1;
1591             p_pic->p[Y_PLANE].i_visible_pitch = p_vout->output.i_width *
1592               p_pic->p[Y_PLANE].i_pixel_pitch;
1593
1594             p_pic->U_PIXELS = p_pic->Y_PIXELS
1595               + p_pic->p[Y_PLANE].i_lines * p_pic->p[Y_PLANE].i_pitch;
1596             p_pic->p[U_PLANE].i_lines = p_vout->output.i_height / 2;
1597             p_pic->p[U_PLANE].i_pitch = p_pic->p[Y_PLANE].i_pitch / 2;
1598             p_pic->p[U_PLANE].i_pixel_pitch = 1;
1599             p_pic->p[U_PLANE].i_visible_pitch = p_vout->output.i_width / 2 *
1600               p_pic->p[U_PLANE].i_pixel_pitch;
1601
1602             p_pic->V_PIXELS =  p_pic->U_PIXELS
1603               + p_pic->p[U_PLANE].i_lines * p_pic->p[U_PLANE].i_pitch;
1604             p_pic->p[V_PLANE].i_lines = p_vout->output.i_height / 2;
1605             p_pic->p[V_PLANE].i_pitch = p_pic->p[Y_PLANE].i_pitch / 2;
1606             p_pic->p[V_PLANE].i_pixel_pitch = 1;
1607             p_pic->p[V_PLANE].i_visible_pitch = p_vout->output.i_width / 2 *
1608               p_pic->p[V_PLANE].i_pixel_pitch;
1609
1610             p_pic->i_planes = 3;
1611             break;
1612
1613         case VLC_FOURCC('Y','U','Y','2'):
1614
1615             p_pic->p->p_pixels = p_pic->p_sys->ddsd.lpSurface;
1616             p_pic->p->i_lines = p_vout->output.i_height;
1617             p_pic->p->i_pitch = p_pic->p_sys->ddsd.lPitch;
1618             p_pic->p->i_pixel_pitch = 2;
1619             p_pic->p->i_visible_pitch = p_vout->output.i_width *
1620               p_pic->p->i_pixel_pitch;
1621
1622             p_pic->i_planes = 1;
1623             break;
1624
1625         default:
1626             /* Unknown chroma, tell the guy to get lost */
1627             msg_Err( p_vout, "never heard of chroma 0x%.8x (%4.4s)",
1628                      p_vout->output.i_chroma,
1629                      (char*)&p_vout->output.i_chroma );
1630             return VLC_EGENERIC;
1631     }
1632
1633     return VLC_SUCCESS;
1634 }
1635
1636 /*****************************************************************************
1637  * DirectXGetDDrawCaps: Probe the capabilities of the hardware
1638  *****************************************************************************
1639  * It is nice to know which features are supported by the hardware so we can
1640  * find ways to optimize our rendering.
1641  *****************************************************************************/
1642 static void DirectXGetDDrawCaps( vout_thread_t *p_vout )
1643 {
1644     DDCAPS ddcaps;
1645     HRESULT dxresult;
1646
1647     /* This is just an indication of whether or not we'll support overlay,
1648      * but with this test we don't know if we support YUV overlay */
1649     memset( &ddcaps, 0, sizeof( DDCAPS ));
1650     ddcaps.dwSize = sizeof(DDCAPS);
1651     dxresult = IDirectDraw2_GetCaps( p_vout->p_sys->p_ddobject,
1652                                      &ddcaps, NULL );
1653     if(dxresult != DD_OK )
1654     {
1655         msg_Warn( p_vout, "cannot get caps" );
1656     }
1657     else
1658     {
1659         vlc_bool_t bHasOverlay, bHasOverlayFourCC, bCanDeinterlace,
1660              bHasColorKey, bCanStretch, bCanBltFourcc,
1661              bAlignBoundarySrc, bAlignBoundaryDest,
1662              bAlignSizeSrc, bAlignSizeDest;
1663
1664         /* Determine if the hardware supports overlay surfaces */
1665         bHasOverlay = (ddcaps.dwCaps & DDCAPS_OVERLAY) ? 1 : 0;
1666         /* Determine if the hardware supports overlay surfaces */
1667         bHasOverlayFourCC = (ddcaps.dwCaps & DDCAPS_OVERLAYFOURCC) ? 1 : 0;
1668         /* Determine if the hardware supports overlay deinterlacing */
1669         bCanDeinterlace = (ddcaps.dwCaps & DDCAPS2_CANFLIPODDEVEN) ? 1 : 0;
1670         /* Determine if the hardware supports colorkeying */
1671         bHasColorKey = (ddcaps.dwCaps & DDCAPS_COLORKEY) ? 1 : 0;
1672         /* Determine if the hardware supports scaling of the overlay surface */
1673         bCanStretch = (ddcaps.dwCaps & DDCAPS_OVERLAYSTRETCH) ? 1 : 0;
1674         /* Determine if the hardware supports color conversion during a blit */
1675         bCanBltFourcc = (ddcaps.dwCaps & DDCAPS_BLTFOURCC) ? 1 : 0;
1676         /* Determine overlay source boundary alignment */
1677         bAlignBoundarySrc = (ddcaps.dwCaps & DDCAPS_ALIGNBOUNDARYSRC) ? 1 : 0;
1678         /* Determine overlay destination boundary alignment */
1679         bAlignBoundaryDest = (ddcaps.dwCaps & DDCAPS_ALIGNBOUNDARYDEST) ? 1:0;
1680         /* Determine overlay destination size alignment */
1681         bAlignSizeSrc = (ddcaps.dwCaps & DDCAPS_ALIGNSIZESRC) ? 1 : 0;
1682         /* Determine overlay destination size alignment */
1683         bAlignSizeDest = (ddcaps.dwCaps & DDCAPS_ALIGNSIZEDEST) ? 1 : 0;
1684  
1685         msg_Dbg( p_vout, "DirectDraw Capabilities: overlay=%i yuvoverlay=%i "
1686                          "can_deinterlace_overlay=%i colorkey=%i stretch=%i "
1687                          "bltfourcc=%i",
1688                          bHasOverlay, bHasOverlayFourCC, bCanDeinterlace,
1689                          bHasColorKey, bCanStretch, bCanBltFourcc );
1690
1691         if( bAlignBoundarySrc || bAlignBoundaryDest ||
1692             bAlignSizeSrc || bAlignSizeDest )
1693         {
1694             if( bAlignBoundarySrc ) p_vout->p_sys->i_align_src_boundary =
1695                 ddcaps.dwAlignBoundarySrc;
1696             if( bAlignBoundaryDest ) p_vout->p_sys->i_align_dest_boundary =
1697                 ddcaps.dwAlignBoundaryDest;
1698             if( bAlignSizeDest ) p_vout->p_sys->i_align_src_size =
1699                 ddcaps.dwAlignSizeSrc;
1700             if( bAlignSizeDest ) p_vout->p_sys->i_align_dest_size =
1701                 ddcaps.dwAlignSizeDest;
1702
1703             msg_Dbg( p_vout, "align_boundary_src=%i,%i "
1704                      "align_boundary_dest=%i,%i "
1705                      "align_size_src=%i,%i align_size_dest=%i,%i",
1706                      bAlignBoundarySrc, p_vout->p_sys->i_align_src_boundary,
1707                      bAlignBoundaryDest, p_vout->p_sys->i_align_dest_boundary,
1708                      bAlignSizeSrc, p_vout->p_sys->i_align_src_size,
1709                      bAlignSizeDest, p_vout->p_sys->i_align_dest_size );
1710         }
1711
1712         /* Don't ask for troubles */
1713         if( !bCanBltFourcc ) p_vout->p_sys->b_hw_yuv = FALSE;
1714     }
1715 }
1716
1717 /*****************************************************************************
1718  * DirectXLockSurface: Lock surface and get picture data pointer
1719  *****************************************************************************
1720  * This function locks a surface and get the surface descriptor which amongst
1721  * other things has the pointer to the picture data.
1722  *****************************************************************************/
1723 static int DirectXLockSurface( vout_thread_t *p_vout, picture_t *p_pic )
1724 {
1725     HRESULT dxresult;
1726
1727     /* Lock the surface to get a valid pointer to the picture buffer */
1728     memset( &p_pic->p_sys->ddsd, 0, sizeof( DDSURFACEDESC ));
1729     p_pic->p_sys->ddsd.dwSize = sizeof(DDSURFACEDESC);
1730     dxresult = IDirectDrawSurface2_Lock( p_pic->p_sys->p_surface,
1731                                          NULL, &p_pic->p_sys->ddsd,
1732                                          DDLOCK_NOSYSLOCK | DDLOCK_WAIT,
1733                                          NULL );
1734     if( dxresult != DD_OK )
1735     {
1736         if( dxresult == DDERR_INVALIDPARAMS )
1737         {
1738             /* DirectX 3 doesn't support the DDLOCK_NOSYSLOCK flag, resulting
1739              * in an invalid params error */
1740             dxresult = IDirectDrawSurface2_Lock( p_pic->p_sys->p_surface, NULL,
1741                                              &p_pic->p_sys->ddsd,
1742                                              DDLOCK_WAIT, NULL);
1743         }
1744         if( dxresult == DDERR_SURFACELOST )
1745         {
1746             /* Your surface can be lost so be sure
1747              * to check this and restore it if needed */
1748
1749             /* When using overlays with back-buffers, we need to restore
1750              * the front buffer so the back-buffers get restored as well. */
1751             if( p_vout->p_sys->b_using_overlay  )
1752                 IDirectDrawSurface2_Restore( p_pic->p_sys->p_front_surface );
1753             else
1754                 IDirectDrawSurface2_Restore( p_pic->p_sys->p_surface );
1755
1756             dxresult = IDirectDrawSurface2_Lock( p_pic->p_sys->p_surface, NULL,
1757                                                  &p_pic->p_sys->ddsd,
1758                                                  DDLOCK_WAIT, NULL);
1759             if( dxresult == DDERR_SURFACELOST )
1760                 msg_Dbg( p_vout, "DirectXLockSurface: DDERR_SURFACELOST" );
1761         }
1762         if( dxresult != DD_OK )
1763         {
1764             return VLC_EGENERIC;
1765         }
1766     }
1767
1768     /* Now we have a pointer to the surface memory, we can update our picture
1769      * structure. */
1770     if( UpdatePictureStruct( p_vout, p_pic, p_vout->output.i_chroma )
1771         != VLC_SUCCESS )
1772     {
1773         DirectXUnlockSurface( p_vout, p_pic );
1774         return VLC_EGENERIC;
1775     }
1776     else
1777         return VLC_SUCCESS;
1778 }
1779
1780 /*****************************************************************************
1781  * DirectXUnlockSurface: Unlock a surface locked by DirectXLockSurface().
1782  *****************************************************************************/
1783 static int DirectXUnlockSurface( vout_thread_t *p_vout, picture_t *p_pic )
1784 {
1785     /* Unlock the Surface */
1786     if( IDirectDrawSurface2_Unlock( p_pic->p_sys->p_surface, NULL ) == DD_OK )
1787         return VLC_SUCCESS;
1788     else
1789         return VLC_EGENERIC;
1790 }
1791
1792 /*****************************************************************************
1793  * DirectXFindColorkey: Finds out the 32bits RGB pixel value of the colorkey
1794  *****************************************************************************/
1795 static DWORD DirectXFindColorkey( vout_thread_t *p_vout, uint32_t i_color )
1796 {
1797     DDSURFACEDESC ddsd;
1798     HRESULT dxresult;
1799     COLORREF i_rgb = 0;
1800     uint32_t i_pixel_backup;
1801     HDC hdc;
1802
1803     ddsd.dwSize = sizeof(ddsd);
1804     dxresult = IDirectDrawSurface2_Lock( p_vout->p_sys->p_display, NULL,
1805                                          &ddsd, DDLOCK_WAIT, NULL );
1806     if( dxresult != DD_OK ) return 0;
1807
1808     i_pixel_backup = *(uint32_t *)ddsd.lpSurface;
1809
1810     switch( ddsd.ddpfPixelFormat.dwRGBBitCount )
1811     {
1812     case 4:
1813         *(uint8_t *)ddsd.lpSurface = 0x11;
1814         break;
1815     case 8:
1816         *(uint8_t *)ddsd.lpSurface = 0x01;
1817         break;
1818     case 16:
1819         *(uint16_t *)ddsd.lpSurface = 0x01;
1820         break;
1821     default:
1822         *(uint32_t *)ddsd.lpSurface = 0x01;
1823         break;
1824     }
1825
1826     IDirectDrawSurface2_Unlock( p_vout->p_sys->p_display, NULL );
1827
1828     if( IDirectDrawSurface2_GetDC( p_vout->p_sys->p_display, &hdc ) == DD_OK )
1829     {
1830         i_rgb = GetPixel( hdc, 0, 0 );
1831         IDirectDrawSurface2_ReleaseDC( p_vout->p_sys->p_display, hdc );
1832     }
1833
1834     ddsd.dwSize = sizeof(ddsd);
1835     dxresult = IDirectDrawSurface2_Lock( p_vout->p_sys->p_display, NULL,
1836                                          &ddsd, DDLOCK_WAIT, NULL );
1837     if( dxresult != DD_OK ) return i_rgb;
1838
1839     *(uint32_t *)ddsd.lpSurface = i_pixel_backup;
1840
1841     IDirectDrawSurface2_Unlock( p_vout->p_sys->p_display, NULL );
1842
1843     return i_rgb;
1844 }
1845
1846 /*****************************************************************************
1847  * config variable callback
1848  *****************************************************************************/
1849 BOOL WINAPI DirectXEnumCallback2( GUID* p_guid, LPTSTR psz_desc,
1850                                   LPTSTR psz_drivername, VOID* p_context,
1851                                   HMONITOR hmon )
1852 {
1853     module_config_t *p_item = (module_config_t *)p_context;
1854
1855     p_item->ppsz_list =
1856         (char **)realloc( p_item->ppsz_list,
1857                           (p_item->i_list+2) * sizeof(char *) );
1858     p_item->ppsz_list_text =
1859         (char **)realloc( p_item->ppsz_list_text,
1860                           (p_item->i_list+2) * sizeof(char *) );
1861
1862     p_item->ppsz_list[p_item->i_list] = strdup( psz_drivername );
1863     p_item->ppsz_list_text[p_item->i_list] = NULL;
1864     p_item->i_list++;
1865     p_item->ppsz_list[p_item->i_list] = NULL;
1866     p_item->ppsz_list_text[p_item->i_list] = NULL;
1867
1868     return TRUE; /* Keep enumerating */
1869 }
1870
1871 static int FindDevicesCallback( vlc_object_t *p_this, char const *psz_name,
1872                                vlc_value_t newval, vlc_value_t oldval, void *d)
1873 {
1874     HRESULT (WINAPI *OurDirectDrawEnumerateEx)( LPDDENUMCALLBACKEXA, LPVOID,
1875                                                 DWORD );
1876     HINSTANCE hddraw_dll;
1877
1878     module_config_t *p_item;
1879     int i;
1880
1881     p_item = config_FindConfig( p_this, psz_name );
1882     if( !p_item ) return VLC_SUCCESS;
1883
1884     /* Clear-up the current list */
1885     if( p_item->i_list )
1886     {
1887         /* Keep the first entry */
1888         for( i = 1; i < p_item->i_list; i++ )
1889         {
1890             free( p_item->ppsz_list[i] );
1891             free( p_item->ppsz_list_text[i] );
1892         }
1893         /* TODO: Remove when no more needed */
1894         p_item->ppsz_list[i] = NULL;
1895         p_item->ppsz_list_text[i] = NULL;
1896     }
1897     p_item->i_list = 1;
1898
1899     /* Load direct draw DLL */
1900     hddraw_dll = LoadLibrary("DDRAW.DLL");
1901     if( hddraw_dll == NULL ) return VLC_SUCCESS;
1902
1903     OurDirectDrawEnumerateEx =
1904       (void *)GetProcAddress( hddraw_dll, "DirectDrawEnumerateExA" );
1905
1906     if( OurDirectDrawEnumerateEx )
1907     {
1908         /* Enumerate displays */
1909         OurDirectDrawEnumerateEx( DirectXEnumCallback2, p_item,
1910                                   DDENUM_ATTACHEDSECONDARYDEVICES );
1911     }
1912
1913     FreeLibrary( hddraw_dll );
1914
1915     return VLC_SUCCESS;
1916 }