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