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