]> git.sesse.net Git - vlc/blob - modules/access/dshow/dshow.cpp
- added dshow-fps option to configure capture framerate
[vlc] / modules / access / dshow / dshow.cpp
1 /*****************************************************************************
2  * dshow.cpp : DirectShow access module for vlc
3  *****************************************************************************
4  * Copyright (C) 2002, 2003 VideoLAN
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., 59 Temple Place - Suite 330, Boston, MA  02111, 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_FALSE );
162
163     add_bool( "dshow-tuner", VLC_FALSE, NULL, TUNER_TEXT, TUNER_LONGTEXT,
164               VLC_FALSE );
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
210 } dshow_stream_t;
211
212 /*****************************************************************************
213  * DirectShow utility functions
214  *****************************************************************************/
215 static void CreateDirectShowGraph( access_sys_t *p_sys )
216 {
217     p_sys->i_crossbar_route_depth = 0;
218
219     /* Create directshow filter graph */
220     if( SUCCEEDED( CoCreateInstance( CLSID_FilterGraph, 0, CLSCTX_INPROC,
221                        (REFIID)IID_IFilterGraph, (void **)&p_sys->p_graph) ) )
222     {
223         /* Create directshow capture graph builder if available */
224         if( SUCCEEDED( CoCreateInstance( CLSID_CaptureGraphBuilder2, 0,
225                          CLSCTX_INPROC, (REFIID)IID_ICaptureGraphBuilder2,
226                          (void **)&p_sys->p_capture_graph_builder2 ) ) )
227         {
228             p_sys->p_capture_graph_builder2->
229                 SetFiltergraph((IGraphBuilder *)p_sys->p_graph);
230         }
231
232         p_sys->p_graph->QueryInterface( IID_IMediaControl,
233                                         (void **)&p_sys->p_control );
234     }
235 }
236
237 static void DeleteDirectShowGraph( access_sys_t *p_sys )
238 {
239     DeleteCrossbarRoutes( p_sys );
240
241     /* Remove filters from graph */
242     for( int i = 0; i < p_sys->i_streams; i++ )
243     {
244         p_sys->p_graph->RemoveFilter( p_sys->pp_streams[i]->p_capture_filter );
245         p_sys->p_graph->RemoveFilter( p_sys->pp_streams[i]->p_device_filter );
246         p_sys->pp_streams[i]->p_capture_filter->Release();
247         p_sys->pp_streams[i]->p_device_filter->Release();
248     }
249
250     /* Release directshow objects */
251     if( p_sys->p_control )
252     {
253         p_sys->p_control->Release();
254         p_sys->p_control = NULL;
255     }
256     if( p_sys->p_capture_graph_builder2 )
257     {
258         p_sys->p_capture_graph_builder2->Release();
259         p_sys->p_capture_graph_builder2 = NULL;
260     }
261
262     if( p_sys->p_graph )
263     {
264         p_sys->p_graph->Release();
265         p_sys->p_graph = NULL;
266     }
267 }
268
269 /*****************************************************************************
270  * CommonOpen: open direct show device
271  *****************************************************************************/
272 static int CommonOpen( vlc_object_t *p_this, access_sys_t *p_sys,
273                        vlc_bool_t b_access_demux )
274 {
275     vlc_value_t  val;
276     int i;
277
278     /* Get/parse options and open device(s) */
279     string vdevname, adevname;
280     int i_width = 0, i_height = 0, i_chroma = 0;
281     vlc_bool_t b_audio = VLC_TRUE;
282
283     var_Create( p_this, "dshow-config", VLC_VAR_BOOL | VLC_VAR_DOINHERIT );
284     var_Create( p_this, "dshow-tuner", VLC_VAR_BOOL | VLC_VAR_DOINHERIT );
285
286     var_Create( p_this, "dshow-vdev", VLC_VAR_STRING | VLC_VAR_DOINHERIT );
287     var_Get( p_this, "dshow-vdev", &val );
288     if( val.psz_string ) vdevname = string( val.psz_string );
289     if( val.psz_string ) free( val.psz_string );
290
291     var_Create( p_this, "dshow-adev", VLC_VAR_STRING | VLC_VAR_DOINHERIT );
292     var_Get( p_this, "dshow-adev", &val );
293     if( val.psz_string ) adevname = string( val.psz_string );
294     if( val.psz_string ) free( val.psz_string );
295
296     static struct {char *psz_size; int  i_width; int  i_height;} size_table[] =
297     { { "subqcif", 128, 96 }, { "qsif", 160, 120 }, { "qcif", 176, 144 },
298       { "sif", 320, 240 }, { "cif", 352, 288 }, { "cif", 640, 480 },
299       { 0, 0, 0 },
300     };
301
302     var_Create( p_this, "dshow-size", VLC_VAR_STRING | VLC_VAR_DOINHERIT );
303     var_Get( p_this, "dshow-size", &val );
304     if( val.psz_string && *val.psz_string )
305     {
306         for( i = 0; size_table[i].psz_size; i++ )
307         {
308             if( !strcmp( val.psz_string, size_table[i].psz_size ) )
309             {
310                 i_width = size_table[i].i_width;
311                 i_height = size_table[i].i_height;
312                 break;
313             }
314         }
315         if( !size_table[i].psz_size ) /* Try to parse "WidthxHeight" */
316         {
317             char *psz_parser;
318             i_width = strtol( val.psz_string, &psz_parser, 0 );
319             if( *psz_parser == 'x' || *psz_parser == 'X')
320             {
321                 i_height = strtol( psz_parser + 1, &psz_parser, 0 );
322             }
323             msg_Dbg( p_this, "Width x Height %dx%d", i_width, i_height );
324         }
325     }
326     if( val.psz_string ) free( val.psz_string );
327
328     var_Create( p_this, "dshow-chroma", VLC_VAR_STRING | VLC_VAR_DOINHERIT );
329     var_Get( p_this, "dshow-chroma", &val );
330     if( val.psz_string && strlen( val.psz_string ) >= 4 )
331     {
332         i_chroma = VLC_FOURCC( val.psz_string[0], val.psz_string[1],
333                                val.psz_string[2], val.psz_string[3] );
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         else if( p_stream->mt.majortype == MEDIATYPE_Audio )
535         {
536             es_format_Init( &fmt, AUDIO_ES, p_stream->i_fourcc );
537
538             fmt.audio.i_channels = p_stream->header.audio.nChannels;
539             fmt.audio.i_rate = p_stream->header.audio.nSamplesPerSec;
540             fmt.audio.i_bitspersample = p_stream->header.audio.wBitsPerSample;
541             fmt.audio.i_blockalign = fmt.audio.i_channels *
542                 fmt.audio.i_bitspersample / 8;
543             fmt.i_bitrate = fmt.audio.i_channels * fmt.audio.i_rate *
544                 fmt.audio.i_bitspersample;
545         }
546
547         p_stream->p_es = es_out_Add( p_demux->out, &fmt );
548     }
549
550     return VLC_SUCCESS;
551 }
552
553 /*****************************************************************************
554  * AccessOpen: open direct show device as an access module
555  *****************************************************************************/
556 static int AccessOpen( vlc_object_t *p_this )
557 {
558     access_t     *p_access = (access_t*)p_this;
559     access_sys_t *p_sys;
560
561     p_access->p_sys = p_sys = (access_sys_t *)malloc( sizeof( access_sys_t ) );
562     memset( p_sys, 0, sizeof( access_sys_t ) );
563
564     if( CommonOpen( p_this, p_sys, VLC_FALSE ) != VLC_SUCCESS )
565     {
566         CommonClose( p_this, p_sys );
567         return VLC_EGENERIC;
568     }
569
570     dshow_stream_t *p_stream = p_sys->pp_streams[0];
571
572     /* Check if we need to force demuxers */
573     if( !p_access->psz_demux || !*p_access->psz_demux )
574     {
575         if( p_stream->i_fourcc == VLC_FOURCC('d','v','s','l') ||
576             p_stream->i_fourcc == VLC_FOURCC('d','v','s','d') ||
577             p_stream->i_fourcc == VLC_FOURCC('d','v','h','d') )
578         {
579             p_access->psz_demux = strdup( "rawdv" );
580         }
581         else if( p_stream->i_fourcc == VLC_FOURCC('m','p','2','v') )
582         {
583             p_access->psz_demux = "mpgv";
584         }
585     }
586
587     /* Setup Access */
588     p_access->pf_read = NULL;
589     p_access->pf_block = ReadCompressed;
590     p_access->pf_control = AccessControl;
591     p_access->pf_seek = NULL;
592     p_access->info.i_update = 0;
593     p_access->info.i_size = 0;
594     p_access->info.i_pos = 0;
595     p_access->info.b_eof = VLC_FALSE;
596     p_access->info.i_title = 0;
597     p_access->info.i_seekpoint = 0;
598     p_access->p_sys = p_sys;
599
600     /* Everything is ready. Let's rock baby */
601     msg_Dbg( p_this, "Playing...");
602     p_sys->p_control->Run();
603
604     return VLC_SUCCESS;
605 }
606
607 /*****************************************************************************
608  * CommonClose: close device
609  *****************************************************************************/
610 static void CommonClose( vlc_object_t *p_this, access_sys_t *p_sys )
611 {
612     msg_Dbg( p_this, "Releasing DirectShow");
613
614     DeleteDirectShowGraph( p_sys );
615
616     /* Uninitialize OLE/COM */
617     CoUninitialize();
618
619     for( int i = 0; i < p_sys->i_streams; i++ ) delete p_sys->pp_streams[i];
620     if( p_sys->i_streams ) free( p_sys->pp_streams );
621
622     vlc_mutex_destroy( &p_sys->lock );
623     vlc_cond_destroy( &p_sys->wait );
624
625     free( p_sys );
626 }
627
628 /*****************************************************************************
629  * AccessClose: close device
630  *****************************************************************************/
631 static void AccessClose( vlc_object_t *p_this )
632 {
633     access_t     *p_access = (access_t *)p_this;
634     access_sys_t *p_sys    = p_access->p_sys;
635
636     /* Stop capturing stuff */
637     p_sys->p_control->Stop();
638
639     CommonClose( p_this, p_sys );
640 }
641
642 /*****************************************************************************
643  * DemuxClose: close device
644  *****************************************************************************/
645 static void DemuxClose( vlc_object_t *p_this )
646 {
647     demux_t      *p_demux = (demux_t *)p_this;
648     access_sys_t *p_sys   = (access_sys_t *)p_demux->p_sys;
649
650     /* Stop capturing stuff */
651     p_sys->p_control->Stop();
652
653     CommonClose( p_this, p_sys );
654 }
655
656 /****************************************************************************
657  * ConnectFilters
658  ****************************************************************************/
659 static bool ConnectFilters( vlc_object_t *p_this, access_sys_t *p_sys,
660                             IBaseFilter *p_filter,
661                             CaptureFilter *p_capture_filter )
662 {
663     CapturePin *p_input_pin = p_capture_filter->CustomGetPin();
664
665     AM_MEDIA_TYPE mediaType = p_input_pin->CustomGetMediaType();
666
667     if( p_sys->p_capture_graph_builder2 )
668     {
669         if( FAILED(p_sys->p_capture_graph_builder2->
670                 RenderStream( &PIN_CATEGORY_CAPTURE, &mediaType.majortype,
671                               p_filter, 0, (IBaseFilter *)p_capture_filter )) )
672         {
673             return false;
674         }
675
676         // Sort out all the possible video inputs
677         // The class needs to be given the capture filters ANALOGVIDEO input pin
678         IEnumPins *pins = 0;
679         if( ( mediaType.majortype == MEDIATYPE_Video ||
680               mediaType.majortype == MEDIATYPE_Stream ) &&
681             SUCCEEDED(p_filter->EnumPins(&pins)) )
682         {
683             IPin        *pP = 0;
684             ULONG        n;
685             PIN_INFO     pinInfo;
686             BOOL         Found = FALSE;
687             IKsPropertySet *pKs=0;
688             GUID guid;
689             DWORD dw;
690
691             while( !Found && ( S_OK == pins->Next(1, &pP, &n) ) )
692             {
693                 if( S_OK == pP->QueryPinInfo(&pinInfo) )
694                 {
695                     // is this pin an ANALOGVIDEOIN input pin?
696                     if( pinInfo.dir == PINDIR_INPUT &&
697                         pP->QueryInterface( IID_IKsPropertySet,
698                                             (void **)&pKs ) == S_OK )
699                     {
700                         if( pKs->Get( AMPROPSETID_Pin,
701                                       AMPROPERTY_PIN_CATEGORY, NULL, 0,
702                                       &guid, sizeof(GUID), &dw ) == S_OK )
703                         {
704                             if( guid == PIN_CATEGORY_ANALOGVIDEOIN )
705                             {
706                                 // recursively search crossbar routes
707                                 FindCrossbarRoutes( p_this, p_sys, pP, 0 );
708                                 // found it
709                                 Found = TRUE;
710                             }
711                         }
712                         pKs->Release();
713                     }
714                     pinInfo.pFilter->Release();
715                 }
716                 pP->Release();
717             }
718             pins->Release();
719         }
720         return true;
721     }
722     else
723     {
724         IEnumPins *p_enumpins;
725         IPin *p_pin;
726
727         if( S_OK != p_filter->EnumPins( &p_enumpins ) ) return false;
728
729         while( S_OK == p_enumpins->Next( 1, &p_pin, NULL ) )
730         {
731             PIN_DIRECTION pin_dir;
732             p_pin->QueryDirection( &pin_dir );
733
734             if( pin_dir == PINDIR_OUTPUT &&
735                 p_sys->p_graph->ConnectDirect( p_pin, (IPin *)p_input_pin,
736                                                0 ) == S_OK )
737             {
738                 p_pin->Release();
739                 p_enumpins->Release();
740                 return true;
741             }
742             p_pin->Release();
743         }
744
745         p_enumpins->Release();
746         return false;
747     }
748 }
749
750 /*
751  * get fourcc priority from arbritary preference, the higher the better
752  */
753 static int GetFourCCPriority( int i_fourcc )
754 {
755     switch( i_fourcc )
756     {
757     case VLC_FOURCC('I','4','2','0'):
758     case VLC_FOURCC('f','l','3','2'):
759         return 9;
760     case VLC_FOURCC('Y','V','1','2'):
761     case VLC_FOURCC('a','r','a','w'):
762         return 8;
763     case VLC_FOURCC('R','V','2','4'):
764         return 7;
765     case VLC_FOURCC('Y','U','Y','2'):
766     case VLC_FOURCC('R','V','3','2'):
767     case VLC_FOURCC('R','G','B','A'):
768         return 6;
769     }
770
771     return 0;
772 }
773
774 #define MAX_MEDIA_TYPES 32
775
776 static int OpenDevice( vlc_object_t *p_this, access_sys_t *p_sys,
777                        string devicename, vlc_bool_t b_audio )
778 {
779     /* See if device is already opened */
780     for( int i = 0; i < p_sys->i_streams; i++ )
781     {
782         if( devicename.size() &&
783             p_sys->pp_streams[i]->devicename == devicename )
784         {
785             /* Already opened */
786             return VLC_SUCCESS;
787         }
788     }
789
790     list<string> list_devices;
791
792     /* Enumerate devices and display their names */
793     FindCaptureDevice( p_this, NULL, &list_devices, b_audio );
794
795     if( !list_devices.size() )
796         return VLC_EGENERIC;
797
798     list<string>::iterator iter;
799     for( iter = list_devices.begin(); iter != list_devices.end(); iter++ )
800         msg_Dbg( p_this, "found device: %s", iter->c_str() );
801
802     /* If no device name was specified, pick the 1st one */
803     if( devicename.size() == 0 )
804     {
805         devicename = *list_devices.begin();
806     }
807
808     // Use the system device enumerator and class enumerator to find
809     // a capture/preview device, such as a desktop USB video camera.
810     IBaseFilter *p_device_filter =
811         FindCaptureDevice( p_this, &devicename, 0, b_audio );
812     if( p_device_filter )
813         msg_Dbg( p_this, "using device: %s", devicename.c_str() );
814     else
815     {
816         msg_Err( p_this, "can't use device: %s, unsupported device type",
817                  devicename.c_str() );
818         return VLC_EGENERIC;
819     }
820
821     // Retreive acceptable media types supported by device
822     AM_MEDIA_TYPE media_types[MAX_MEDIA_TYPES];
823     size_t media_count =
824         EnumDeviceCaps( p_this, p_device_filter, p_sys->i_chroma,
825                         p_sys->i_width, p_sys->i_height,
826                         0, 0, 0, media_types, MAX_MEDIA_TYPES );
827
828     /* Find out if the pin handles MEDIATYPE_Stream, in which case we
829      * won't add a prefered media type as this doesn't seem to work well
830      * -- to investigate. */
831     vlc_bool_t b_stream_type = VLC_FALSE;
832     for( size_t i = 0; i < media_count; i++ )
833     {
834         if( media_types[i].majortype == MEDIATYPE_Stream )
835         {
836             b_stream_type = VLC_TRUE;
837             break;
838         }
839     }
840
841     size_t mt_count = 0;
842     AM_MEDIA_TYPE *mt = NULL;
843
844     if( !b_stream_type && !b_audio )
845     {
846         // Insert prefered video media type
847         AM_MEDIA_TYPE mtr;
848         VIDEOINFOHEADER vh;
849
850         mtr.majortype            = MEDIATYPE_Video;
851         mtr.subtype              = MEDIASUBTYPE_I420;
852         mtr.bFixedSizeSamples    = TRUE;
853         mtr.bTemporalCompression = FALSE;
854         mtr.pUnk                 = NULL;
855         mtr.formattype           = FORMAT_VideoInfo;
856         mtr.cbFormat             = sizeof(vh);
857         mtr.pbFormat             = (BYTE *)&vh;
858
859         memset(&vh, 0, sizeof(vh));
860
861         vh.bmiHeader.biSize   = sizeof(vh.bmiHeader);
862         vh.bmiHeader.biWidth  = p_sys->i_width > 0 ? p_sys->i_width : 320;
863         vh.bmiHeader.biHeight = p_sys->i_height > 0 ? p_sys->i_height : 240;
864         vh.bmiHeader.biPlanes      = 3;
865         vh.bmiHeader.biBitCount    = 12;
866         vh.bmiHeader.biCompression = VLC_FOURCC('I','4','2','0');
867         vh.bmiHeader.biSizeImage   = vh.bmiHeader.biWidth * 12 *
868             vh.bmiHeader.biHeight / 8;
869         mtr.lSampleSize            = vh.bmiHeader.biSizeImage;
870
871         mt_count = 1;
872         mt = (AM_MEDIA_TYPE *)malloc( sizeof(AM_MEDIA_TYPE)*mt_count );
873         CopyMediaType(mt, &mtr);
874     }
875     else if( !b_stream_type )
876     {
877         // Insert prefered audio media type
878         AM_MEDIA_TYPE mtr;
879         WAVEFORMATEX wf;
880
881         mtr.majortype            = MEDIATYPE_Audio;
882         mtr.subtype              = MEDIASUBTYPE_PCM;
883         mtr.bFixedSizeSamples    = TRUE;
884         mtr.bTemporalCompression = FALSE;
885         mtr.lSampleSize          = 0;
886         mtr.pUnk                 = NULL;
887         mtr.formattype           = FORMAT_WaveFormatEx;
888         mtr.cbFormat             = sizeof(wf);
889         mtr.pbFormat             = (BYTE *)&wf;
890
891         memset(&wf, 0, sizeof(wf));
892
893         wf.wFormatTag = WAVE_FORMAT_PCM;
894         wf.nChannels = 2;
895         wf.nSamplesPerSec = 44100;
896         wf.wBitsPerSample = 16;
897         wf.nBlockAlign = wf.nSamplesPerSec * wf.wBitsPerSample / 8;
898         wf.nAvgBytesPerSec = wf.nSamplesPerSec * wf.nBlockAlign;
899         wf.cbSize = 0;
900
901         mt_count = 1;
902         mt = (AM_MEDIA_TYPE *)malloc( sizeof(AM_MEDIA_TYPE)*mt_count );
903         CopyMediaType(mt, &mtr);
904     }
905
906     if( media_count > 0 )
907     {
908         mt = (AM_MEDIA_TYPE *)realloc( mt, sizeof(AM_MEDIA_TYPE) *
909                                        (mt_count + media_count) );
910
911         // Order and copy returned media types according to arbitrary
912         // fourcc priority
913         for( size_t c = 0; c < media_count; c++ )
914         {
915             int slot_priority =
916                 GetFourCCPriority(GetFourCCFromMediaType(media_types[c]));
917             size_t slot_copy = c;
918             for( size_t d = c+1; d < media_count; d++ )
919             {
920                 int priority =
921                     GetFourCCPriority(GetFourCCFromMediaType(media_types[d]));
922                 if( priority > slot_priority )
923                 {
924                     slot_priority = priority;
925                     slot_copy = d;
926                 }
927             }
928             if( slot_copy != c )
929             {
930                 mt[c+mt_count] = media_types[slot_copy];
931                 media_types[slot_copy] = media_types[c];
932             }
933             else
934             {
935                 mt[c+mt_count] = media_types[c];
936             }
937         }
938         mt_count += media_count;
939     }
940
941     /* Create and add our capture filter */
942     CaptureFilter *p_capture_filter =
943         new CaptureFilter( p_this, p_sys, mt, mt_count );
944     p_sys->p_graph->AddFilter( p_capture_filter, 0 );
945
946     /* Add the device filter to the graph (seems necessary with VfW before
947      * accessing pin attributes). */
948     p_sys->p_graph->AddFilter( p_device_filter, 0 );
949
950     /* Attempt to connect one of this device's capture output pins */
951     msg_Dbg( p_this, "connecting filters" );
952     if( ConnectFilters( p_this, p_sys, p_device_filter, p_capture_filter ) )
953     {
954         /* Success */
955         msg_Dbg( p_this, "filters connected successfully !" );
956
957         dshow_stream_t dshow_stream;
958         dshow_stream.b_pts = VLC_FALSE;
959         dshow_stream.p_es = 0;
960         dshow_stream.mt =
961             p_capture_filter->CustomGetPin()->CustomGetMediaType();
962
963         /* Show Device properties. Done here so the VLC stream is setup with
964          * the proper parameters. */
965         vlc_value_t val;
966         var_Get( p_this, "dshow-config", &val );
967         if( val.b_bool )
968         {
969             ShowDeviceProperties( p_this, p_sys->p_capture_graph_builder2,
970                                   p_device_filter, b_audio );
971         }
972
973         ConfigTuner( p_this, p_sys->p_capture_graph_builder2,
974                      p_device_filter );
975
976         var_Get( p_this, "dshow-tuner", &val );
977         if( val.b_bool && dshow_stream.mt.majortype != MEDIATYPE_Stream )
978         {
979             /* FIXME: we do MEDIATYPE_Stream later so we don't do it twice. */
980             ShowTunerProperties( p_this, p_sys->p_capture_graph_builder2,
981                                  p_device_filter, b_audio );
982         }
983
984         dshow_stream.mt =
985             p_capture_filter->CustomGetPin()->CustomGetMediaType();
986
987         dshow_stream.i_fourcc = GetFourCCFromMediaType( dshow_stream.mt );
988         if( dshow_stream.i_fourcc )
989         {
990             if( dshow_stream.mt.majortype == MEDIATYPE_Video )
991             {
992                 dshow_stream.header.video =
993                     *(VIDEOINFOHEADER *)dshow_stream.mt.pbFormat;
994                 msg_Dbg( p_this, "MEDIATYPE_Video" );
995                 msg_Dbg( p_this, "selected video pin accepts format: %4.4s",
996                          (char *)&dshow_stream.i_fourcc);
997             }
998             else if( dshow_stream.mt.majortype == MEDIATYPE_Audio )
999             {
1000                 dshow_stream.header.audio =
1001                     *(WAVEFORMATEX *)dshow_stream.mt.pbFormat;
1002                 msg_Dbg( p_this, "MEDIATYPE_Audio" );
1003                 msg_Dbg( p_this, "selected audio pin accepts format: %4.4s",
1004                          (char *)&dshow_stream.i_fourcc);
1005             }
1006             else if( dshow_stream.mt.majortype == MEDIATYPE_Stream )
1007             {
1008                 msg_Dbg( p_this, "MEDIATYPE_Stream" );
1009                 msg_Dbg( p_this, "selected stream pin accepts format: %4.4s",
1010                          (char *)&dshow_stream.i_fourcc);
1011             }
1012             else
1013             {
1014                 msg_Dbg( p_this, "unknown stream majortype" );
1015                 goto fail;
1016             }
1017
1018             /* Add directshow elementary stream to our list */
1019             dshow_stream.p_device_filter = p_device_filter;
1020             dshow_stream.p_capture_filter = p_capture_filter;
1021
1022             p_sys->pp_streams = (dshow_stream_t **)realloc( p_sys->pp_streams,
1023                 sizeof(dshow_stream_t *) * (p_sys->i_streams + 1) );
1024             p_sys->pp_streams[p_sys->i_streams] = new dshow_stream_t;
1025             *p_sys->pp_streams[p_sys->i_streams++] = dshow_stream;
1026
1027             return VLC_SUCCESS;
1028         }
1029     }
1030
1031  fail:
1032     /* Remove filters from graph */
1033     p_sys->p_graph->RemoveFilter( p_device_filter );
1034     p_sys->p_graph->RemoveFilter( p_capture_filter );
1035
1036     /* Release objects */
1037     p_device_filter->Release();
1038     p_capture_filter->Release();
1039
1040     return VLC_EGENERIC;
1041 }
1042
1043 static IBaseFilter *
1044 FindCaptureDevice( vlc_object_t *p_this, string *p_devicename,
1045                    list<string> *p_listdevices, vlc_bool_t b_audio )
1046 {
1047     IBaseFilter *p_base_filter = NULL;
1048     IMoniker *p_moniker = NULL;
1049     ULONG i_fetched;
1050     HRESULT hr;
1051
1052     /* Create the system device enumerator */
1053     ICreateDevEnum *p_dev_enum = NULL;
1054
1055     hr = CoCreateInstance( CLSID_SystemDeviceEnum, NULL, CLSCTX_INPROC,
1056                            IID_ICreateDevEnum, (void **)&p_dev_enum );
1057     if( FAILED(hr) )
1058     {
1059         msg_Err( p_this, "failed to create the device enumerator (0x%lx)", hr);
1060         return NULL;
1061     }
1062
1063     /* Create an enumerator for the video capture devices */
1064     IEnumMoniker *p_class_enum = NULL;
1065     if( !b_audio )
1066         hr = p_dev_enum->CreateClassEnumerator( CLSID_VideoInputDeviceCategory,
1067                                                 &p_class_enum, 0 );
1068     else
1069         hr = p_dev_enum->CreateClassEnumerator( CLSID_AudioInputDeviceCategory,
1070                                                 &p_class_enum, 0 );
1071     p_dev_enum->Release();
1072     if( FAILED(hr) )
1073     {
1074         msg_Err( p_this, "failed to create the class enumerator (0x%lx)", hr );
1075         return NULL;
1076     }
1077
1078     /* If there are no enumerators for the requested type, then
1079      * CreateClassEnumerator will succeed, but p_class_enum will be NULL */
1080     if( p_class_enum == NULL )
1081     {
1082         msg_Err( p_this, "no capture device was detected" );
1083         return NULL;
1084     }
1085
1086     /* Enumerate the devices */
1087
1088     /* Note that if the Next() call succeeds but there are no monikers,
1089      * it will return S_FALSE (which is not a failure). Therefore, we check
1090      * that the return code is S_OK instead of using SUCCEEDED() macro. */
1091
1092     while( p_class_enum->Next( 1, &p_moniker, &i_fetched ) == S_OK )
1093     {
1094         /* Getting the property page to get the device name */
1095         IPropertyBag *p_bag;
1096         hr = p_moniker->BindToStorage( 0, 0, IID_IPropertyBag,
1097                                        (void **)&p_bag );
1098         if( SUCCEEDED(hr) )
1099         {
1100             VARIANT var;
1101             var.vt = VT_BSTR;
1102             hr = p_bag->Read( L"FriendlyName", &var, NULL );
1103             p_bag->Release();
1104             if( SUCCEEDED(hr) )
1105             {
1106                 int i_convert = WideCharToMultiByte(CP_ACP, 0, var.bstrVal,
1107                         SysStringLen(var.bstrVal), NULL, 0, NULL, NULL);
1108                 char *p_buf = (char *)alloca( i_convert ); p_buf[0] = 0;
1109                 WideCharToMultiByte( CP_ACP, 0, var.bstrVal,
1110                         SysStringLen(var.bstrVal), p_buf, i_convert, NULL, NULL );
1111                 SysFreeString(var.bstrVal);
1112
1113                 if( p_listdevices ) p_listdevices->push_back( p_buf );
1114
1115                 if( p_devicename && *p_devicename == string(p_buf) )
1116                 {
1117                     /* Bind Moniker to a filter object */
1118                     hr = p_moniker->BindToObject( 0, 0, IID_IBaseFilter,
1119                                                   (void **)&p_base_filter );
1120                     if( FAILED(hr) )
1121                     {
1122                         msg_Err( p_this, "couldn't bind moniker to filter "
1123                                  "object (0x%lx)", hr );
1124                         p_moniker->Release();
1125                         p_class_enum->Release();
1126                         return NULL;
1127                     }
1128                     p_moniker->Release();
1129                     p_class_enum->Release();
1130                     return p_base_filter;
1131                 }
1132             }
1133         }
1134
1135         p_moniker->Release();
1136     }
1137
1138     p_class_enum->Release();
1139     return NULL;
1140 }
1141
1142 static size_t EnumDeviceCaps( vlc_object_t *p_this, IBaseFilter *p_filter,
1143                               int i_fourcc, int i_width, int i_height,
1144                               int i_channels, int i_samplespersec,
1145                               int i_bitspersample, AM_MEDIA_TYPE *mt,
1146                               size_t mt_max )
1147 {
1148     IEnumPins *p_enumpins;
1149     IPin *p_output_pin;
1150     IEnumMediaTypes *p_enummt;
1151     size_t mt_count = 0;
1152
1153     LONGLONG i_AvgTimePerFrame = 0;
1154     float r_fps = var_GetFloat( p_this, "dshow-fps" );
1155     if( r_fps )
1156         i_AvgTimePerFrame = 10000000000LL/(LONGLONG)(r_fps*1000.0f);
1157
1158     if( FAILED(p_filter->EnumPins( &p_enumpins )) )
1159     {
1160         msg_Dbg( p_this, "EnumDeviceCaps failed: no pin enumeration !");
1161         return 0;
1162     }
1163
1164     while( S_OK == p_enumpins->Next( 1, &p_output_pin, NULL ) )
1165     {
1166         PIN_INFO info;
1167
1168         if( S_OK == p_output_pin->QueryPinInfo( &info ) )
1169         {
1170             msg_Dbg( p_this, "EnumDeviceCaps: %s pin: %S",
1171                      info.dir == PINDIR_INPUT ? "input" : "output",
1172                      info.achName );
1173             if( info.pFilter ) info.pFilter->Release();
1174         }
1175
1176         p_output_pin->Release();
1177     }
1178
1179     p_enumpins->Reset();
1180
1181     while( !mt_count && p_enumpins->Next( 1, &p_output_pin, NULL ) == S_OK )
1182     {
1183         PIN_INFO info;
1184
1185         if( S_OK == p_output_pin->QueryPinInfo( &info ) )
1186         {
1187             if( info.pFilter ) info.pFilter->Release();
1188             if( info.dir == PINDIR_INPUT )
1189             {
1190                 p_output_pin->Release();
1191                 continue;
1192             }
1193             msg_Dbg( p_this, "EnumDeviceCaps: trying pin %S", info.achName );
1194         }
1195
1196         AM_MEDIA_TYPE *p_mt;
1197
1198         /*
1199         ** Configure pin with a default compatible media if possible
1200         */
1201
1202         IAMStreamConfig *pSC;
1203         if( SUCCEEDED(p_output_pin->QueryInterface( IID_IAMStreamConfig,
1204                                             (void **)&pSC )) )
1205         {
1206             int piCount, piSize;
1207             if( SUCCEEDED(pSC->GetNumberOfCapabilities(&piCount, &piSize)) )
1208             {
1209                 BYTE *pSCC= (BYTE *)CoTaskMemAlloc(piSize);
1210                 if( NULL != pSCC )
1211                 {
1212                     for( int i=0; i<piCount; ++i )
1213                     {
1214                         if( SUCCEEDED(pSC->GetStreamCaps(i, &p_mt, pSCC)) )
1215                         {
1216                             int i_current_fourcc = GetFourCCFromMediaType( *p_mt );
1217
1218                             if( !i_current_fourcc || (i_fourcc && (i_current_fourcc != i_fourcc)) )
1219                             {
1220                                 // incompatible or unrecognized chroma, try next media type
1221                                 FreeMediaType( *p_mt );
1222                                 CoTaskMemFree( (PVOID)p_mt );
1223                                 continue;
1224                             }
1225
1226                             if( MEDIATYPE_Video == p_mt->majortype
1227                                     && FORMAT_VideoInfo == p_mt->formattype )
1228                             {
1229                                 VIDEO_STREAM_CONFIG_CAPS *pVSCC = reinterpret_cast<VIDEO_STREAM_CONFIG_CAPS*>(pSCC);
1230                                 VIDEOINFOHEADER *pVih = reinterpret_cast<VIDEOINFOHEADER*>(p_mt->pbFormat);
1231
1232                                 if( i_AvgTimePerFrame )
1233                                 {
1234                                     if( pVSCC->MinFrameInterval > i_AvgTimePerFrame
1235                                       || i_AvgTimePerFrame > pVSCC->MaxFrameInterval )
1236                                     {
1237                                         // required frame rate not compatible, try next media type
1238                                         FreeMediaType( *p_mt );
1239                                         CoTaskMemFree( (PVOID)p_mt );
1240                                         continue;
1241                                     }
1242                                     pVih->AvgTimePerFrame = i_AvgTimePerFrame;
1243                                 }
1244
1245                                 if( i_width )
1246                                 {
1247                                     if( i_width % pVSCC->OutputGranularityX
1248                                      || pVSCC->MinOutputSize.cx > i_width
1249                                      || i_width > pVSCC->MaxOutputSize.cx )
1250                                     {
1251                                         // required width not compatible, try next media type
1252                                         FreeMediaType( *p_mt );
1253                                         CoTaskMemFree( (PVOID)p_mt );
1254                                         continue;
1255                                     }
1256                                     pVih->bmiHeader.biWidth = i_width;
1257                                 }
1258
1259                                 if( i_height )
1260                                 {
1261                                     if( i_height % pVSCC->OutputGranularityY
1262                                      || pVSCC->MinOutputSize.cy > i_height 
1263                                      || i_height > pVSCC->MaxOutputSize.cy )
1264                                     {
1265                                         // required height not compatible, try next media type
1266                                         FreeMediaType( *p_mt );
1267                                         CoTaskMemFree( (PVOID)p_mt );
1268                                         continue;
1269                                     }
1270                                     pVih->bmiHeader.biHeight = i_height;
1271                                 }
1272
1273                                 // Set the sample size and image size.
1274                                 // (Round the image width up to a DWORD boundary.)
1275                                 p_mt->lSampleSize = pVih->bmiHeader.biSizeImage = 
1276                                     ((pVih->bmiHeader.biWidth + 3) & ~3) *
1277                                     pVih->bmiHeader.biHeight * (pVih->bmiHeader.biBitCount>>3);
1278
1279                                 // no cropping, use full video input buffer
1280                                 memset(&(pVih->rcSource), 0, sizeof(RECT));
1281                                 memset(&(pVih->rcTarget), 0, sizeof(RECT));
1282
1283                                 // select this format as default
1284                                 if( SUCCEEDED( pSC->SetFormat(p_mt) ) )
1285                                 {
1286                                     msg_Dbg( p_this, "EnumDeviceCaps: input pin video format configured");
1287                                     // no need to check any more media types 
1288                                     i = piCount;
1289                                 }
1290                                 else FreeMediaType( *p_mt );
1291                             }
1292                             else if( p_mt->majortype == MEDIATYPE_Audio
1293                                     && p_mt->formattype == FORMAT_WaveFormatEx )
1294                             {
1295                                 AUDIO_STREAM_CONFIG_CAPS *pASCC = reinterpret_cast<AUDIO_STREAM_CONFIG_CAPS*>(pSCC);
1296                                 WAVEFORMATEX *pWfx = reinterpret_cast<WAVEFORMATEX*>(p_mt->pbFormat);
1297
1298                                 if( i_channels )
1299                                 {
1300                                     if( i_channels % pASCC->ChannelsGranularity
1301                                      || (unsigned int)i_channels < pASCC->MinimumChannels
1302                                      || (unsigned int)i_channels > pASCC->MaximumChannels )
1303                                     {
1304                                         // required channels not compatible, try next media type
1305                                         FreeMediaType( *p_mt );
1306                                         CoTaskMemFree( (PVOID)p_mt );
1307                                         continue;
1308                                     }
1309                                     pWfx->nChannels = i_channels;
1310                                 }
1311
1312                                 if( i_samplespersec )
1313                                 {
1314                                     if( i_samplespersec % pASCC->BitsPerSampleGranularity
1315                                      || (unsigned int)i_samplespersec < pASCC->MinimumSampleFrequency
1316                                      || (unsigned int)i_samplespersec > pASCC->MaximumSampleFrequency )
1317                                     {
1318                                         // required sampling rate not compatible, try next media type
1319                                         FreeMediaType( *p_mt );
1320                                         CoTaskMemFree( (PVOID)p_mt );
1321                                         continue;
1322                                     }
1323                                     pWfx->nSamplesPerSec = i_samplespersec;
1324                                 }
1325
1326                                 if( i_bitspersample )
1327                                 {
1328                                     if( i_bitspersample % pASCC->BitsPerSampleGranularity
1329                                      || (unsigned int)i_bitspersample < pASCC->MinimumBitsPerSample
1330                                      || (unsigned int)i_bitspersample > pASCC->MaximumBitsPerSample )
1331                                     {
1332                                         // required sample size not compatible, try next media type
1333                                         FreeMediaType( *p_mt );
1334                                         CoTaskMemFree( (PVOID)p_mt );
1335                                         continue;
1336                                     }
1337                                     pWfx->wBitsPerSample = i_bitspersample;
1338                                 }
1339
1340                                 // select this format as default
1341                                 if( SUCCEEDED( pSC->SetFormat(p_mt) ) )
1342                                 {
1343                                     msg_Dbg( p_this, "EnumDeviceCaps: input pin default format configured");
1344                                     // no need to check any more media types 
1345                                     i = piCount;
1346                                 }
1347                             }
1348                             FreeMediaType( *p_mt );
1349                             CoTaskMemFree( (PVOID)p_mt );
1350                         }
1351                     }
1352                     CoTaskMemFree( (LPVOID)pSCC );
1353                 }
1354             }
1355             pSC->Release();
1356         }
1357
1358         /*
1359         ** Probe pin for available medias (may be a previously configured one)
1360         */
1361
1362         if( FAILED( p_output_pin->EnumMediaTypes( &p_enummt ) ) )
1363         {
1364             p_output_pin->Release();
1365             continue;
1366         }
1367
1368
1369         while( p_enummt->Next( 1, &p_mt, NULL ) == S_OK )
1370         {
1371             int i_current_fourcc = GetFourCCFromMediaType( *p_mt );
1372             if( i_current_fourcc && p_mt->majortype == MEDIATYPE_Video
1373                 && p_mt->formattype == FORMAT_VideoInfo )
1374             {
1375                 int i_current_width = ((VIDEOINFOHEADER *)p_mt->pbFormat)->bmiHeader.biWidth;
1376                 int i_current_height = ((VIDEOINFOHEADER *)p_mt->pbFormat)->bmiHeader.biHeight;
1377                 LONGLONG i_current_atpf = ((VIDEOINFOHEADER *)p_mt->pbFormat)->AvgTimePerFrame;
1378
1379                 if( i_current_height < 0 )
1380                     i_current_height = -i_current_height; 
1381
1382                 msg_Dbg( p_this, "EnumDeviceCaps: input pin "
1383                          "accepts chroma: %4.4s, width:%i, height:%i, fps:%f",
1384                          (char *)&i_current_fourcc, i_current_width,
1385                          i_current_height, (10000000.0f/((float)i_current_atpf)) );
1386
1387                 if( ( !i_fourcc || i_fourcc == i_current_fourcc ) &&
1388                     ( !i_width || i_width == i_current_width ) &&
1389                     ( !i_height || i_height == i_current_height ) &&
1390                     ( !i_AvgTimePerFrame || i_AvgTimePerFrame == i_current_atpf ) &&
1391                     mt_count < mt_max )
1392                 {
1393                     /* Pick match */
1394                     mt[mt_count++] = *p_mt;
1395                 }
1396                 else FreeMediaType( *p_mt );
1397             }
1398             else if( i_current_fourcc && p_mt->majortype == MEDIATYPE_Audio 
1399                     && p_mt->formattype == FORMAT_WaveFormatEx)
1400             {
1401                 int i_current_channels =
1402                     ((WAVEFORMATEX *)p_mt->pbFormat)->nChannels;
1403                 int i_current_samplespersec =
1404                     ((WAVEFORMATEX *)p_mt->pbFormat)->nSamplesPerSec;
1405                 int i_current_bitspersample =
1406                     ((WAVEFORMATEX *)p_mt->pbFormat)->wBitsPerSample;
1407
1408                 msg_Dbg( p_this, "EnumDeviceCaps: input pin "
1409                          "accepts format: %4.4s, channels:%i, "
1410                          "samples/sec:%i bits/sample:%i",
1411                          (char *)&i_current_fourcc, i_current_channels,
1412                          i_current_samplespersec, i_current_bitspersample);
1413
1414                 if( (!i_channels || i_channels == i_current_channels) &&
1415                     (!i_samplespersec ||
1416                      i_samplespersec == i_current_samplespersec) &&
1417                     (!i_bitspersample ||
1418                      i_bitspersample == i_current_bitspersample) &&
1419                     mt_count < mt_max )
1420                 {
1421                     /* Pick  match */
1422                     mt[mt_count++] = *p_mt;
1423
1424                     /* Setup a few properties like the audio latency */
1425                     IAMBufferNegotiation *p_ambuf;
1426                     if( SUCCEEDED( p_output_pin->QueryInterface(
1427                           IID_IAMBufferNegotiation, (void **)&p_ambuf ) ) )
1428                     {
1429                         ALLOCATOR_PROPERTIES AllocProp;
1430                         AllocProp.cbAlign = -1;
1431
1432                         /* 100 ms of latency */
1433                         AllocProp.cbBuffer = i_current_channels *
1434                           i_current_samplespersec *
1435                           i_current_bitspersample / 8 / 10;
1436
1437                         AllocProp.cbPrefix = -1;
1438                         AllocProp.cBuffers = -1;
1439                         p_ambuf->SuggestAllocatorProperties( &AllocProp );
1440                         p_ambuf->Release();
1441                     }
1442                 }
1443                 else FreeMediaType( *p_mt );
1444             }
1445             else if( i_current_fourcc && p_mt->majortype == MEDIATYPE_Stream )
1446             {
1447                 msg_Dbg( p_this, "EnumDeviceCaps: input pin "
1448                          "accepts stream format: %4.4s",
1449                          (char *)&i_current_fourcc );
1450
1451                 if( ( !i_fourcc || i_fourcc == i_current_fourcc ) &&
1452                     mt_count < mt_max )
1453                 {
1454                     /* Pick match */
1455                     mt[mt_count++] = *p_mt;
1456                     i_fourcc = i_current_fourcc;
1457                 }
1458                 else FreeMediaType( *p_mt );
1459             }
1460             else
1461             {
1462                 char *psz_type = "unknown";
1463                 if( p_mt->majortype == MEDIATYPE_Video ) psz_type = "video";
1464                 if( p_mt->majortype == MEDIATYPE_Audio ) psz_type = "audio";
1465                 if( p_mt->majortype == MEDIATYPE_Stream ) psz_type = "stream";
1466                 msg_Dbg( p_this, "EnumDeviceCaps: input pin media: unknown format "
1467                          "(%s %4.4s)", psz_type, (char *)&p_mt->subtype );
1468                 FreeMediaType( *p_mt );
1469             }
1470             CoTaskMemFree( (PVOID)p_mt );
1471         }
1472
1473         p_enummt->Release();
1474         p_output_pin->Release();
1475     }
1476
1477     p_enumpins->Release();
1478     return mt_count;
1479 }
1480
1481 /*****************************************************************************
1482  * ReadCompressed: reads compressed (MPEG/DV) data from the device.
1483  *****************************************************************************
1484  * Returns -1 in case of error, 0 in case of EOF, otherwise the number of
1485  * bytes.
1486  *****************************************************************************/
1487 static block_t *ReadCompressed( access_t *p_access )
1488 {
1489     access_sys_t   *p_sys = p_access->p_sys;
1490     dshow_stream_t *p_stream = NULL;
1491     VLCMediaSample sample;
1492
1493     /* Read 1 DV/MPEG frame (they contain the video and audio data) */
1494
1495     /* There must be only 1 elementary stream to produce a valid stream
1496      * of MPEG or DV data */
1497     p_stream = p_sys->pp_streams[0];
1498
1499     while( 1 )
1500     {
1501         if( p_access->b_die || p_access->b_error ) return 0;
1502
1503         /* Get new sample/frame from the elementary stream (blocking). */
1504         vlc_mutex_lock( &p_sys->lock );
1505
1506         if( p_stream->p_capture_filter->CustomGetPin()
1507               ->CustomGetSample( &sample ) != S_OK )
1508         {
1509             /* No data available. Wait until some data has arrived */
1510             vlc_cond_wait( &p_sys->wait, &p_sys->lock );
1511             vlc_mutex_unlock( &p_sys->lock );
1512             continue;
1513         }
1514
1515         vlc_mutex_unlock( &p_sys->lock );
1516
1517         /*
1518          * We got our sample
1519          */
1520         block_t *p_block;
1521         uint8_t *p_data;
1522         int i_data_size = sample.p_sample->GetActualDataLength();
1523
1524         if( !i_data_size || !(p_block = block_New( p_access, i_data_size )) )
1525         {
1526             sample.p_sample->Release();
1527             continue;
1528         }
1529
1530         sample.p_sample->GetPointer( &p_data );
1531         p_access->p_vlc->pf_memcpy( p_block->p_buffer, p_data, i_data_size );
1532         sample.p_sample->Release();
1533
1534         /* The caller got what he wanted */
1535         return p_block;
1536     }
1537
1538     return 0; /* never reached */
1539 }
1540
1541 /****************************************************************************
1542  * Demux:
1543  ****************************************************************************/
1544 static int Demux( demux_t *p_demux )
1545 {
1546     access_sys_t *p_sys = (access_sys_t *)p_demux->p_sys;
1547     dshow_stream_t *p_stream = NULL;
1548     VLCMediaSample sample;
1549     int i_data_size, i_stream;
1550     uint8_t *p_data;
1551     block_t *p_block;
1552
1553     vlc_mutex_lock( &p_sys->lock );
1554
1555     /* Try to grab an audio sample (audio has a higher priority) */
1556     for( i_stream = 0; i_stream < p_sys->i_streams; i_stream++ )
1557     {
1558         p_stream = p_sys->pp_streams[i_stream];
1559         if( p_stream->mt.majortype == MEDIATYPE_Audio &&
1560             p_stream->p_capture_filter &&
1561             p_stream->p_capture_filter->CustomGetPin()
1562               ->CustomGetSample( &sample ) == S_OK )
1563         {
1564             break;
1565         }
1566     }
1567     /* Try to grab a video sample */
1568     if( i_stream == p_sys->i_streams )
1569     {
1570         for( i_stream = 0; i_stream < p_sys->i_streams; i_stream++ )
1571         {
1572             p_stream = p_sys->pp_streams[i_stream];
1573             if( p_stream->p_capture_filter &&
1574                 p_stream->p_capture_filter->CustomGetPin()
1575                     ->CustomGetSample( &sample ) == S_OK )
1576             {
1577                 break;
1578             }
1579         }
1580     }
1581
1582     vlc_mutex_unlock( &p_sys->lock );
1583
1584     if( i_stream == p_sys->i_streams )
1585     {
1586         /* Sleep so we do not consume all the cpu, 10ms seems
1587          * like a good value (100fps) */
1588         msleep( 10000 );
1589         return 1;
1590     }
1591
1592     /*
1593      * We got our sample
1594      */
1595     i_data_size = sample.p_sample->GetActualDataLength();
1596     sample.p_sample->GetPointer( &p_data );
1597
1598     REFERENCE_TIME i_pts, i_end_date;
1599     HRESULT hr = sample.p_sample->GetTime( &i_pts, &i_end_date );
1600     if( hr != VFW_S_NO_STOP_TIME && hr != S_OK ) i_pts = 0;
1601
1602     if( !i_pts )
1603     {
1604         if( p_stream->mt.majortype == MEDIATYPE_Video || !p_stream->b_pts )
1605         {
1606             /* Use our data timestamp */
1607             i_pts = sample.i_timestamp;
1608             p_stream->b_pts = VLC_TRUE;
1609         }
1610     }
1611
1612     i_pts /= 10; /* Dshow works with 100 nano-seconds resolution */
1613
1614 #if 0
1615     msg_Dbg( p_demux, "Read() stream: %i, size: %i, PTS: "I64Fd,
1616              i_stream, i_data_size, i_pts );
1617 #endif
1618
1619     p_block = block_New( p_demux, i_data_size );
1620     p_demux->p_vlc->pf_memcpy( p_block->p_buffer, p_data, i_data_size );
1621     p_block->i_pts = p_block->i_dts = i_pts;
1622     sample.p_sample->Release();
1623
1624     es_out_Control( p_demux->out, ES_OUT_SET_PCR, i_pts > 0 ? i_pts : 0 );
1625     es_out_Send( p_demux->out, p_stream->p_es, p_block );
1626
1627     return 1;
1628 }
1629
1630 /*****************************************************************************
1631  * AccessControl:
1632  *****************************************************************************/
1633 static int AccessControl( access_t *p_access, int i_query, va_list args )
1634 {
1635     vlc_bool_t   *pb_bool;
1636     int          *pi_int;
1637     int64_t      *pi_64;
1638
1639     switch( i_query )
1640     {
1641     /* */
1642     case ACCESS_CAN_SEEK:
1643     case ACCESS_CAN_FASTSEEK:
1644     case ACCESS_CAN_PAUSE:
1645     case ACCESS_CAN_CONTROL_PACE:
1646         pb_bool = (vlc_bool_t*)va_arg( args, vlc_bool_t* );
1647         *pb_bool = VLC_FALSE;
1648         break;
1649
1650     /* */
1651     case ACCESS_GET_MTU:
1652         pi_int = (int*)va_arg( args, int * );
1653         *pi_int = 0;
1654         break;
1655
1656     case ACCESS_GET_PTS_DELAY:
1657         pi_64 = (int64_t*)va_arg( args, int64_t * );
1658         *pi_64 = (int64_t)var_GetInteger( p_access, "dshow-caching" ) * 1000;
1659         break;
1660
1661     /* */
1662     case ACCESS_SET_PAUSE_STATE:
1663     case ACCESS_GET_TITLE_INFO:
1664     case ACCESS_SET_TITLE:
1665     case ACCESS_SET_SEEKPOINT:
1666     case ACCESS_SET_PRIVATE_ID_STATE:
1667         return VLC_EGENERIC;
1668
1669     default:
1670         msg_Warn( p_access, "unimplemented query in control" );
1671         return VLC_EGENERIC;
1672     }
1673
1674     return VLC_SUCCESS;
1675 }
1676
1677 /****************************************************************************
1678  * DemuxControl:
1679  ****************************************************************************/
1680 static int DemuxControl( demux_t *p_demux, int i_query, va_list args )
1681 {
1682     vlc_bool_t *pb;
1683     int64_t    *pi64;
1684
1685     switch( i_query )
1686     {
1687     /* Special for access_demux */
1688     case DEMUX_CAN_PAUSE:
1689     case DEMUX_SET_PAUSE_STATE:
1690     case DEMUX_CAN_CONTROL_PACE:
1691         pb = (vlc_bool_t*)va_arg( args, vlc_bool_t * );
1692         *pb = VLC_FALSE;
1693         return VLC_SUCCESS;
1694
1695     case DEMUX_GET_PTS_DELAY:
1696         pi64 = (int64_t*)va_arg( args, int64_t * );
1697         *pi64 = (int64_t)var_GetInteger( p_demux, "dshow-caching" ) * 1000;
1698         return VLC_SUCCESS;
1699
1700     case DEMUX_GET_TIME:
1701         pi64 = (int64_t*)va_arg( args, int64_t * );
1702         *pi64 = mdate();
1703         return VLC_SUCCESS;
1704
1705     /* TODO implement others */
1706     default:
1707         return VLC_EGENERIC;
1708     }
1709
1710     return VLC_EGENERIC;
1711 }
1712
1713 /*****************************************************************************
1714  * config variable callback
1715  *****************************************************************************/
1716 static int FindDevicesCallback( vlc_object_t *p_this, char const *psz_name,
1717                                vlc_value_t newval, vlc_value_t oldval, void * )
1718 {
1719     module_config_t *p_item;
1720     vlc_bool_t b_audio = VLC_FALSE;
1721     int i;
1722
1723     p_item = config_FindConfig( p_this, psz_name );
1724     if( !p_item ) return VLC_SUCCESS;
1725
1726     if( !strcmp( psz_name, "dshow-adev" ) ) b_audio = VLC_TRUE;
1727
1728     /* Clear-up the current list */
1729     if( p_item->i_list )
1730     {
1731         /* Keep the 2 first entries */
1732         for( i = 2; i < p_item->i_list; i++ )
1733         {
1734             free( p_item->ppsz_list[i] );
1735             free( p_item->ppsz_list_text[i] );
1736         }
1737         /* TODO: Remove when no more needed */
1738         p_item->ppsz_list[i] = NULL;
1739         p_item->ppsz_list_text[i] = NULL;
1740     }
1741     p_item->i_list = 2;
1742
1743     /* Find list of devices */
1744     list<string> list_devices;
1745
1746     /* Initialize OLE/COM */
1747     CoInitialize( 0 );
1748
1749     FindCaptureDevice( p_this, NULL, &list_devices, b_audio );
1750
1751     /* Uninitialize OLE/COM */
1752     CoUninitialize();
1753
1754     if( !list_devices.size() ) return VLC_SUCCESS;
1755
1756     p_item->ppsz_list =
1757         (char **)realloc( p_item->ppsz_list,
1758                           (list_devices.size()+3) * sizeof(char *) );
1759     p_item->ppsz_list_text =
1760         (char **)realloc( p_item->ppsz_list_text,
1761                           (list_devices.size()+3) * sizeof(char *) );
1762
1763     list<string>::iterator iter;
1764     for( iter = list_devices.begin(), i = 2; iter != list_devices.end();
1765          iter++, i++ )
1766     {
1767         p_item->ppsz_list[i] = strdup( iter->c_str() );
1768         p_item->ppsz_list_text[i] = NULL;
1769         p_item->i_list++;
1770     }
1771     p_item->ppsz_list[i] = NULL;
1772     p_item->ppsz_list_text[i] = NULL;
1773
1774     /* Signal change to the interface */
1775     p_item->b_dirty = VLC_TRUE;
1776
1777     return VLC_SUCCESS;
1778 }
1779
1780 static int ConfigDevicesCallback( vlc_object_t *p_this, char const *psz_name,
1781                                vlc_value_t newval, vlc_value_t oldval, void * )
1782 {
1783     module_config_t *p_item;
1784     vlc_bool_t b_audio = VLC_FALSE;
1785
1786     /* Initialize OLE/COM */
1787     CoInitialize( 0 );
1788
1789     p_item = config_FindConfig( p_this, psz_name );
1790     if( !p_item ) return VLC_SUCCESS;
1791
1792     if( !strcmp( psz_name, "dshow-adev" ) ) b_audio = VLC_TRUE;
1793
1794     string devicename;
1795
1796     if( newval.psz_string && *newval.psz_string )
1797     {
1798         devicename = newval.psz_string;
1799     }
1800     else
1801     {
1802         /* If no device name was specified, pick the 1st one */
1803         list<string> list_devices;
1804
1805         /* Enumerate devices */
1806         FindCaptureDevice( p_this, NULL, &list_devices, b_audio );
1807         if( !list_devices.size() ) return VLC_EGENERIC;
1808         devicename = *list_devices.begin();
1809     }
1810
1811     IBaseFilter *p_device_filter =
1812         FindCaptureDevice( p_this, &devicename, NULL, b_audio );
1813     if( p_device_filter )
1814     {
1815         ShowPropertyPage( p_device_filter );
1816     }
1817     else
1818     {
1819         /* Uninitialize OLE/COM */
1820         CoUninitialize();
1821
1822         msg_Err( p_this, "didn't find device: %s", devicename.c_str() );
1823         return VLC_EGENERIC;
1824     }
1825
1826     /* Uninitialize OLE/COM */
1827     CoUninitialize();
1828
1829     return VLC_SUCCESS;
1830 }
1831
1832 /*****************************************************************************
1833  * Properties
1834  *****************************************************************************/
1835 static void ShowPropertyPage( IUnknown *obj )
1836 {
1837     ISpecifyPropertyPages *p_spec;
1838     CAUUID cauuid;
1839
1840     HRESULT hr = obj->QueryInterface( IID_ISpecifyPropertyPages,
1841                                       (void **)&p_spec );
1842     if( FAILED(hr) ) return;
1843
1844     if( SUCCEEDED(p_spec->GetPages( &cauuid )) )
1845     {
1846         if( cauuid.cElems > 0 )
1847         {
1848             HWND hwnd_desktop = ::GetDesktopWindow();
1849
1850             OleCreatePropertyFrame( hwnd_desktop, 30, 30, NULL, 1, &obj,
1851                                     cauuid.cElems, cauuid.pElems, 0, 0, NULL );
1852
1853             CoTaskMemFree( cauuid.pElems );
1854         }
1855         p_spec->Release();
1856     }
1857 }
1858
1859 static void ShowDeviceProperties( vlc_object_t *p_this,
1860                                   ICaptureGraphBuilder2 *p_graph,
1861                                   IBaseFilter *p_device_filter,
1862                                   vlc_bool_t b_audio )
1863 {
1864     HRESULT hr;
1865     msg_Dbg( p_this, "Configuring Device Properties" );
1866
1867     /*
1868      * Video or audio capture filter page
1869      */
1870     ShowPropertyPage( p_device_filter );
1871
1872     /*
1873      * Audio capture pin
1874      */
1875     if( p_graph && b_audio )
1876     {
1877         IAMStreamConfig *p_SC;
1878
1879         msg_Dbg( p_this, "Showing WDM Audio Configuration Pages" );
1880
1881         hr = p_graph->FindInterface( &PIN_CATEGORY_CAPTURE,
1882                                      &MEDIATYPE_Audio, p_device_filter,
1883                                      IID_IAMStreamConfig, (void **)&p_SC );
1884         if( SUCCEEDED(hr) )
1885         {
1886             ShowPropertyPage(p_SC);
1887             p_SC->Release();
1888         }
1889
1890         /*
1891          * TV Audio filter
1892          */
1893         IAMTVAudio *p_TVA;
1894         HRESULT hr = p_graph->FindInterface( &PIN_CATEGORY_CAPTURE,
1895                                              &MEDIATYPE_Audio, p_device_filter,
1896                                              IID_IAMTVAudio, (void **)&p_TVA );
1897         if( SUCCEEDED(hr) )
1898         {
1899             ShowPropertyPage(p_TVA);
1900             p_TVA->Release();
1901         }
1902     }
1903
1904     /*
1905      * Video capture pin
1906      */
1907     if( p_graph && !b_audio )
1908     {
1909         IAMStreamConfig *p_SC;
1910
1911         msg_Dbg( p_this, "Showing WDM Video Configuration Pages" );
1912
1913         hr = p_graph->FindInterface( &PIN_CATEGORY_CAPTURE,
1914                                      &MEDIATYPE_Interleaved, p_device_filter,
1915                                      IID_IAMStreamConfig, (void **)&p_SC );
1916         if( FAILED(hr) )
1917         {
1918             hr = p_graph->FindInterface( &PIN_CATEGORY_CAPTURE,
1919                                          &MEDIATYPE_Video, p_device_filter,
1920                                          IID_IAMStreamConfig, (void **)&p_SC );
1921         }
1922
1923         if( FAILED(hr) )
1924         {
1925             hr = p_graph->FindInterface( &PIN_CATEGORY_CAPTURE,
1926                                          &MEDIATYPE_Stream, p_device_filter,
1927                                          IID_IAMStreamConfig, (void **)&p_SC );
1928         }
1929
1930         if( SUCCEEDED(hr) )
1931         {
1932             ShowPropertyPage(p_SC);
1933             p_SC->Release();
1934         }
1935     }
1936 }
1937
1938 static void ShowTunerProperties( vlc_object_t *p_this,
1939                                  ICaptureGraphBuilder2 *p_graph,
1940                                  IBaseFilter *p_device_filter,
1941                                  vlc_bool_t b_audio )
1942 {
1943     HRESULT hr;
1944     msg_Dbg( p_this, "Configuring Tuner Properties" );
1945
1946     if( !p_graph || b_audio ) return;
1947
1948     IAMTVTuner *p_TV;
1949     hr = p_graph->FindInterface( &PIN_CATEGORY_CAPTURE,
1950                                  &MEDIATYPE_Interleaved, p_device_filter,
1951                                  IID_IAMTVTuner, (void **)&p_TV );
1952     if( FAILED(hr) )
1953     {
1954         hr = p_graph->FindInterface( &PIN_CATEGORY_CAPTURE,
1955                                      &MEDIATYPE_Video, p_device_filter,
1956                                      IID_IAMTVTuner, (void **)&p_TV );
1957     }
1958
1959     if( FAILED(hr) )
1960     {
1961         hr = p_graph->FindInterface( &PIN_CATEGORY_CAPTURE,
1962                                      &MEDIATYPE_Stream, p_device_filter,
1963                                      IID_IAMTVTuner, (void **)&p_TV );
1964     }
1965
1966     if( SUCCEEDED(hr) )
1967     {
1968         ShowPropertyPage(p_TV);
1969         p_TV->Release();
1970     }
1971 }
1972
1973 static void ConfigTuner( vlc_object_t *p_this, ICaptureGraphBuilder2 *p_graph,
1974                          IBaseFilter *p_device_filter )
1975 {
1976     int i_channel, i_country, i_input;
1977     long l_modes = 0;
1978     IAMTVTuner *p_TV;
1979     HRESULT hr;
1980
1981     if( !p_graph ) return;
1982
1983     i_channel = var_GetInteger( p_this, "dshow-tuner-channel" );
1984     i_country = var_GetInteger( p_this, "dshow-tuner-country" );
1985     i_input = var_GetInteger( p_this, "dshow-tuner-input" );
1986
1987     if( !i_channel && !i_country && !i_input ) return; /* Nothing to do */
1988
1989     msg_Dbg( p_this, "tuner config: channel %i, country %i, input type %i",
1990              i_channel, i_country, i_input );
1991
1992     hr = p_graph->FindInterface( &PIN_CATEGORY_CAPTURE, &MEDIATYPE_Interleaved,
1993                                  p_device_filter, IID_IAMTVTuner,
1994                                  (void **)&p_TV );
1995     if( FAILED(hr) )
1996     {
1997         hr = p_graph->FindInterface( &PIN_CATEGORY_CAPTURE, &MEDIATYPE_Video,
1998                                      p_device_filter, IID_IAMTVTuner,
1999                                      (void **)&p_TV );
2000     }
2001
2002     if( FAILED(hr) )
2003     {
2004         hr = p_graph->FindInterface( &PIN_CATEGORY_CAPTURE, &MEDIATYPE_Stream,
2005                                      p_device_filter, IID_IAMTVTuner,
2006                                      (void **)&p_TV );
2007     }
2008
2009     if( FAILED(hr) )
2010     {
2011         msg_Dbg( p_this, "couldn't find tuner interface" );
2012         return;
2013     }
2014
2015     hr = p_TV->GetAvailableModes( &l_modes );
2016     if( SUCCEEDED(hr) && (l_modes & AMTUNER_MODE_TV) )
2017     {
2018         hr = p_TV->put_Mode( AMTUNER_MODE_TV );
2019     }
2020
2021     if( i_input == 1 ) p_TV->put_InputType( 0, TunerInputCable );
2022     else if( i_input == 2 ) p_TV->put_InputType( 0, TunerInputAntenna );
2023
2024     p_TV->put_CountryCode( i_country );
2025     p_TV->put_Channel( i_channel, AMTUNER_SUBCHAN_NO_TUNE,
2026                        AMTUNER_SUBCHAN_NO_TUNE );
2027     p_TV->Release();
2028 }