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