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