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