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