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