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