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