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