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