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