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