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