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