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