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