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