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