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