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