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