]> git.sesse.net Git - vlc/blob - modules/access/dshow/dshow.cpp
macosx: fixed menubar appearance in fullscreen mode by partially reverting [46c93c9cc...
[vlc] / modules / access / dshow / dshow.cpp
1 /*****************************************************************************
2  * dshow.cpp : DirectShow access module for vlc
3  *****************************************************************************
4  * Copyright (C) 2002, 2003 the VideoLAN team
5  * $Id$
6  *
7  * Author: Gildas Bazin <gbazin@videolan.org>
8  *         Damien Fouilleul <damienf@videolan.org>
9  *
10  * This program is free software; you can redistribute it and/or modify
11  * it under the terms of the GNU General Public License as published by
12  * the Free Software Foundation; either version 2 of the License, or
13  * (at your option) any later version.
14  *
15  * This program is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18  * GNU General Public License for more details.
19  *
20  * You should have received a copy of the GNU General Public License
21  * along with this program; if not, write to the Free Software
22  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
23  *****************************************************************************/
24
25 /*****************************************************************************
26  * Preamble
27  *****************************************************************************/
28
29 #ifdef HAVE_CONFIG_H
30 # include "config.h"
31 #endif
32
33 #define __STDC_FORMAT_MACROS 1
34 #include <inttypes.h>
35
36 #include <vlc_common.h>
37 #include <vlc_plugin.h>
38 #include <vlc_input.h>
39 #include <vlc_access.h>
40 #include <vlc_demux.h>
41 #include <vlc_vout.h>
42 #include <vlc_dialog.h>
43 #include <vlc_charset.h>
44
45 #include "common.h"
46 #include "filter.h"
47
48 /*****************************************************************************
49  * Access: local prototypes
50  *****************************************************************************/
51 static block_t *ReadCompressed( access_t * );
52 static int AccessControl ( access_t *, int, va_list );
53
54 static int Demux       ( demux_t * );
55 static int DemuxControl( demux_t *, int, va_list );
56
57 static int OpenDevice( vlc_object_t *, access_sys_t *, string, bool );
58 static IBaseFilter *FindCaptureDevice( vlc_object_t *, string *,
59                                        list<string> *, bool );
60 static size_t EnumDeviceCaps( vlc_object_t *, IBaseFilter *,
61                               int, int, int, int, int, int,
62                               AM_MEDIA_TYPE *mt, size_t );
63 static bool ConnectFilters( vlc_object_t *, access_sys_t *,
64                             IBaseFilter *, CaptureFilter * );
65 static int FindDevicesCallback( vlc_object_t *, char const *,
66                                 vlc_value_t, vlc_value_t, void * );
67 static int ConfigDevicesCallback( vlc_object_t *, char const *,
68                                   vlc_value_t, vlc_value_t, void * );
69
70 static void ShowPropertyPage( IUnknown * );
71 static void ShowDeviceProperties( vlc_object_t *, ICaptureGraphBuilder2 *,
72                                   IBaseFilter *, bool );
73 static void ShowTunerProperties( vlc_object_t *, ICaptureGraphBuilder2 *,
74                                  IBaseFilter *, bool );
75 static void ConfigTuner( vlc_object_t *, ICaptureGraphBuilder2 *,
76                          IBaseFilter * );
77
78 /*****************************************************************************
79  * Module descriptor
80  *****************************************************************************/
81 static const char *const ppsz_vdev[] = { "", "none" };
82 static const char *const ppsz_vdev_text[] = { N_("Default"), N_("None") };
83 static const char *const ppsz_adev[] = { "", "none" };
84 static const char *const ppsz_adev_text[] = { N_("Default"), N_("None") };
85 static const int pi_tuner_input[] = { 0, 1, 2 };
86 static const char *const ppsz_tuner_input_text[] =
87     {N_("Default"), N_("Cable"), N_("Antenna")};
88 static const int pi_amtuner_mode[]  = { AMTUNER_MODE_DEFAULT,
89                                  AMTUNER_MODE_TV,
90                                  AMTUNER_MODE_FM_RADIO,
91                                  AMTUNER_MODE_AM_RADIO,
92                                  AMTUNER_MODE_DSS };
93 static const char *const ppsz_amtuner_mode_text[] = { N_("Default"),
94                                           N_("TV"),
95                                           N_("FM radio"),
96                                           N_("AM radio"),
97                                           N_("DSS") };
98
99 #define CACHING_TEXT N_("Caching value in ms")
100 #define CACHING_LONGTEXT N_( \
101     "Caching value for DirectShow streams. " \
102     "This value should be set in milliseconds." )
103 #define VDEV_TEXT N_("Video device name")
104 #define VDEV_LONGTEXT N_( \
105     "Name of the video device that will be used by the " \
106     "DirectShow plugin. If you don't specify anything, the default device " \
107     "will be used.")
108 #define ADEV_TEXT N_("Audio device name")
109 #define ADEV_LONGTEXT N_( \
110     "Name of the audio device that will be used by the " \
111     "DirectShow plugin. If you don't specify anything, the default device " \
112     "will be used. ")
113 #define SIZE_TEXT N_("Video size")
114 #define SIZE_LONGTEXT N_( \
115     "Size of the video that will be displayed by the " \
116     "DirectShow plugin. If you don't specify anything the default size for " \
117     "your device will be used. You can specify a standard size (cif, d1, ...) or <width>x<height>.")
118 #define CHROMA_TEXT N_("Video input chroma format")
119 #define CHROMA_LONGTEXT N_( \
120     "Force the DirectShow video input to use a specific chroma format " \
121     "(eg. I420 (default), RV24, etc.)")
122 #define FPS_TEXT N_("Video input frame rate")
123 #define FPS_LONGTEXT N_( \
124     "Force the DirectShow video input to use a specific frame rate" \
125     "(eg. 0 means default, 25, 29.97, 50, 59.94, etc.)")
126 #define CONFIG_TEXT N_("Device properties")
127 #define CONFIG_LONGTEXT N_( \
128     "Show the properties dialog of the selected device before starting the " \
129     "stream.")
130 #define TUNER_TEXT N_("Tuner properties")
131 #define TUNER_LONGTEXT N_( \
132     "Show the tuner properties [channel selection] page." )
133 #define CHANNEL_TEXT N_("Tuner TV Channel")
134 #define CHANNEL_LONGTEXT N_( \
135     "Set the TV channel the tuner will set to " \
136     "(0 means default)." )
137 #define COUNTRY_TEXT N_("Tuner country code")
138 #define COUNTRY_LONGTEXT N_( \
139     "Set the tuner country code that establishes the current " \
140     "channel-to-frequency mapping (0 means default)." )
141 #define TUNER_INPUT_TEXT N_("Tuner input type")
142 #define TUNER_INPUT_LONGTEXT N_( \
143     "Select the tuner input type (Cable/Antenna)." )
144 #define VIDEO_IN_TEXT N_("Video input pin")
145 #define VIDEO_IN_LONGTEXT N_( \
146   "Select the video input source, such as composite, s-video, " \
147   "or tuner. Since these settings are hardware-specific, you should find good " \
148   "settings in the \"Device config\" area, and use those numbers here. -1 " \
149   "means that settings will not be changed.")
150 #define AUDIO_IN_TEXT N_("Audio input pin")
151 #define AUDIO_IN_LONGTEXT N_( \
152   "Select the audio input source. See the \"video input\" option." )
153 #define VIDEO_OUT_TEXT N_("Video output pin")
154 #define VIDEO_OUT_LONGTEXT N_( \
155   "Select the video output type. See the \"video input\" option." )
156 #define AUDIO_OUT_TEXT N_("Audio output pin")
157 #define AUDIO_OUT_LONGTEXT N_( \
158   "Select the audio output type. See the \"video input\" option." )
159
160 #define AMTUNER_MODE_TEXT N_("AM Tuner mode")
161 #define AMTUNER_MODE_LONGTEXT N_( \
162     "AM Tuner mode. Can be one of Default (0), TV (1)," \
163      "AM Radio (2), FM Radio (3) or DSS (4).")
164
165 #define AUDIO_CHANNELS_TEXT N_("Number of audio channels")
166 #define AUDIO_CHANNELS_LONGTEXT N_( \
167     "Select audio input format with the given number of audio channels (if non 0)" )
168
169 #define AUDIO_SAMPLERATE_TEXT N_("Audio sample rate")
170 #define AUDIO_SAMPLERATE_LONGTEXT N_( \
171     "Select audio input format with the given sample rate (if non 0)" )
172
173 #define AUDIO_BITSPERSAMPLE_TEXT N_("Audio bits per sample")
174 #define AUDIO_BITSPERSAMPLE_LONGTEXT N_( \
175     "Select audio input format with the given bits/sample (if non 0)" )
176
177 static int  CommonOpen ( vlc_object_t *, access_sys_t *, bool );
178 static void CommonClose( vlc_object_t *, access_sys_t * );
179
180 static int  AccessOpen ( vlc_object_t * );
181 static void AccessClose( vlc_object_t * );
182
183 static int  DemuxOpen  ( vlc_object_t * );
184 static void DemuxClose ( vlc_object_t * );
185
186 vlc_module_begin ()
187     set_shortname( N_("DirectShow") )
188     set_description( N_("DirectShow input") )
189     set_category( CAT_INPUT )
190     set_subcategory( SUBCAT_INPUT_ACCESS )
191     add_integer( "dshow-caching", (mtime_t)(0.2*CLOCK_FREQ) / 1000, NULL,
192                  CACHING_TEXT, CACHING_LONGTEXT, true )
193
194     add_string( "dshow-vdev", NULL, NULL, VDEV_TEXT, VDEV_LONGTEXT, false)
195         change_string_list( ppsz_vdev, ppsz_vdev_text, FindDevicesCallback )
196         change_action_add( FindDevicesCallback, N_("Refresh list") )
197         change_action_add( ConfigDevicesCallback, N_("Configure") )
198
199     add_string( "dshow-adev", NULL, NULL, ADEV_TEXT, ADEV_LONGTEXT, false)
200         change_string_list( ppsz_adev, ppsz_adev_text, FindDevicesCallback )
201         change_action_add( FindDevicesCallback, N_("Refresh list") )
202         change_action_add( ConfigDevicesCallback, N_("Configure") )
203
204     add_string( "dshow-size", NULL, NULL, SIZE_TEXT, SIZE_LONGTEXT, false)
205
206     add_string( "dshow-chroma", NULL, NULL, CHROMA_TEXT, CHROMA_LONGTEXT, true )
207
208     add_float( "dshow-fps", 0.0f, NULL, FPS_TEXT, FPS_LONGTEXT, true )
209
210     add_bool( "dshow-config", false, NULL, CONFIG_TEXT, CONFIG_LONGTEXT, true )
211
212     add_bool( "dshow-tuner", false, NULL, TUNER_TEXT, TUNER_LONGTEXT, true )
213
214     add_integer( "dshow-tuner-channel", 0, NULL, CHANNEL_TEXT, CHANNEL_LONGTEXT,
215                 true )
216
217     add_integer( "dshow-tuner-country", 0, NULL, COUNTRY_TEXT, COUNTRY_LONGTEXT,
218                 true )
219
220     add_integer( "dshow-tuner-input", 0, NULL, TUNER_INPUT_TEXT,
221                  TUNER_INPUT_LONGTEXT, true )
222         change_integer_list( pi_tuner_input, ppsz_tuner_input_text, NULL )
223
224     add_integer( "dshow-video-input",  -1, NULL, VIDEO_IN_TEXT,
225                  VIDEO_IN_LONGTEXT, true )
226
227     add_integer( "dshow-video-output", -1, NULL, VIDEO_OUT_TEXT,
228                  VIDEO_OUT_LONGTEXT, true )
229
230     add_integer( "dshow-audio-input",  -1, NULL, AUDIO_IN_TEXT,
231                  AUDIO_IN_LONGTEXT, true )
232
233     add_integer( "dshow-audio-output", -1, NULL, AUDIO_OUT_TEXT,
234                  AUDIO_OUT_LONGTEXT, true )
235
236     add_integer( "dshow-amtuner-mode", AMTUNER_MODE_TV, NULL,
237                 AMTUNER_MODE_TEXT, AMTUNER_MODE_LONGTEXT, false)
238         change_integer_list( pi_amtuner_mode, ppsz_amtuner_mode_text, NULL )
239
240     add_integer( "dshow-audio-channels", 0, NULL, AUDIO_CHANNELS_TEXT,
241                  AUDIO_CHANNELS_LONGTEXT, true )
242     add_integer( "dshow-audio-samplerate", 0, NULL, AUDIO_SAMPLERATE_TEXT,
243                  AUDIO_SAMPLERATE_LONGTEXT, true )
244     add_integer( "dshow-audio-bitspersample", 0, NULL, AUDIO_BITSPERSAMPLE_TEXT,
245                  AUDIO_BITSPERSAMPLE_LONGTEXT, true )
246
247     add_shortcut( "dshow" )
248     set_capability( "access_demux", 0 )
249     set_callbacks( DemuxOpen, DemuxClose )
250
251     add_submodule ()
252     set_description( N_("DirectShow input") )
253     add_shortcut( "dshow" )
254     set_capability( "access", 0 )
255     set_callbacks( AccessOpen, AccessClose )
256
257 vlc_module_end ()
258
259 /*****************************************************************************
260  * DirectShow elementary stream descriptor
261  *****************************************************************************/
262 typedef struct dshow_stream_t
263 {
264     string          devicename;
265     IBaseFilter     *p_device_filter;
266     CaptureFilter   *p_capture_filter;
267     AM_MEDIA_TYPE   mt;
268
269     union
270     {
271       VIDEOINFOHEADER video;
272       WAVEFORMATEX    audio;
273
274     } header;
275
276     int             i_fourcc;
277     es_out_id_t     *p_es;
278
279     bool      b_pts;
280
281     deque<VLCMediaSample> samples_queue;
282 } dshow_stream_t;
283
284 /*****************************************************************************
285  * DirectShow utility functions
286  *****************************************************************************/
287 static void CreateDirectShowGraph( access_sys_t *p_sys )
288 {
289     p_sys->i_crossbar_route_depth = 0;
290
291     /* Create directshow filter graph */
292     if( SUCCEEDED( CoCreateInstance( CLSID_FilterGraph, 0, CLSCTX_INPROC,
293                        (REFIID)IID_IFilterGraph, (void **)&p_sys->p_graph) ) )
294     {
295         /* Create directshow capture graph builder if available */
296         if( SUCCEEDED( CoCreateInstance( CLSID_CaptureGraphBuilder2, 0,
297                          CLSCTX_INPROC, (REFIID)IID_ICaptureGraphBuilder2,
298                          (void **)&p_sys->p_capture_graph_builder2 ) ) )
299         {
300             p_sys->p_capture_graph_builder2->
301                 SetFiltergraph((IGraphBuilder *)p_sys->p_graph);
302         }
303
304         p_sys->p_graph->QueryInterface( IID_IMediaControl,
305                                         (void **)&p_sys->p_control );
306     }
307 }
308
309 static void DeleteDirectShowGraph( access_sys_t *p_sys )
310 {
311     DeleteCrossbarRoutes( p_sys );
312
313     /* Remove filters from graph */
314     for( int i = 0; i < p_sys->i_streams; i++ )
315     {
316         p_sys->p_graph->RemoveFilter( p_sys->pp_streams[i]->p_capture_filter );
317         p_sys->p_graph->RemoveFilter( p_sys->pp_streams[i]->p_device_filter );
318         p_sys->pp_streams[i]->p_capture_filter->Release();
319         p_sys->pp_streams[i]->p_device_filter->Release();
320     }
321
322     /* Release directshow objects */
323     if( p_sys->p_control )
324     {
325         p_sys->p_control->Release();
326         p_sys->p_control = NULL;
327     }
328     if( p_sys->p_capture_graph_builder2 )
329     {
330         p_sys->p_capture_graph_builder2->Release();
331         p_sys->p_capture_graph_builder2 = NULL;
332     }
333
334     if( p_sys->p_graph )
335     {
336         p_sys->p_graph->Release();
337         p_sys->p_graph = NULL;
338     }
339 }
340
341 /*****************************************************************************
342  * CommonOpen: open direct show device
343  *****************************************************************************/
344 static int CommonOpen( vlc_object_t *p_this, access_sys_t *p_sys,
345                        bool b_access_demux )
346 {
347     vlc_value_t  val;
348     int i;
349
350     /* Get/parse options and open device(s) */
351     string vdevname, adevname;
352     int i_width = 0, i_height = 0, i_chroma = 0;
353     bool b_use_audio = true;
354     bool b_use_video = true;
355
356     /* Initialize OLE/COM */
357     CoInitialize( 0 );
358
359     var_Create( p_this, "dshow-config", VLC_VAR_BOOL | VLC_VAR_DOINHERIT );
360     var_Create( p_this, "dshow-tuner", VLC_VAR_BOOL | VLC_VAR_DOINHERIT );
361     var_Create( p_this, "dshow-vdev", VLC_VAR_STRING | VLC_VAR_DOINHERIT );
362     var_Get( p_this, "dshow-vdev", &val );
363     if( val.psz_string )
364     {
365         msg_Dbg( p_this, "dshow-vdev: %s", val.psz_string ) ;
366         /* skip none device */
367         if ( strncasecmp( val.psz_string, "none", 4 ) != 0 )
368             vdevname = string( val.psz_string );
369         else
370             b_use_video = false ;
371     }
372     free( val.psz_string );
373
374     var_Create( p_this, "dshow-adev", VLC_VAR_STRING | VLC_VAR_DOINHERIT );
375     var_Get( p_this, "dshow-adev", &val );
376     if( val.psz_string )
377     {
378         msg_Dbg( p_this, "dshow-adev: %s", val.psz_string ) ;
379         /* skip none device */
380         if ( strncasecmp( val.psz_string, "none", 4 ) != 0 )
381             adevname = string( val.psz_string );
382         else
383             b_use_audio = false ;
384     }
385     free( val.psz_string );
386
387     static struct {const char *psz_size; int  i_width; int  i_height;} size_table[] =
388     { { "subqcif", 128, 96 }, { "qsif", 160, 120 }, { "qcif", 176, 144 },
389       { "sif", 320, 240 }, { "cif", 352, 288 }, { "d1", 640, 480 },
390       { 0, 0, 0 },
391     };
392
393     var_Create( p_this, "dshow-size", VLC_VAR_STRING | VLC_VAR_DOINHERIT );
394     var_Get( p_this, "dshow-size", &val );
395     if( val.psz_string && *val.psz_string )
396     {
397         for( i = 0; size_table[i].psz_size; i++ )
398         {
399             if( !strcmp( val.psz_string, size_table[i].psz_size ) )
400             {
401                 i_width = size_table[i].i_width;
402                 i_height = size_table[i].i_height;
403                 break;
404             }
405         }
406         if( !size_table[i].psz_size ) /* Try to parse "WidthxHeight" */
407         {
408             char *psz_parser;
409             i_width = strtol( val.psz_string, &psz_parser, 0 );
410             if( *psz_parser == 'x' || *psz_parser == 'X')
411             {
412                 i_height = strtol( psz_parser + 1, &psz_parser, 0 );
413             }
414             msg_Dbg( p_this, "width x height %dx%d", i_width, i_height );
415         }
416     }
417     free( val.psz_string );
418
419     p_sys->b_chroma = false;
420     var_Create( p_this, "dshow-chroma", VLC_VAR_STRING | VLC_VAR_DOINHERIT );
421     var_Get( p_this, "dshow-chroma", &val );
422     if( val.psz_string && strlen( val.psz_string ) >= 4 )
423     {
424         i_chroma = VLC_FOURCC( val.psz_string[0], val.psz_string[1],
425                                val.psz_string[2], val.psz_string[3] );
426         p_sys->b_chroma = true;
427     }
428     free( val.psz_string );
429
430     var_Create( p_this, "dshow-fps", VLC_VAR_FLOAT | VLC_VAR_DOINHERIT );
431     var_Create( p_this, "dshow-tuner-channel",
432                 VLC_VAR_INTEGER | VLC_VAR_DOINHERIT );
433     var_Create( p_this, "dshow-tuner-country",
434                 VLC_VAR_INTEGER | VLC_VAR_DOINHERIT );
435     var_Create( p_this, "dshow-tuner-input",
436                 VLC_VAR_INTEGER | VLC_VAR_DOINHERIT );
437
438     var_Create( p_this, "dshow-amtuner-mode",
439                 VLC_VAR_INTEGER | VLC_VAR_DOINHERIT );
440
441     var_Create( p_this, "dshow-caching", VLC_VAR_INTEGER | VLC_VAR_DOINHERIT );
442
443     var_Create( p_this, "dshow-video-input", VLC_VAR_INTEGER | VLC_VAR_DOINHERIT );
444     var_Create( p_this, "dshow-audio-input", VLC_VAR_INTEGER | VLC_VAR_DOINHERIT );
445     var_Create( p_this, "dshow-video-output", VLC_VAR_INTEGER | VLC_VAR_DOINHERIT );
446     var_Create( p_this, "dshow-audio-output", VLC_VAR_INTEGER | VLC_VAR_DOINHERIT );
447
448     /* Initialize some data */
449     p_sys->i_streams = 0;
450     p_sys->pp_streams = NULL;
451     p_sys->i_width = i_width;
452     p_sys->i_height = i_height;
453     p_sys->i_chroma = i_chroma;
454
455     p_sys->p_graph = NULL;
456     p_sys->p_capture_graph_builder2 = NULL;
457     p_sys->p_control = NULL;
458
459     /* Build directshow graph */
460     CreateDirectShowGraph( p_sys );
461
462     vlc_mutex_init( &p_sys->lock );
463     vlc_cond_init( &p_sys->wait );
464
465     if( !b_use_video && !b_use_audio )
466     {
467         dialog_Fatal( p_this, _("Capture failed"),
468                         _("No video or audio device selected.") );
469         return VLC_EGENERIC ;
470     }
471
472     if( !b_use_video )
473         msg_Dbg( p_this, "skipping video device" ) ;
474     bool b_err_video = false ;
475
476     if( b_use_video && OpenDevice( p_this, p_sys, vdevname, 0 ) != VLC_SUCCESS )
477     {
478         msg_Err( p_this, "can't open video device");
479         b_err_video = true ;
480     }
481
482     if ( b_use_video && !b_err_video )
483     {
484         /* Check if we can handle the demuxing ourselves or need to spawn
485          * a demuxer module */
486         dshow_stream_t *p_stream = p_sys->pp_streams[p_sys->i_streams-1];
487
488         if( p_stream->mt.majortype == MEDIATYPE_Video )
489         {
490             if( /* Raw DV stream */
491                 p_stream->i_fourcc == VLC_FOURCC('d','v','s','l') ||
492                 p_stream->i_fourcc == VLC_FOURCC('d','v','s','d') ||
493                 p_stream->i_fourcc == VLC_FOURCC('d','v','h','d') ||
494                 /* Raw MPEG video stream */
495                 p_stream->i_fourcc == VLC_FOURCC('m','p','2','v') )
496             {
497                 b_use_audio = false;
498
499                 if( b_access_demux )
500                 {
501                     /* Let the access (only) take care of that */
502                     return VLC_EGENERIC;
503                 }
504             }
505         }
506
507         if( p_stream->mt.majortype == MEDIATYPE_Stream )
508         {
509             b_use_audio = false;
510
511             if( b_access_demux )
512             {
513                 /* Let the access (only) take care of that */
514                 return VLC_EGENERIC;
515             }
516
517             var_Get( p_this, "dshow-tuner", &val );
518             if( val.b_bool )
519             {
520                 /* FIXME: we do MEDIATYPE_Stream here so we don't do
521                  * it twice. */
522                 ShowTunerProperties( p_this, p_sys->p_capture_graph_builder2,
523                                      p_stream->p_device_filter, 0 );
524             }
525         }
526     }
527
528     if( !b_use_audio )
529         msg_Dbg( p_this, "skipping audio device") ;
530
531     bool b_err_audio = false ;
532
533     if( b_use_audio && OpenDevice( p_this, p_sys, adevname, 1 ) != VLC_SUCCESS )
534     {
535         msg_Err( p_this, "can't open audio device");
536         b_err_audio = true ;
537     }
538
539     if( ( b_use_video && b_err_video && b_use_audio && b_err_audio ) ||
540         ( !b_use_video && b_use_audio && b_err_audio ) ||
541         ( b_use_video && !b_use_audio && b_err_video ) )
542     {
543         msg_Err( p_this, "FATAL: could not open ANY device" ) ;
544         dialog_Fatal( p_this,  _("Capture failed"),
545                         _("VLC cannot open ANY capture device."
546                           "Check the error log for details.") );
547         return VLC_EGENERIC ;
548     }
549
550     for( i = p_sys->i_crossbar_route_depth-1; i >= 0 ; --i )
551     {
552             var_Get( p_this, "dshow-video-input", &val );
553             if( val.i_int >= 0 )
554                     p_sys->crossbar_routes[i].VideoInputIndex=val.i_int;
555             var_Get( p_this, "dshow-video-output", &val );
556             if( val.i_int >= 0 )
557                     p_sys->crossbar_routes[i].VideoOutputIndex=val.i_int;
558             var_Get( p_this, "dshow-audio-input", &val );
559             if( val.i_int >= 0 )
560                     p_sys->crossbar_routes[i].AudioInputIndex=val.i_int;
561             var_Get( p_this, "dshow-audio-output", &val );
562             if( val.i_int >= 0 )
563                     p_sys->crossbar_routes[i].AudioOutputIndex=val.i_int;
564
565         IAMCrossbar *pXbar = p_sys->crossbar_routes[i].pXbar;
566         LONG VideoInputIndex = p_sys->crossbar_routes[i].VideoInputIndex;
567         LONG VideoOutputIndex = p_sys->crossbar_routes[i].VideoOutputIndex;
568         LONG AudioInputIndex = p_sys->crossbar_routes[i].AudioInputIndex;
569         LONG AudioOutputIndex = p_sys->crossbar_routes[i].AudioOutputIndex;
570
571         if( SUCCEEDED(pXbar->Route(VideoOutputIndex, VideoInputIndex)) )
572         {
573             msg_Dbg( p_this, "crossbar at depth %d, routed video "
574                      "output %ld to video input %ld", i, VideoOutputIndex,
575                      VideoInputIndex );
576
577             if( AudioOutputIndex != -1 && AudioInputIndex != -1 )
578             {
579                 if( SUCCEEDED( pXbar->Route(AudioOutputIndex,
580                                             AudioInputIndex)) )
581                 {
582                     msg_Dbg(p_this, "crossbar at depth %d, routed audio "
583                             "output %ld to audio input %ld", i,
584                             AudioOutputIndex, AudioInputIndex );
585                 }
586             }
587         }
588         else
589             msg_Err( p_this, "crossbar at depth %d could not route video "
590                      "output %ld to input %ld", i, VideoOutputIndex, VideoInputIndex );
591     }
592
593     /*
594     ** Show properties pages from other filters in graph
595     */
596     var_Get( p_this, "dshow-config", &val );
597     if( val.b_bool )
598     {
599         for( i = p_sys->i_crossbar_route_depth-1; i >= 0 ; --i )
600         {
601             IAMCrossbar *pXbar = p_sys->crossbar_routes[i].pXbar;
602             IBaseFilter *p_XF;
603
604             if( SUCCEEDED( pXbar->QueryInterface( IID_IBaseFilter,
605                                                   (void **)&p_XF ) ) )
606             {
607                 ShowPropertyPage( p_XF );
608                 p_XF->Release();
609             }
610         }
611     }
612
613     /* Initialize some data */
614     p_sys->i_current_stream = 0;
615
616     if( !p_sys->i_streams ) return VLC_EGENERIC;
617
618     return VLC_SUCCESS;
619 }
620
621 /*****************************************************************************
622  * DemuxOpen: open direct show device as an access_demux module
623  *****************************************************************************/
624 static int DemuxOpen( vlc_object_t *p_this )
625 {
626     demux_t      *p_demux = (demux_t *)p_this;
627     access_sys_t *p_sys;
628     int i;
629
630     p_sys = (access_sys_t*)calloc( 1, sizeof( access_sys_t ) );
631     if( !p_sys )
632         return VLC_ENOMEM;
633     p_demux->p_sys = (demux_sys_t *)p_sys;
634
635     if( CommonOpen( p_this, p_sys, true ) != VLC_SUCCESS )
636     {
637         CommonClose( p_this, p_sys );
638         return VLC_EGENERIC;
639     }
640
641     /* Everything is ready. Let's rock baby */
642     msg_Dbg( p_this, "Playing...");
643     p_sys->p_control->Run();
644
645     p_demux->pf_demux   = Demux;
646     p_demux->pf_control = DemuxControl;
647     p_demux->info.i_update = 0;
648     p_demux->info.i_title = 0;
649     p_demux->info.i_seekpoint = 0;
650
651     for( i = 0; i < p_sys->i_streams; i++ )
652     {
653         dshow_stream_t *p_stream = p_sys->pp_streams[i];
654         es_format_t fmt;
655
656         if( p_stream->mt.majortype == MEDIATYPE_Video )
657         {
658             es_format_Init( &fmt, VIDEO_ES, p_stream->i_fourcc );
659
660             fmt.video.i_width  = p_stream->header.video.bmiHeader.biWidth;
661             fmt.video.i_height = p_stream->header.video.bmiHeader.biHeight;
662             fmt.video.i_aspect = 4 * VOUT_ASPECT_FACTOR / 3;
663
664             if( !p_stream->header.video.bmiHeader.biCompression )
665             {
666                 /* RGB DIB are coded from bottom to top */
667                 fmt.video.i_height = (unsigned int)(-(int)fmt.video.i_height);
668             }
669
670             /* Setup rgb mask for RGB formats */
671             if( p_stream->i_fourcc == VLC_FOURCC('R','V','2','4') )
672             {
673                 /* This is in BGR format */
674                 fmt.video.i_bmask = 0x00ff0000;
675                 fmt.video.i_gmask = 0x0000ff00;
676                 fmt.video.i_rmask = 0x000000ff;
677             }
678
679             if( p_stream->header.video.AvgTimePerFrame )
680             {
681                 fmt.video.i_frame_rate = 10000000;
682                 fmt.video.i_frame_rate_base =
683                     p_stream->header.video.AvgTimePerFrame;
684             }
685         }
686         else if( p_stream->mt.majortype == MEDIATYPE_Audio )
687         {
688             es_format_Init( &fmt, AUDIO_ES, p_stream->i_fourcc );
689
690             fmt.audio.i_channels = p_stream->header.audio.nChannels;
691             fmt.audio.i_rate = p_stream->header.audio.nSamplesPerSec;
692             fmt.audio.i_bitspersample = p_stream->header.audio.wBitsPerSample;
693             fmt.audio.i_blockalign = fmt.audio.i_channels *
694                 fmt.audio.i_bitspersample / 8;
695             fmt.i_bitrate = fmt.audio.i_channels * fmt.audio.i_rate *
696                 fmt.audio.i_bitspersample;
697         }
698
699         p_stream->p_es = es_out_Add( p_demux->out, &fmt );
700     }
701
702     return VLC_SUCCESS;
703 }
704
705 /*****************************************************************************
706  * AccessOpen: open direct show device as an access module
707  *****************************************************************************/
708 static int AccessOpen( vlc_object_t *p_this )
709 {
710     access_t     *p_access = (access_t*)p_this;
711     access_sys_t *p_sys;
712
713     p_access->p_sys = p_sys = (access_sys_t*)calloc( 1, sizeof( access_sys_t ) );
714     if( !p_sys )
715         return VLC_ENOMEM;
716
717     if( CommonOpen( p_this, p_sys, false ) != VLC_SUCCESS )
718     {
719         CommonClose( p_this, p_sys );
720         return VLC_EGENERIC;
721     }
722
723     dshow_stream_t *p_stream = p_sys->pp_streams[0];
724
725     /* Check if we need to force demuxers */
726     if( !p_access->psz_demux || !*p_access->psz_demux )
727     {
728         if( p_stream->i_fourcc == VLC_FOURCC('d','v','s','l') ||
729             p_stream->i_fourcc == VLC_FOURCC('d','v','s','d') ||
730             p_stream->i_fourcc == VLC_FOURCC('d','v','h','d') )
731         {
732             free( p_access->psz_demux );
733             p_access->psz_demux = strdup( "rawdv" );
734         }
735         else if( p_stream->i_fourcc == VLC_FOURCC('m','p','2','v') )
736         {
737             free( p_access->psz_demux );
738             p_access->psz_demux = strdup( "mpgv" );
739         }
740     }
741
742     /* Setup Access */
743     p_access->pf_read = NULL;
744     p_access->pf_block = ReadCompressed;
745     p_access->pf_control = AccessControl;
746     p_access->pf_seek = NULL;
747     p_access->info.i_update = 0;
748     p_access->info.i_size = 0;
749     p_access->info.i_pos = 0;
750     p_access->info.b_eof = false;
751     p_access->info.i_title = 0;
752     p_access->info.i_seekpoint = 0;
753     p_access->p_sys = p_sys;
754
755     /* Everything is ready. Let's rock baby */
756     msg_Dbg( p_this, "Playing...");
757     p_sys->p_control->Run();
758
759     return VLC_SUCCESS;
760 }
761
762 /*****************************************************************************
763  * CommonClose: close device
764  *****************************************************************************/
765 static void CommonClose( vlc_object_t *p_this, access_sys_t *p_sys )
766 {
767     msg_Dbg( p_this, "releasing DirectShow");
768
769     DeleteDirectShowGraph( p_sys );
770
771     /* Uninitialize OLE/COM */
772     CoUninitialize();
773
774     for( int i = 0; i < p_sys->i_streams; i++ ) delete p_sys->pp_streams[i];
775     if( p_sys->i_streams ) free( p_sys->pp_streams );
776
777     vlc_mutex_destroy( &p_sys->lock );
778     vlc_cond_destroy( &p_sys->wait );
779
780     free( p_sys );
781 }
782
783 /*****************************************************************************
784  * AccessClose: close device
785  *****************************************************************************/
786 static void AccessClose( vlc_object_t *p_this )
787 {
788     access_t     *p_access = (access_t *)p_this;
789     access_sys_t *p_sys    = p_access->p_sys;
790
791     /* Stop capturing stuff */
792     p_sys->p_control->Stop();
793
794     CommonClose( p_this, p_sys );
795 }
796
797 /*****************************************************************************
798  * DemuxClose: close device
799  *****************************************************************************/
800 static void DemuxClose( vlc_object_t *p_this )
801 {
802     demux_t      *p_demux = (demux_t *)p_this;
803     access_sys_t *p_sys   = (access_sys_t *)p_demux->p_sys;
804
805     /* Stop capturing stuff */
806     p_sys->p_control->Stop();
807
808     CommonClose( p_this, p_sys );
809 }
810
811 /****************************************************************************
812  * ConnectFilters
813  ****************************************************************************/
814 static bool ConnectFilters( vlc_object_t *p_this, access_sys_t *p_sys,
815                             IBaseFilter *p_filter,
816                             CaptureFilter *p_capture_filter )
817 {
818     CapturePin *p_input_pin = p_capture_filter->CustomGetPin();
819
820     AM_MEDIA_TYPE mediaType = p_input_pin->CustomGetMediaType();
821
822     if( p_sys->p_capture_graph_builder2 )
823     {
824         if( FAILED(p_sys->p_capture_graph_builder2->
825                 RenderStream( &PIN_CATEGORY_CAPTURE, &mediaType.majortype,
826                               p_filter, 0, (IBaseFilter *)p_capture_filter )) )
827         {
828             return false;
829         }
830
831         // Sort out all the possible video inputs
832         // The class needs to be given the capture filters ANALOGVIDEO input pin
833         IEnumPins *pins = NULL;
834         if( ( mediaType.majortype == MEDIATYPE_Video ||
835               mediaType.majortype == MEDIATYPE_Stream ) &&
836             SUCCEEDED(p_filter->EnumPins(&pins)) )
837         {
838             IPin        *pP = NULL;
839             ULONG        n;
840             PIN_INFO     pinInfo;
841             BOOL         Found = FALSE;
842             IKsPropertySet *pKs = NULL;
843             GUID guid;
844             DWORD dw;
845
846             while( !Found && ( S_OK == pins->Next(1, &pP, &n) ) )
847             {
848                 if( S_OK == pP->QueryPinInfo(&pinInfo) )
849                 {
850                     // is this pin an ANALOGVIDEOIN input pin?
851                     if( pinInfo.dir == PINDIR_INPUT &&
852                         pP->QueryInterface( IID_IKsPropertySet,
853                                             (void **)&pKs ) == S_OK )
854                     {
855                         if( pKs->Get( AMPROPSETID_Pin,
856                                       AMPROPERTY_PIN_CATEGORY, NULL, 0,
857                                       &guid, sizeof(GUID), &dw ) == S_OK )
858                         {
859                             if( guid == PIN_CATEGORY_ANALOGVIDEOIN )
860                             {
861                                 // recursively search crossbar routes
862                                 FindCrossbarRoutes( p_this, p_sys, pP, 0 );
863                                 // found it
864                                 Found = TRUE;
865                             }
866                         }
867                         pKs->Release();
868                     }
869                     pinInfo.pFilter->Release();
870                 }
871                 pP->Release();
872             }
873             pins->Release();
874             msg_Dbg( p_this, "ConnectFilters: graph_builder2 available.") ;
875             if ( !Found )
876                 msg_Warn( p_this, "ConnectFilters: No crossBar routes found (incobatible pin types)" ) ;
877         }
878         return true;
879     }
880     else
881     {
882         IEnumPins *p_enumpins;
883         IPin *p_pin;
884
885         if( S_OK != p_filter->EnumPins( &p_enumpins ) ) return false;
886
887         while( S_OK == p_enumpins->Next( 1, &p_pin, NULL ) )
888         {
889             PIN_DIRECTION pin_dir;
890             p_pin->QueryDirection( &pin_dir );
891
892             if( pin_dir == PINDIR_OUTPUT &&
893                 p_sys->p_graph->ConnectDirect( p_pin, (IPin *)p_input_pin,
894                                                0 ) == S_OK )
895             {
896                 p_pin->Release();
897                 p_enumpins->Release();
898                 return true;
899             }
900             p_pin->Release();
901         }
902
903         p_enumpins->Release();
904         return false;
905     }
906 }
907
908 /*
909  * get fourcc priority from arbritary preference, the higher the better
910  */
911 static int GetFourCCPriority( int i_fourcc )
912 {
913     switch( i_fourcc )
914     {
915     case VLC_FOURCC('I','4','2','0'):
916     case VLC_FOURCC('f','l','3','2'):
917         return 9;
918     case VLC_FOURCC('Y','V','1','2'):
919     case VLC_FOURCC('a','r','a','w'):
920         return 8;
921     case VLC_FOURCC('R','V','2','4'):
922         return 7;
923     case VLC_FOURCC('Y','U','Y','2'):
924     case VLC_FOURCC('R','V','3','2'):
925     case VLC_FOURCC('R','G','B','A'):
926         return 6;
927     }
928
929     return 0;
930 }
931
932 #define MAX_MEDIA_TYPES 32
933
934 static int OpenDevice( vlc_object_t *p_this, access_sys_t *p_sys,
935                        string devicename, bool b_audio )
936 {
937     /* See if device is already opened */
938     for( int i = 0; i < p_sys->i_streams; i++ )
939     {
940         if( devicename.size() &&
941             p_sys->pp_streams[i]->devicename == devicename )
942         {
943             /* Already opened */
944             return VLC_SUCCESS;
945         }
946     }
947
948     list<string> list_devices;
949
950     /* Enumerate devices and display their names */
951     FindCaptureDevice( p_this, NULL, &list_devices, b_audio );
952     if( !list_devices.size() )
953         return VLC_EGENERIC;
954
955     list<string>::iterator iter;
956     for( iter = list_devices.begin(); iter != list_devices.end(); iter++ )
957         msg_Dbg( p_this, "found device: %s", iter->c_str() );
958
959     /* If no device name was specified, pick the 1st one */
960     if( devicename.size() == 0 )
961     {
962         /* When none selected */
963         devicename = *list_devices.begin();
964         msg_Dbg( p_this, "asking for default device: %s", devicename.c_str() ) ;
965     }
966     else
967         msg_Dbg( p_this, "asking for device: %s", devicename.c_str() ) ;
968     // Use the system device enumerator and class enumerator to find
969     // a capture/preview device, such as a desktop USB video camera.
970     IBaseFilter *p_device_filter =
971         FindCaptureDevice( p_this, &devicename, NULL, b_audio );
972
973     if( p_device_filter )
974         msg_Dbg( p_this, "using device: %s", devicename.c_str() );
975     else
976     {
977         msg_Err( p_this, "can't use device: %s, unsupported device type",
978                  devicename.c_str() );
979         dialog_Fatal( p_this, _("Capture failed"),
980                         _("VLC cannot use the device \"%s\", because its "
981                           "type is not supported."), devicename.c_str() );
982         return VLC_EGENERIC;
983     }
984
985     // Retreive acceptable media types supported by device
986     AM_MEDIA_TYPE media_types[MAX_MEDIA_TYPES];
987     size_t media_count =
988         EnumDeviceCaps( p_this, p_device_filter, b_audio ? 0 : p_sys->i_chroma,
989                         p_sys->i_width, p_sys->i_height,
990       b_audio ? var_CreateGetInteger( p_this, "dshow-audio-channels" ) : 0,
991       b_audio ? var_CreateGetInteger( p_this, "dshow-audio-samplerate" ) : 0,
992       b_audio ? var_CreateGetInteger( p_this, "dshow-audio-bitspersample" ) : 0,
993       media_types, MAX_MEDIA_TYPES );
994
995     AM_MEDIA_TYPE *mt = NULL;
996
997     if( media_count > 0 )
998     {
999         mt = (AM_MEDIA_TYPE *)CoTaskMemAlloc(sizeof(AM_MEDIA_TYPE) * media_count);
1000
1001         // Order and copy returned media types according to arbitrary
1002         // fourcc priority
1003         for( size_t c = 0; c < media_count; c++ )
1004         {
1005             int slot_priority =
1006                 GetFourCCPriority(GetFourCCFromMediaType(media_types[c]));
1007             size_t slot_copy = c;
1008             for( size_t d = c+1; d < media_count; d++ )
1009             {
1010                 int priority =
1011                     GetFourCCPriority(GetFourCCFromMediaType(media_types[d]));
1012                 if( priority > slot_priority )
1013                 {
1014                     slot_priority = priority;
1015                     slot_copy = d;
1016                 }
1017             }
1018             if( slot_copy != c )
1019             {
1020                 mt[c] = media_types[slot_copy];
1021                 media_types[slot_copy] = media_types[c];
1022             }
1023             else
1024             {
1025                 mt[c] = media_types[c];
1026             }
1027         }
1028     }
1029     else {
1030         /* capture device */
1031         msg_Err( p_this, "capture device '%s' does not support required parameters !", devicename.c_str() );
1032         dialog_Fatal( p_this, _("Capture failed"),
1033                         _("The capture device \"%s\" does not support the "
1034                           "required parameters."), devicename.c_str() );
1035         p_device_filter->Release();
1036         return VLC_EGENERIC;
1037     }
1038
1039     /* Create and add our capture filter */
1040     CaptureFilter *p_capture_filter =
1041         new CaptureFilter( p_this, p_sys, mt, media_count );
1042     p_sys->p_graph->AddFilter( p_capture_filter, 0 );
1043
1044     /* Add the device filter to the graph (seems necessary with VfW before
1045      * accessing pin attributes). */
1046     p_sys->p_graph->AddFilter( p_device_filter, 0 );
1047
1048     /* Attempt to connect one of this device's capture output pins */
1049     msg_Dbg( p_this, "connecting filters" );
1050     if( ConnectFilters( p_this, p_sys, p_device_filter, p_capture_filter ) )
1051     {
1052         /* Success */
1053         msg_Dbg( p_this, "filters connected successfully !" );
1054
1055         dshow_stream_t dshow_stream;
1056         dshow_stream.b_pts = false;
1057         dshow_stream.p_es = 0;
1058         dshow_stream.mt =
1059             p_capture_filter->CustomGetPin()->CustomGetMediaType();
1060
1061         /* Show Device properties. Done here so the VLC stream is setup with
1062          * the proper parameters. */
1063         vlc_value_t val;
1064         var_Get( p_this, "dshow-config", &val );
1065         if( val.b_bool )
1066         {
1067             ShowDeviceProperties( p_this, p_sys->p_capture_graph_builder2,
1068                                   p_device_filter, b_audio );
1069         }
1070
1071         ConfigTuner( p_this, p_sys->p_capture_graph_builder2,
1072                      p_device_filter );
1073
1074         var_Get( p_this, "dshow-tuner", &val );
1075         if( val.b_bool && dshow_stream.mt.majortype != MEDIATYPE_Stream )
1076         {
1077             /* FIXME: we do MEDIATYPE_Stream later so we don't do it twice. */
1078             ShowTunerProperties( p_this, p_sys->p_capture_graph_builder2,
1079                                  p_device_filter, b_audio );
1080         }
1081
1082         dshow_stream.mt =
1083             p_capture_filter->CustomGetPin()->CustomGetMediaType();
1084
1085         dshow_stream.i_fourcc = GetFourCCFromMediaType( dshow_stream.mt );
1086         if( dshow_stream.i_fourcc )
1087         {
1088             if( dshow_stream.mt.majortype == MEDIATYPE_Video )
1089             {
1090                 dshow_stream.header.video =
1091                     *(VIDEOINFOHEADER *)dshow_stream.mt.pbFormat;
1092                 msg_Dbg( p_this, "MEDIATYPE_Video" );
1093                 msg_Dbg( p_this, "selected video pin accepts format: %4.4s",
1094                          (char *)&dshow_stream.i_fourcc);
1095             }
1096             else if( dshow_stream.mt.majortype == MEDIATYPE_Audio )
1097             {
1098                 dshow_stream.header.audio =
1099                     *(WAVEFORMATEX *)dshow_stream.mt.pbFormat;
1100                 msg_Dbg( p_this, "MEDIATYPE_Audio" );
1101                 msg_Dbg( p_this, "selected audio pin accepts format: %4.4s",
1102                          (char *)&dshow_stream.i_fourcc);
1103             }
1104             else if( dshow_stream.mt.majortype == MEDIATYPE_Stream )
1105             {
1106                 msg_Dbg( p_this, "MEDIATYPE_Stream" );
1107                 msg_Dbg( p_this, "selected stream pin accepts format: %4.4s",
1108                          (char *)&dshow_stream.i_fourcc);
1109             }
1110             else
1111             {
1112                 msg_Dbg( p_this, "unknown stream majortype" );
1113                 goto fail;
1114             }
1115
1116             /* Add directshow elementary stream to our list */
1117             dshow_stream.p_device_filter = p_device_filter;
1118             dshow_stream.p_capture_filter = p_capture_filter;
1119
1120             p_sys->pp_streams = (dshow_stream_t **)realloc( p_sys->pp_streams,
1121                 sizeof(dshow_stream_t *) * (p_sys->i_streams + 1) );
1122             p_sys->pp_streams[p_sys->i_streams] = new dshow_stream_t;
1123             *p_sys->pp_streams[p_sys->i_streams++] = dshow_stream;
1124
1125             return VLC_SUCCESS;
1126         }
1127     }
1128
1129  fail:
1130     /* Remove filters from graph */
1131     p_sys->p_graph->RemoveFilter( p_device_filter );
1132     p_sys->p_graph->RemoveFilter( p_capture_filter );
1133
1134     /* Release objects */
1135     p_device_filter->Release();
1136     p_capture_filter->Release();
1137
1138     return VLC_EGENERIC;
1139 }
1140
1141 /* FindCaptureDevices:: This Function had two purposes :
1142     Returns the list of capture devices when p_listdevices != NULL
1143     Creates an IBaseFilter when p_devicename corresponds to an existing devname
1144    These actions *may* be requested whith a single call.
1145 */
1146 static IBaseFilter *
1147 FindCaptureDevice( vlc_object_t *p_this, string *p_devicename,
1148                    list<string> *p_listdevices, bool b_audio )
1149 {
1150     IBaseFilter *p_base_filter = NULL;
1151     IMoniker *p_moniker = NULL;
1152     ULONG i_fetched;
1153     HRESULT hr;
1154     list<string> devicelist;
1155
1156     /* Create the system device enumerator */
1157     ICreateDevEnum *p_dev_enum = NULL;
1158
1159     hr = CoCreateInstance( CLSID_SystemDeviceEnum, NULL, CLSCTX_INPROC,
1160                            IID_ICreateDevEnum, (void **)&p_dev_enum );
1161     if( FAILED(hr) )
1162     {
1163         msg_Err( p_this, "failed to create the device enumerator (0x%lx)", hr);
1164         return NULL;
1165     }
1166
1167     /* Create an enumerator for the video capture devices */
1168     IEnumMoniker *p_class_enum = NULL;
1169     if( !b_audio )
1170         hr = p_dev_enum->CreateClassEnumerator( CLSID_VideoInputDeviceCategory,
1171                                                 &p_class_enum, 0 );
1172     else
1173         hr = p_dev_enum->CreateClassEnumerator( CLSID_AudioInputDeviceCategory,
1174                                                 &p_class_enum, 0 );
1175     p_dev_enum->Release();
1176     if( FAILED(hr) )
1177     {
1178         msg_Err( p_this, "failed to create the class enumerator (0x%lx)", hr );
1179         return NULL;
1180     }
1181
1182     /* If there are no enumerators for the requested type, then
1183      * CreateClassEnumerator will succeed, but p_class_enum will be NULL */
1184     if( p_class_enum == NULL )
1185     {
1186         msg_Err( p_this, "no %s capture device was detected", ( b_audio ? "audio" : "video" ) );
1187         return NULL;
1188     }
1189
1190     /* Enumerate the devices */
1191
1192     /* Note that if the Next() call succeeds but there are no monikers,
1193      * it will return S_FALSE (which is not a failure). Therefore, we check
1194      * that the return code is S_OK instead of using SUCCEEDED() macro. */
1195
1196     while( p_class_enum->Next( 1, &p_moniker, &i_fetched ) == S_OK )
1197     {
1198         /* Getting the property page to get the device name */
1199         IPropertyBag *p_bag;
1200         hr = p_moniker->BindToStorage( 0, 0, IID_IPropertyBag,
1201                                        (void **)&p_bag );
1202         if( SUCCEEDED(hr) )
1203         {
1204             VARIANT var;
1205             var.vt = VT_BSTR;
1206             hr = p_bag->Read( L"FriendlyName", &var, NULL );
1207             p_bag->Release();
1208             if( SUCCEEDED(hr) )
1209             {
1210                 char *p_buf = FromWide( var.bstrVal );
1211                 string devname = string(p_buf);
1212                 free( p_buf) ;
1213
1214                 int dup = 0;
1215                 /* find out if this name is already used by a previously found device */
1216                 list<string>::const_iterator iter = devicelist.begin();
1217                 list<string>::const_iterator end = devicelist.end();
1218                 string ordevname = devname ;
1219                 while ( iter != end )
1220                 {
1221                     if( 0 == (*iter).compare( devname ) )
1222                     { /* devname is on the list. Try another name with sequence
1223                          number apended and then rescan until a unique entry is found*/
1224                          char seq[16];
1225                          snprintf(seq, 16, " #%d", ++dup);
1226                          devname = ordevname + seq;
1227                          iter = devicelist.begin();
1228                     }
1229                     else
1230                          ++iter;
1231                 }
1232                 devicelist.push_back( devname );
1233
1234                 if( p_devicename && *p_devicename == devname )
1235                 {
1236                     msg_Dbg( p_this, "asked for %s, binding to %s", p_devicename->c_str() , devname.c_str() ) ;
1237                     /* NULL possibly means we don't need BindMoniker BindCtx ?? */
1238                     hr = p_moniker->BindToObject( NULL, 0, IID_IBaseFilter,
1239                                                   (void **)&p_base_filter );
1240                     if( FAILED(hr) )
1241                     {
1242                         msg_Err( p_this, "couldn't bind moniker to filter "
1243                                  "object (0x%lx)", hr );
1244                         p_moniker->Release();
1245                         p_class_enum->Release();
1246                         return NULL;
1247                     }
1248                     p_moniker->Release();
1249                     p_class_enum->Release();
1250                     return p_base_filter;
1251                 }
1252             }
1253         }
1254
1255         p_moniker->Release();
1256     }
1257
1258     p_class_enum->Release();
1259
1260     if( p_listdevices ) {
1261     devicelist.sort();
1262     *p_listdevices = devicelist;
1263     }
1264     return NULL;
1265 }
1266
1267 static size_t EnumDeviceCaps( vlc_object_t *p_this, IBaseFilter *p_filter,
1268                               int i_fourcc, int i_width, int i_height,
1269                               int i_channels, int i_samplespersec,
1270                               int i_bitspersample, AM_MEDIA_TYPE *mt,
1271                               size_t mt_max )
1272 {
1273     IEnumPins *p_enumpins;
1274     IPin *p_output_pin;
1275     IEnumMediaTypes *p_enummt;
1276     size_t mt_count = 0;
1277
1278     LONGLONG i_AvgTimePerFrame = 0;
1279     float r_fps = var_GetFloat( p_this, "dshow-fps" );
1280     if( r_fps )
1281         i_AvgTimePerFrame = 10000000000LL/(LONGLONG)(r_fps*1000.0f);
1282
1283     if( FAILED(p_filter->EnumPins( &p_enumpins )) )
1284     {
1285         msg_Dbg( p_this, "EnumDeviceCaps failed: no pin enumeration !");
1286         return 0;
1287     }
1288
1289     while( S_OK == p_enumpins->Next( 1, &p_output_pin, NULL ) )
1290     {
1291         PIN_INFO info;
1292
1293         if( S_OK == p_output_pin->QueryPinInfo( &info ) )
1294         {
1295             msg_Dbg( p_this, "EnumDeviceCaps: %s pin: %S",
1296                      info.dir == PINDIR_INPUT ? "input" : "output",
1297                      info.achName );
1298             if( info.pFilter ) info.pFilter->Release();
1299         }
1300
1301         p_output_pin->Release();
1302     }
1303
1304     p_enumpins->Reset();
1305
1306     while( !mt_count && p_enumpins->Next( 1, &p_output_pin, NULL ) == S_OK )
1307     {
1308         PIN_INFO info;
1309
1310         if( S_OK == p_output_pin->QueryPinInfo( &info ) )
1311         {
1312             if( info.pFilter ) info.pFilter->Release();
1313             if( info.dir == PINDIR_INPUT )
1314             {
1315                 p_output_pin->Release();
1316                 continue;
1317             }
1318             msg_Dbg( p_this, "EnumDeviceCaps: trying pin %S", info.achName );
1319         }
1320
1321         AM_MEDIA_TYPE *p_mt;
1322
1323         /*
1324         ** Configure pin with a default compatible media if possible
1325         */
1326
1327         IAMStreamConfig *pSC;
1328         if( SUCCEEDED(p_output_pin->QueryInterface( IID_IAMStreamConfig,
1329                                             (void **)&pSC )) )
1330         {
1331             int piCount, piSize;
1332             if( SUCCEEDED(pSC->GetNumberOfCapabilities(&piCount, &piSize)) )
1333             {
1334                 BYTE *pSCC= (BYTE *)CoTaskMemAlloc(piSize);
1335                 if( NULL != pSCC )
1336                 {
1337                     int i_priority = -1;
1338                     for( int i=0; i<piCount; ++i )
1339                     {
1340                         if( SUCCEEDED(pSC->GetStreamCaps(i, &p_mt, pSCC)) )
1341                         {
1342                             int i_current_fourcc = GetFourCCFromMediaType( *p_mt );
1343                             int i_current_priority = GetFourCCPriority(i_current_fourcc);
1344
1345                             if( (i_fourcc && (i_current_fourcc != i_fourcc))
1346                              || (i_priority > i_current_priority) )
1347                             {
1348                                 // unwanted chroma, try next media type
1349                                 FreeMediaType( *p_mt );
1350                                 CoTaskMemFree( (PVOID)p_mt );
1351                                 continue;
1352                             }
1353
1354                             if( MEDIATYPE_Video == p_mt->majortype
1355                                     && FORMAT_VideoInfo == p_mt->formattype )
1356                             {
1357                                 VIDEO_STREAM_CONFIG_CAPS *pVSCC = reinterpret_cast<VIDEO_STREAM_CONFIG_CAPS*>(pSCC);
1358                                 VIDEOINFOHEADER *pVih = reinterpret_cast<VIDEOINFOHEADER*>(p_mt->pbFormat);
1359
1360                                 if( i_AvgTimePerFrame )
1361                                 {
1362                                     if( pVSCC->MinFrameInterval > i_AvgTimePerFrame
1363                                       || i_AvgTimePerFrame > pVSCC->MaxFrameInterval )
1364                                     {
1365                                         // required frame rate not compatible, try next media type
1366                                         FreeMediaType( *p_mt );
1367                                         CoTaskMemFree( (PVOID)p_mt );
1368                                         continue;
1369                                     }
1370                                     pVih->AvgTimePerFrame = i_AvgTimePerFrame;
1371                                 }
1372
1373                                 if( i_width )
1374                                 {
1375                                     if((   !pVSCC->OutputGranularityX
1376                                            && i_width != pVSCC->MinOutputSize.cx
1377                                            && i_width != pVSCC->MaxOutputSize.cx)
1378                                        ||
1379                                        (   pVSCC->OutputGranularityX
1380                                            && ((i_width % pVSCC->OutputGranularityX)
1381                                                || pVSCC->MinOutputSize.cx > i_width
1382                                                || i_width > pVSCC->MaxOutputSize.cx )))
1383                                     {
1384                                         // required width not compatible, try next media type
1385                                         FreeMediaType( *p_mt );
1386                                         CoTaskMemFree( (PVOID)p_mt );
1387                                         continue;
1388                                     }
1389                                     pVih->bmiHeader.biWidth = i_width;
1390                                 }
1391
1392                                 if( i_height )
1393                                 {
1394                                     if((   !pVSCC->OutputGranularityY
1395                                            && i_height != pVSCC->MinOutputSize.cy
1396                                            && i_height != pVSCC->MaxOutputSize.cy)
1397                                        ||
1398                                        (   pVSCC->OutputGranularityY
1399                                            && ((i_height % pVSCC->OutputGranularityY)
1400                                                || pVSCC->MinOutputSize.cy > i_height
1401                                                || i_height > pVSCC->MaxOutputSize.cy )))
1402                                     {
1403                                         // required height not compatible, try next media type
1404                                         FreeMediaType( *p_mt );
1405                                         CoTaskMemFree( (PVOID)p_mt );
1406                                         continue;
1407                                     }
1408                                     pVih->bmiHeader.biHeight = i_height;
1409                                 }
1410
1411                                 // Set the sample size and image size.
1412                                 // (Round the image width up to a DWORD boundary.)
1413                                 p_mt->lSampleSize = pVih->bmiHeader.biSizeImage =
1414                                     ((pVih->bmiHeader.biWidth + 3) & ~3) *
1415                                     pVih->bmiHeader.biHeight * (pVih->bmiHeader.biBitCount>>3);
1416
1417                                 // no cropping, use full video input buffer
1418                                 memset(&(pVih->rcSource), 0, sizeof(RECT));
1419                                 memset(&(pVih->rcTarget), 0, sizeof(RECT));
1420
1421                                 // select this format as default
1422                                 if( SUCCEEDED( pSC->SetFormat(p_mt) ) )
1423                                 {
1424                                     i_priority = i_current_priority;
1425                                     if( i_fourcc )
1426                                         // no need to check any more media types
1427                                         i = piCount;
1428                                 }
1429                             }
1430                             else if( p_mt->majortype == MEDIATYPE_Audio
1431                                     && p_mt->formattype == FORMAT_WaveFormatEx )
1432                             {
1433                                 AUDIO_STREAM_CONFIG_CAPS *pASCC = reinterpret_cast<AUDIO_STREAM_CONFIG_CAPS*>(pSCC);
1434                                 WAVEFORMATEX *pWfx = reinterpret_cast<WAVEFORMATEX*>(p_mt->pbFormat);
1435
1436                                 if( i_current_fourcc && (WAVE_FORMAT_PCM == pWfx->wFormatTag) )
1437                                 {
1438                                     int val = i_channels;
1439                                     if( ! val )
1440                                         val = 2;
1441
1442                                     if( (   !pASCC->ChannelsGranularity
1443                                             && (unsigned int)val != pASCC->MinimumChannels
1444                                             && (unsigned int)val != pASCC->MaximumChannels)
1445                                         ||
1446                                         (   pASCC->ChannelsGranularity
1447                                             && ((val % pASCC->ChannelsGranularity)
1448                                                 || (unsigned int)val < pASCC->MinimumChannels
1449                                                 || (unsigned int)val > pASCC->MaximumChannels)))
1450                                     {
1451                                         // required number channels not available, try next media type
1452                                         FreeMediaType( *p_mt );
1453                                         CoTaskMemFree( (PVOID)p_mt );
1454                                         continue;
1455                                     }
1456                                     pWfx->nChannels = val;
1457
1458                                     val = i_samplespersec;
1459                                     if( ! val )
1460                                         val = 44100;
1461
1462                                     if( (   !pASCC->SampleFrequencyGranularity
1463                                             && (unsigned int)val != pASCC->MinimumSampleFrequency
1464                                             && (unsigned int)val != pASCC->MaximumSampleFrequency)
1465                                         ||
1466                                         (   pASCC->SampleFrequencyGranularity
1467                                             && ((val % pASCC->SampleFrequencyGranularity)
1468                                                 || (unsigned int)val < pASCC->MinimumSampleFrequency
1469                                                 || (unsigned int)val > pASCC->MaximumSampleFrequency )))
1470                                     {
1471                                         // required sampling rate not available, try next media type
1472                                         FreeMediaType( *p_mt );
1473                                         CoTaskMemFree( (PVOID)p_mt );
1474                                         continue;
1475                                     }
1476                                     pWfx->nSamplesPerSec = val;
1477  
1478                                     val = i_bitspersample;
1479                                     if( ! val )
1480                                     {
1481                                         if( VLC_FOURCC('f', 'l', '3', '2') == i_current_fourcc )
1482                                             val = 32;
1483                                         else
1484                                             val = 16;
1485                                     }
1486
1487                                     if( (   !pASCC->BitsPerSampleGranularity
1488                                             && (unsigned int)val != pASCC->MinimumBitsPerSample
1489                                             &&  (unsigned int)val != pASCC->MaximumBitsPerSample )
1490                                         ||
1491                                         (   pASCC->BitsPerSampleGranularity
1492                                             && ((val % pASCC->BitsPerSampleGranularity)
1493                                                 || (unsigned int)val < pASCC->MinimumBitsPerSample
1494                                                 || (unsigned int)val > pASCC->MaximumBitsPerSample )))
1495                                     {
1496                                         // required sample size not available, try next media type
1497                                         FreeMediaType( *p_mt );
1498                                         CoTaskMemFree( (PVOID)p_mt );
1499                                         continue;
1500                                     }
1501
1502                                     pWfx->wBitsPerSample = val;
1503                                     pWfx->nBlockAlign = (pWfx->wBitsPerSample * pWfx->nChannels)/8;
1504                                     pWfx->nAvgBytesPerSec = pWfx->nSamplesPerSec * pWfx->nBlockAlign;
1505
1506                                     // select this format as default
1507                                     if( SUCCEEDED( pSC->SetFormat(p_mt) ) )
1508                                     {
1509                                         i_priority = i_current_priority;
1510                                     }
1511                                 }
1512                             }
1513                             FreeMediaType( *p_mt );
1514                             CoTaskMemFree( (PVOID)p_mt );
1515                         }
1516                     }
1517                     CoTaskMemFree( (LPVOID)pSCC );
1518                     if( i_priority >= 0 )
1519                         msg_Dbg( p_this, "EnumDeviceCaps: input pin default format configured");
1520                 }
1521             }
1522             pSC->Release();
1523         }
1524
1525         /*
1526         ** Probe pin for available medias (may be a previously configured one)
1527         */
1528
1529         if( FAILED( p_output_pin->EnumMediaTypes( &p_enummt ) ) )
1530         {
1531             p_output_pin->Release();
1532             continue;
1533         }
1534
1535         while( p_enummt->Next( 1, &p_mt, NULL ) == S_OK )
1536         {
1537             int i_current_fourcc = GetFourCCFromMediaType( *p_mt );
1538             if( i_current_fourcc && p_mt->majortype == MEDIATYPE_Video
1539                 && p_mt->formattype == FORMAT_VideoInfo )
1540             {
1541                 int i_current_width = ((VIDEOINFOHEADER *)p_mt->pbFormat)->bmiHeader.biWidth;
1542                 int i_current_height = ((VIDEOINFOHEADER *)p_mt->pbFormat)->bmiHeader.biHeight;
1543                 LONGLONG i_current_atpf = ((VIDEOINFOHEADER *)p_mt->pbFormat)->AvgTimePerFrame;
1544
1545                 if( i_current_height < 0 )
1546                     i_current_height = -i_current_height;
1547
1548                 msg_Dbg( p_this, "EnumDeviceCaps: input pin "
1549                          "accepts chroma: %4.4s, width:%i, height:%i, fps:%f",
1550                          (char *)&i_current_fourcc, i_current_width,
1551                          i_current_height, (10000000.0f/((float)i_current_atpf)) );
1552
1553                 if( ( !i_fourcc || i_fourcc == i_current_fourcc ) &&
1554                     ( !i_width || i_width == i_current_width ) &&
1555                     ( !i_height || i_height == i_current_height ) &&
1556                     ( !i_AvgTimePerFrame || i_AvgTimePerFrame == i_current_atpf ) &&
1557                     mt_count < mt_max )
1558                 {
1559                     /* Pick match */
1560                     mt[mt_count++] = *p_mt;
1561                 }
1562                 else FreeMediaType( *p_mt );
1563             }
1564             else if( i_current_fourcc && p_mt->majortype == MEDIATYPE_Audio
1565                     && p_mt->formattype == FORMAT_WaveFormatEx)
1566             {
1567                 int i_current_channels =
1568                     ((WAVEFORMATEX *)p_mt->pbFormat)->nChannels;
1569                 int i_current_samplespersec =
1570                     ((WAVEFORMATEX *)p_mt->pbFormat)->nSamplesPerSec;
1571                 int i_current_bitspersample =
1572                     ((WAVEFORMATEX *)p_mt->pbFormat)->wBitsPerSample;
1573
1574                 msg_Dbg( p_this, "EnumDeviceCaps: input pin "
1575                          "accepts format: %4.4s, channels:%i, "
1576                          "samples/sec:%i bits/sample:%i",
1577                          (char *)&i_current_fourcc, i_current_channels,
1578                          i_current_samplespersec, i_current_bitspersample);
1579
1580                 if( (!i_channels || i_channels == i_current_channels) &&
1581                     (!i_samplespersec ||
1582                      i_samplespersec == i_current_samplespersec) &&
1583                     (!i_bitspersample ||
1584                      i_bitspersample == i_current_bitspersample) &&
1585                     mt_count < mt_max )
1586                 {
1587                     /* Pick  match */
1588                     mt[mt_count++] = *p_mt;
1589
1590                     /* Setup a few properties like the audio latency */
1591                     IAMBufferNegotiation *p_ambuf;
1592                     if( SUCCEEDED( p_output_pin->QueryInterface(
1593                           IID_IAMBufferNegotiation, (void **)&p_ambuf ) ) )
1594                     {
1595                         ALLOCATOR_PROPERTIES AllocProp;
1596                         AllocProp.cbAlign = -1;
1597
1598                         /* 100 ms of latency */
1599                         AllocProp.cbBuffer = i_current_channels *
1600                           i_current_samplespersec *
1601                           i_current_bitspersample / 8 / 10;
1602
1603                         AllocProp.cbPrefix = -1;
1604                         AllocProp.cBuffers = -1;
1605                         p_ambuf->SuggestAllocatorProperties( &AllocProp );
1606                         p_ambuf->Release();
1607                     }
1608                 }
1609                 else FreeMediaType( *p_mt );
1610             }
1611             else if( i_current_fourcc && p_mt->majortype == MEDIATYPE_Stream )
1612             {
1613                 msg_Dbg( p_this, "EnumDeviceCaps: input pin "
1614                          "accepts stream format: %4.4s",
1615                          (char *)&i_current_fourcc );
1616
1617                 if( ( !i_fourcc || i_fourcc == i_current_fourcc ) &&
1618                     mt_count < mt_max )
1619                 {
1620                     /* Pick match */
1621                     mt[mt_count++] = *p_mt;
1622                     i_fourcc = i_current_fourcc;
1623                 }
1624                 else FreeMediaType( *p_mt );
1625             }
1626             else
1627             {
1628                 const char * psz_type = "unknown";
1629                 if( p_mt->majortype == MEDIATYPE_Video ) psz_type = "video";
1630                 if( p_mt->majortype == MEDIATYPE_Audio ) psz_type = "audio";
1631                 if( p_mt->majortype == MEDIATYPE_Stream ) psz_type = "stream";
1632                 msg_Dbg( p_this, "EnumDeviceCaps: input pin media: unsupported format "
1633                          "(%s %4.4s)", psz_type, (char *)&p_mt->subtype );
1634
1635                 FreeMediaType( *p_mt );
1636             }
1637             CoTaskMemFree( (PVOID)p_mt );
1638         }
1639
1640         if( !mt_count && p_enummt->Reset() == S_OK )
1641         {
1642             // VLC did not find any supported MEDIATYPE for this output pin.
1643             // However the graph builder might insert converter filters in
1644             // the graph if we use a different codec in VLC filter input pin.
1645             // however, in order to avoid nasty surprises, make use of this
1646             // facility only for known unsupported codecs.
1647
1648             while( !mt_count && p_enummt->Next( 1, &p_mt, NULL ) == S_OK )
1649             {
1650                 // the first four bytes of subtype GUID contains the codec FOURCC
1651                 const char *pfcc = (char *)&p_mt->subtype;
1652                 int i_current_fourcc = VLC_FOURCC(pfcc[0], pfcc[1], pfcc[2], pfcc[3]);
1653                 if( VLC_FOURCC('H','C','W','2') == i_current_fourcc
1654                  && p_mt->majortype == MEDIATYPE_Video )
1655                 {
1656                     // output format for 'Hauppauge WinTV PVR PCI II Capture'
1657                     // try I420 as an input format
1658                     i_current_fourcc = VLC_FOURCC('I','4','2','0');
1659                     if( !i_fourcc || i_fourcc == i_current_fourcc )
1660                     {
1661                         // return alternative media type
1662                         AM_MEDIA_TYPE mtr;
1663                         VIDEOINFOHEADER vh;
1664  
1665                         mtr.majortype            = MEDIATYPE_Video;
1666                         mtr.subtype              = MEDIASUBTYPE_I420;
1667                         mtr.bFixedSizeSamples    = TRUE;
1668                         mtr.bTemporalCompression = FALSE;
1669                         mtr.pUnk                 = NULL;
1670                         mtr.formattype           = FORMAT_VideoInfo;
1671                         mtr.cbFormat             = sizeof(vh);
1672                         mtr.pbFormat             = (BYTE *)&vh;
1673  
1674                         memset(&vh, 0, sizeof(vh));
1675  
1676                         vh.bmiHeader.biSize   = sizeof(vh.bmiHeader);
1677                         vh.bmiHeader.biWidth  = i_width > 0 ? i_width :
1678                             ((VIDEOINFOHEADER *)p_mt->pbFormat)->bmiHeader.biWidth;
1679                         vh.bmiHeader.biHeight = i_height > 0 ? i_height :
1680                             ((VIDEOINFOHEADER *)p_mt->pbFormat)->bmiHeader.biHeight;
1681                         vh.bmiHeader.biPlanes      = 3;
1682                         vh.bmiHeader.biBitCount    = 12;
1683                         vh.bmiHeader.biCompression = VLC_FOURCC('I','4','2','0');
1684                         vh.bmiHeader.biSizeImage   = vh.bmiHeader.biWidth * 12 *
1685                             vh.bmiHeader.biHeight / 8;
1686                         mtr.lSampleSize            = vh.bmiHeader.biSizeImage;
1687  
1688                         msg_Dbg( p_this, "EnumDeviceCaps: input pin media: using 'I420' in place of unsupported format 'HCW2'");
1689
1690                         if( SUCCEEDED(CopyMediaType(mt+mt_count, &mtr)) )
1691                             ++mt_count;
1692                     }
1693                 }
1694                 FreeMediaType( *p_mt );
1695             }
1696         }
1697
1698         p_enummt->Release();
1699         p_output_pin->Release();
1700     }
1701
1702     p_enumpins->Release();
1703     return mt_count;
1704 }
1705
1706 /*****************************************************************************
1707  * ReadCompressed: reads compressed (MPEG/DV) data from the device.
1708  *****************************************************************************
1709  * Returns -1 in case of error, 0 in case of EOF, otherwise the number of
1710  * bytes.
1711  *****************************************************************************/
1712 static block_t *ReadCompressed( access_t *p_access )
1713 {
1714     access_sys_t   *p_sys = p_access->p_sys;
1715     dshow_stream_t *p_stream = NULL;
1716     VLCMediaSample sample;
1717
1718     /* Read 1 DV/MPEG frame (they contain the video and audio data) */
1719
1720     /* There must be only 1 elementary stream to produce a valid stream
1721      * of MPEG or DV data */
1722     p_stream = p_sys->pp_streams[0];
1723
1724     while( 1 )
1725     {
1726         if( !vlc_object_alive (p_access) || p_access->b_error ) return 0;
1727
1728         /* Get new sample/frame from the elementary stream (blocking). */
1729         vlc_mutex_lock( &p_sys->lock );
1730
1731         if( p_stream->p_capture_filter->CustomGetPin()
1732               ->CustomGetSample( &sample ) != S_OK )
1733         {
1734             /* No data available. Wait until some data has arrived */
1735             vlc_cond_wait( &p_sys->wait, &p_sys->lock );
1736             vlc_mutex_unlock( &p_sys->lock );
1737             continue;
1738         }
1739
1740         vlc_mutex_unlock( &p_sys->lock );
1741
1742         /*
1743          * We got our sample
1744          */
1745         block_t *p_block;
1746         uint8_t *p_data;
1747         int i_data_size = sample.p_sample->GetActualDataLength();
1748
1749         if( !i_data_size || !(p_block = block_New( p_access, i_data_size )) )
1750         {
1751             sample.p_sample->Release();
1752             continue;
1753         }
1754
1755         sample.p_sample->GetPointer( &p_data );
1756         vlc_memcpy( p_block->p_buffer, p_data, i_data_size );
1757         sample.p_sample->Release();
1758
1759         /* The caller got what he wanted */
1760         return p_block;
1761     }
1762
1763     return NULL; /* never reached */
1764 }
1765
1766 /****************************************************************************
1767  * Demux:
1768  ****************************************************************************/
1769 static int Demux( demux_t *p_demux )
1770 {
1771     access_sys_t *p_sys = (access_sys_t *)p_demux->p_sys;
1772     int i_stream;
1773     int i_found_samples;
1774
1775     i_found_samples = 0;
1776     vlc_mutex_lock( &p_sys->lock );
1777
1778     while ( !i_found_samples )
1779     {
1780         /* Try to grab samples from all streams */
1781         for( i_stream = 0; i_stream < p_sys->i_streams; i_stream++ )
1782         {
1783             dshow_stream_t *p_stream = p_sys->pp_streams[i_stream];
1784             if( p_stream->p_capture_filter &&
1785                 p_stream->p_capture_filter->CustomGetPin()
1786                 ->CustomGetSamples( p_stream->samples_queue ) == S_OK )
1787             {
1788                 i_found_samples = 1;
1789             }
1790         }
1791
1792         if ( !i_found_samples)
1793         {
1794             /* Didn't find any audio nor video sample, just wait till the
1795              * dshow thread pushes some samples */
1796             vlc_cond_wait( &p_sys->wait, &p_sys->lock );
1797             /* Some DShow thread pushed data, or the OS broke the wait all
1798              * by itself. In all cases, it's *strongly* advised to test the
1799              * condition again, so let the loop do the test again */
1800         }
1801     }
1802
1803     vlc_mutex_unlock( &p_sys->lock );
1804
1805     for ( i_stream = 0; i_stream < p_sys->i_streams; i_stream++ )
1806     {
1807         int i_samples;
1808         dshow_stream_t *p_stream = p_sys->pp_streams[i_stream];
1809
1810         i_samples = p_stream->samples_queue.size();
1811         while ( i_samples > 0 )
1812         {
1813             int i_data_size;
1814             uint8_t *p_data;
1815             block_t *p_block;
1816             VLCMediaSample sample;
1817
1818             sample = p_stream->samples_queue.front();
1819             p_stream->samples_queue.pop_front();
1820
1821             i_data_size = sample.p_sample->GetActualDataLength();
1822             sample.p_sample->GetPointer( &p_data );
1823
1824             REFERENCE_TIME i_pts, i_end_date;
1825             HRESULT hr = sample.p_sample->GetTime( &i_pts, &i_end_date );
1826             if( hr != VFW_S_NO_STOP_TIME && hr != S_OK ) i_pts = 0;
1827
1828             if( !i_pts )
1829             {
1830                 if( p_stream->mt.majortype == MEDIATYPE_Video || !p_stream->b_pts )
1831                 {
1832                     /* Use our data timestamp */
1833                     i_pts = sample.i_timestamp;
1834                     p_stream->b_pts = true;
1835                 }
1836             }
1837
1838             i_pts /= 10; /* Dshow works with 100 nano-seconds resolution */
1839
1840 #if 0
1841             msg_Dbg( p_demux, "Read() stream: %i, size: %i, PTS: %"PRId64,
1842                      i_stream, i_data_size, i_pts );
1843 #endif
1844
1845             p_block = block_New( p_demux, i_data_size );
1846             vlc_memcpy( p_block->p_buffer, p_data, i_data_size );
1847             p_block->i_pts = p_block->i_dts = i_pts;
1848             sample.p_sample->Release();
1849
1850             es_out_Control( p_demux->out, ES_OUT_SET_PCR, i_pts > 0 ? i_pts : 0 );
1851             es_out_Send( p_demux->out, p_stream->p_es, p_block );
1852
1853             i_samples--;
1854         }
1855     }
1856
1857     return 1;
1858 }
1859
1860 /*****************************************************************************
1861  * AccessControl:
1862  *****************************************************************************/
1863 static int AccessControl( access_t *p_access, int i_query, va_list args )
1864 {
1865     bool   *pb_bool;
1866     int          *pi_int;
1867     int64_t      *pi_64;
1868
1869     switch( i_query )
1870     {
1871     /* */
1872     case ACCESS_CAN_SEEK:
1873     case ACCESS_CAN_FASTSEEK:
1874     case ACCESS_CAN_PAUSE:
1875     case ACCESS_CAN_CONTROL_PACE:
1876         pb_bool = (bool*)va_arg( args, bool* );
1877         *pb_bool = false;
1878         break;
1879
1880     /* */
1881     case ACCESS_GET_PTS_DELAY:
1882         pi_64 = (int64_t*)va_arg( args, int64_t * );
1883         *pi_64 = (int64_t)var_GetInteger( p_access, "dshow-caching" ) * 1000;
1884         break;
1885
1886     /* */
1887     case ACCESS_SET_PAUSE_STATE:
1888     case ACCESS_GET_TITLE_INFO:
1889     case ACCESS_SET_TITLE:
1890     case ACCESS_SET_SEEKPOINT:
1891     case ACCESS_SET_PRIVATE_ID_STATE:
1892         return VLC_EGENERIC;
1893
1894     default:
1895         msg_Warn( p_access, "unimplemented query in control" );
1896         return VLC_EGENERIC;
1897     }
1898
1899     return VLC_SUCCESS;
1900 }
1901
1902 /****************************************************************************
1903  * DemuxControl:
1904  ****************************************************************************/
1905 static int DemuxControl( demux_t *p_demux, int i_query, va_list args )
1906 {
1907     bool *pb;
1908     int64_t    *pi64;
1909
1910     switch( i_query )
1911     {
1912     /* Special for access_demux */
1913     case DEMUX_CAN_PAUSE:
1914     case DEMUX_CAN_SEEK:
1915     case DEMUX_SET_PAUSE_STATE:
1916     case DEMUX_CAN_CONTROL_PACE:
1917         pb = (bool*)va_arg( args, bool * );
1918         *pb = false;
1919         return VLC_SUCCESS;
1920
1921     case DEMUX_GET_PTS_DELAY:
1922         pi64 = (int64_t*)va_arg( args, int64_t * );
1923         *pi64 = (int64_t)var_GetInteger( p_demux, "dshow-caching" ) * 1000;
1924         return VLC_SUCCESS;
1925
1926     case DEMUX_GET_TIME:
1927         pi64 = (int64_t*)va_arg( args, int64_t * );
1928         *pi64 = mdate();
1929         return VLC_SUCCESS;
1930
1931     /* TODO implement others */
1932     default:
1933         return VLC_EGENERIC;
1934     }
1935
1936     return VLC_EGENERIC;
1937 }
1938
1939 /*****************************************************************************
1940  * config variable callback
1941  *****************************************************************************/
1942 static int FindDevicesCallback( vlc_object_t *p_this, char const *psz_name,
1943                                vlc_value_t newval, vlc_value_t oldval, void * )
1944 {
1945     module_config_t *p_item;
1946     bool b_audio = false;
1947     int i;
1948
1949     p_item = config_FindConfig( p_this, psz_name );
1950     if( !p_item ) return VLC_SUCCESS;
1951
1952     if( !strcmp( psz_name, "dshow-adev" ) ) b_audio = true;
1953
1954     /* Clear-up the current list */
1955     if( p_item->i_list )
1956     {
1957         /* Keep the 2 first entries */
1958         for( i = 2; i < p_item->i_list; i++ )
1959         {
1960             free( const_cast<char *>(p_item->ppsz_list[i]) );
1961             free( const_cast<char *>(p_item->ppsz_list_text[i]) );
1962         }
1963         /* TODO: Remove when no more needed */
1964         p_item->ppsz_list[i] = NULL;
1965         p_item->ppsz_list_text[i] = NULL;
1966     }
1967     p_item->i_list = 2;
1968
1969     /* Find list of devices */
1970     list<string> list_devices;
1971
1972     /* Initialize OLE/COM */
1973     CoInitialize( 0 );
1974
1975     FindCaptureDevice( p_this, NULL, &list_devices, b_audio );
1976
1977     /* Uninitialize OLE/COM */
1978     CoUninitialize();
1979
1980     if( !list_devices.size() ) return VLC_SUCCESS;
1981
1982     p_item->ppsz_list =
1983         (char **)realloc( p_item->ppsz_list,
1984                           (list_devices.size()+3) * sizeof(char *) );
1985     p_item->ppsz_list_text =
1986         (char **)realloc( p_item->ppsz_list_text,
1987                           (list_devices.size()+3) * sizeof(char *) );
1988
1989     list<string>::iterator iter;
1990     for( iter = list_devices.begin(), i = 2; iter != list_devices.end();
1991          iter++, i++ )
1992     {
1993         p_item->ppsz_list[i] = strdup( iter->c_str() );
1994         p_item->ppsz_list_text[i] = NULL;
1995         p_item->i_list++;
1996     }
1997     p_item->ppsz_list[i] = NULL;
1998     p_item->ppsz_list_text[i] = NULL;
1999
2000     /* Signal change to the interface */
2001     p_item->b_dirty = true;
2002
2003     return VLC_SUCCESS;
2004 }
2005
2006 static int ConfigDevicesCallback( vlc_object_t *p_this, char const *psz_name,
2007                                vlc_value_t newval, vlc_value_t oldval, void * )
2008 {
2009     module_config_t *p_item;
2010     bool b_audio = false;
2011
2012     /* Initialize OLE/COM */
2013     CoInitialize( 0 );
2014
2015     p_item = config_FindConfig( p_this, psz_name );
2016     if( !p_item ) return VLC_SUCCESS;
2017
2018     if( !strcmp( psz_name, "dshow-adev" ) ) b_audio = true;
2019
2020     string devicename;
2021
2022     if( newval.psz_string && *newval.psz_string )
2023     {
2024         devicename = newval.psz_string;
2025     }
2026     else
2027     {
2028         /* If no device name was specified, pick the 1st one */
2029         list<string> list_devices;
2030
2031         /* Enumerate devices */
2032         FindCaptureDevice( p_this, NULL, &list_devices, b_audio );
2033         if( !list_devices.size() ) return VLC_EGENERIC;
2034         devicename = *list_devices.begin();
2035     }
2036
2037     IBaseFilter *p_device_filter =
2038         FindCaptureDevice( p_this, &devicename, NULL, b_audio );
2039     if( p_device_filter )
2040     {
2041         ShowPropertyPage( p_device_filter );
2042         p_device_filter->Release();
2043     }
2044     else
2045     {
2046         /* Uninitialize OLE/COM */
2047         CoUninitialize();
2048
2049         msg_Err( p_this, "didn't find device: %s", devicename.c_str() );
2050         return VLC_EGENERIC;
2051     }
2052
2053     /* Uninitialize OLE/COM */
2054     CoUninitialize();
2055
2056     return VLC_SUCCESS;
2057 }
2058
2059 /*****************************************************************************
2060  * Properties
2061  *****************************************************************************/
2062
2063 static void ShowPropertyPage( IUnknown *obj )
2064 {
2065     ISpecifyPropertyPages *p_spec;
2066     CAUUID cauuid;
2067
2068     HRESULT hr = obj->QueryInterface( IID_ISpecifyPropertyPages,
2069                                       (void **)&p_spec );
2070     if( FAILED(hr) ) return;
2071
2072     if( SUCCEEDED(p_spec->GetPages( &cauuid )) )
2073     {
2074         if( cauuid.cElems > 0 )
2075         {
2076             HWND hwnd_desktop = ::GetDesktopWindow();
2077
2078             OleCreatePropertyFrame( hwnd_desktop, 30, 30, NULL, 1, &obj,
2079                                     cauuid.cElems, cauuid.pElems, 0, 0, NULL );
2080
2081             CoTaskMemFree( cauuid.pElems );
2082         }
2083         p_spec->Release();
2084     }
2085 }
2086
2087 static void ShowDeviceProperties( vlc_object_t *p_this,
2088                                   ICaptureGraphBuilder2 *p_graph,
2089                                   IBaseFilter *p_device_filter,
2090                                   bool b_audio )
2091 {
2092     HRESULT hr;
2093     msg_Dbg( p_this, "configuring Device Properties" );
2094
2095     /*
2096      * Video or audio capture filter page
2097      */
2098     ShowPropertyPage( p_device_filter );
2099
2100     /*
2101      * Audio capture pin
2102      */
2103     if( p_graph && b_audio )
2104     {
2105         IAMStreamConfig *p_SC;
2106
2107         msg_Dbg( p_this, "showing WDM Audio Configuration Pages" );
2108
2109         hr = p_graph->FindInterface( &PIN_CATEGORY_CAPTURE,
2110                                      &MEDIATYPE_Audio, p_device_filter,
2111                                      IID_IAMStreamConfig, (void **)&p_SC );
2112         if( SUCCEEDED(hr) )
2113         {
2114             ShowPropertyPage(p_SC);
2115             p_SC->Release();
2116         }
2117
2118         /*
2119          * TV Audio filter
2120          */
2121         IAMTVAudio *p_TVA;
2122         HRESULT hr = p_graph->FindInterface( &PIN_CATEGORY_CAPTURE,
2123                                              &MEDIATYPE_Audio, p_device_filter,
2124                                              IID_IAMTVAudio, (void **)&p_TVA );
2125         if( SUCCEEDED(hr) )
2126         {
2127             ShowPropertyPage(p_TVA);
2128             p_TVA->Release();
2129         }
2130     }
2131
2132     /*
2133      * Video capture pin
2134      */
2135     if( p_graph && !b_audio )
2136     {
2137         IAMStreamConfig *p_SC;
2138
2139         msg_Dbg( p_this, "showing WDM Video Configuration Pages" );
2140
2141         hr = p_graph->FindInterface( &PIN_CATEGORY_CAPTURE,
2142                                      &MEDIATYPE_Interleaved, p_device_filter,
2143                                      IID_IAMStreamConfig, (void **)&p_SC );
2144         if( FAILED(hr) )
2145         {
2146             hr = p_graph->FindInterface( &PIN_CATEGORY_CAPTURE,
2147                                          &MEDIATYPE_Video, p_device_filter,
2148                                          IID_IAMStreamConfig, (void **)&p_SC );
2149         }
2150
2151         if( FAILED(hr) )
2152         {
2153             hr = p_graph->FindInterface( &PIN_CATEGORY_CAPTURE,
2154                                          &MEDIATYPE_Stream, p_device_filter,
2155                                          IID_IAMStreamConfig, (void **)&p_SC );
2156         }
2157
2158         if( SUCCEEDED(hr) )
2159         {
2160             ShowPropertyPage(p_SC);
2161             p_SC->Release();
2162         }
2163     }
2164 }
2165
2166 static void ShowTunerProperties( vlc_object_t *p_this,
2167                                  ICaptureGraphBuilder2 *p_graph,
2168                                  IBaseFilter *p_device_filter,
2169                                  bool b_audio )
2170 {
2171     HRESULT hr;
2172     msg_Dbg( p_this, "configuring Tuner Properties" );
2173
2174     if( !p_graph || b_audio ) return;
2175
2176     IAMTVTuner *p_TV;
2177     hr = p_graph->FindInterface( &PIN_CATEGORY_CAPTURE,
2178                                  &MEDIATYPE_Interleaved, p_device_filter,
2179                                  IID_IAMTVTuner, (void **)&p_TV );
2180     if( FAILED(hr) )
2181     {
2182         hr = p_graph->FindInterface( &PIN_CATEGORY_CAPTURE,
2183                                      &MEDIATYPE_Video, p_device_filter,
2184                                      IID_IAMTVTuner, (void **)&p_TV );
2185     }
2186
2187     if( FAILED(hr) )
2188     {
2189         hr = p_graph->FindInterface( &PIN_CATEGORY_CAPTURE,
2190                                      &MEDIATYPE_Stream, p_device_filter,
2191                                      IID_IAMTVTuner, (void **)&p_TV );
2192     }
2193
2194     if( SUCCEEDED(hr) )
2195     {
2196         ShowPropertyPage(p_TV);
2197         p_TV->Release();
2198     }
2199 }
2200
2201 static void ConfigTuner( vlc_object_t *p_this, ICaptureGraphBuilder2 *p_graph,
2202                          IBaseFilter *p_device_filter )
2203 {
2204     int i_channel, i_country, i_input, i_amtuner_mode;
2205     long l_modes = 0;
2206     IAMTVTuner *p_TV;
2207     HRESULT hr;
2208
2209     if( !p_graph ) return;
2210
2211     i_channel = var_GetInteger( p_this, "dshow-tuner-channel" );
2212     i_country = var_GetInteger( p_this, "dshow-tuner-country" );
2213     i_input = var_GetInteger( p_this, "dshow-tuner-input" );
2214     i_amtuner_mode = var_GetInteger( p_this, "dshow-amtuner-mode" );
2215
2216     if( !i_channel && !i_country && !i_input ) return; /* Nothing to do */
2217
2218     msg_Dbg( p_this, "tuner config: channel %i, country %i, input type %i",
2219              i_channel, i_country, i_input );
2220
2221     hr = p_graph->FindInterface( &PIN_CATEGORY_CAPTURE, &MEDIATYPE_Interleaved,
2222                                  p_device_filter, IID_IAMTVTuner,
2223                                  (void **)&p_TV );
2224     if( FAILED(hr) )
2225     {
2226         hr = p_graph->FindInterface( &PIN_CATEGORY_CAPTURE, &MEDIATYPE_Video,
2227                                      p_device_filter, IID_IAMTVTuner,
2228                                      (void **)&p_TV );
2229     }
2230
2231     if( FAILED(hr) )
2232     {
2233         hr = p_graph->FindInterface( &PIN_CATEGORY_CAPTURE, &MEDIATYPE_Stream,
2234                                      p_device_filter, IID_IAMTVTuner,
2235                                      (void **)&p_TV );
2236     }
2237
2238     if( FAILED(hr) )
2239     {
2240         msg_Dbg( p_this, "couldn't find tuner interface" );
2241         return;
2242     }
2243
2244     hr = p_TV->GetAvailableModes( &l_modes );
2245     if( SUCCEEDED(hr) && (l_modes & i_amtuner_mode) )
2246     {
2247         hr = p_TV->put_Mode( (AMTunerModeType)i_amtuner_mode );
2248     }
2249
2250     if( i_input == 1 ) p_TV->put_InputType( 0, TunerInputCable );
2251     else if( i_input == 2 ) p_TV->put_InputType( 0, TunerInputAntenna );
2252
2253     p_TV->put_CountryCode( i_country );
2254     p_TV->put_Channel( i_channel, AMTUNER_SUBCHAN_NO_TUNE,
2255                        AMTUNER_SUBCHAN_NO_TUNE );
2256     p_TV->Release();
2257 }