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