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