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