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