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