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