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