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