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