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