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