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