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