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