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