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