]> git.sesse.net Git - vlc/blob - modules/access/dshow/dshow.cpp
- ordered device supported media types using an arbitrary fourcc preference priority...
[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 "filter.h"
36
37 /*****************************************************************************
38  * Access: local prototypes
39  *****************************************************************************/
40 static ssize_t Read          ( input_thread_t *, byte_t *, size_t );
41 static ssize_t ReadCompressed( input_thread_t *, byte_t *, size_t );
42
43 static int OpenDevice( input_thread_t *, string, vlc_bool_t );
44 static IBaseFilter *FindCaptureDevice( vlc_object_t *, string *,
45                                        list<string> *, vlc_bool_t );
46 static size_t EnumDeviceCaps( vlc_object_t *, IBaseFilter *,
47                                      int, int, int, int, int, int, AM_MEDIA_TYPE *mt, size_t mt_max);
48 static bool ConnectFilters( vlc_object_t *, IBaseFilter *, CaptureFilter * );
49
50 static int FindDevicesCallback( vlc_object_t *, char const *,
51                                 vlc_value_t, vlc_value_t, void * );
52 static int ConfigDevicesCallback( vlc_object_t *, char const *,
53                                   vlc_value_t, vlc_value_t, void * );
54
55 static void PropertiesPage( vlc_object_t *, IBaseFilter *,
56                             ICaptureGraphBuilder2 *, vlc_bool_t );
57
58 #if 0
59     /* Debug only, use this to find out GUIDs */
60     unsigned char p_st[];
61     UuidToString( (IID *)&IID_IAMBufferNegotiation, &p_st );
62     msg_Err( p_input, "BufferNegotiation: %s" , p_st );
63 #endif
64
65 /*
66  * header:
67  *  fcc  ".dsh"
68  *  u32    stream count
69  *      fcc "auds"|"vids"       0
70  *      fcc codec               4
71  *      if vids
72  *          u32 width           8
73  *          u32 height          12
74  *          u32 padding         16
75  *      if auds
76  *          u32 channels        12
77  *          u32 samplerate      8
78  *          u32 samplesize      16
79  *
80  * data:
81  *  u32     stream number
82  *  u32     data size
83  *  u8      data
84  */
85
86 static void SetDWBE( uint8_t *p, uint32_t dw )
87 {
88     p[0] = (dw >> 24)&0xff;
89     p[1] = (dw >> 16)&0xff;
90     p[2] = (dw >>  8)&0xff;
91     p[3] = (dw      )&0xff;
92 }
93
94 static void SetQWBE( uint8_t *p, uint64_t qw )
95 {
96     SetDWBE( p, (qw >> 32)&0xffffffff );
97     SetDWBE( &p[4], qw&0xffffffff );
98 }
99
100 /*****************************************************************************
101  * Module descriptor
102  *****************************************************************************/
103 static char *ppsz_vdev[] = { "", "none" };
104 static char *ppsz_vdev_text[] = { N_("Default"), N_("None") };
105 static char *ppsz_adev[] = { "", "none" };
106 static char *ppsz_adev_text[] = { N_("Default"), N_("None") };
107
108 #define CACHING_TEXT N_("Caching value in ms")
109 #define CACHING_LONGTEXT N_( \
110     "Allows you to modify the default caching value for DirectShow streams. " \
111     "This value should be set in milliseconds units." )
112 #define VDEV_TEXT N_("Video device name")
113 #define VDEV_LONGTEXT N_( \
114     "You can specify the name of the video device that will be used by the " \
115     "DirectShow plugin. If you don't specify anything, the default device " \
116     "will be used.")
117 #define ADEV_TEXT N_("Audio device name")
118 #define ADEV_LONGTEXT N_( \
119     "You can specify the name of the audio device that will be used by the " \
120     "DirectShow plugin. If you don't specify anything, the default device " \
121     "will be used.")
122 #define SIZE_TEXT N_("Video size")
123 #define SIZE_LONGTEXT N_( \
124     "You can specify the size of the video that will be displayed by the " \
125     "DirectShow plugin. If you don't specify anything the default size for " \
126     "your device will be used.")
127 #define CHROMA_TEXT N_("Video input chroma format")
128 #define CHROMA_LONGTEXT N_( \
129     "Force the DirectShow video input to use a specific chroma format " \
130     "(eg. I420 (default), RV24, etc.)")
131 #define CONFIG_TEXT N_("Device properties")
132 #define CONFIG_LONGTEXT N_( \
133     "Show the properties dialog of the selected device before starting the " \
134     "stream.")
135
136 static int  AccessOpen ( vlc_object_t * );
137 static void AccessClose( vlc_object_t * );
138
139 static int  DemuxOpen  ( vlc_object_t * );
140 static void DemuxClose ( vlc_object_t * );
141
142 vlc_module_begin();
143     set_shortname( _("DirectShow") );
144     set_description( _("DirectShow input") );
145     add_integer( "dshow-caching", (mtime_t)(0.2*CLOCK_FREQ) / 1000, NULL,
146                  CACHING_TEXT, CACHING_LONGTEXT, VLC_TRUE );
147
148     add_string( "dshow-vdev", NULL, NULL, VDEV_TEXT, VDEV_LONGTEXT, VLC_FALSE);
149         change_string_list( ppsz_vdev, ppsz_vdev_text, FindDevicesCallback );
150         change_action_add( FindDevicesCallback, N_("Refresh list") );
151         change_action_add( ConfigDevicesCallback, N_("Configure") );
152
153     add_string( "dshow-adev", NULL, NULL, ADEV_TEXT, ADEV_LONGTEXT, VLC_FALSE);
154         change_string_list( ppsz_adev, ppsz_adev_text, FindDevicesCallback );
155         change_action_add( FindDevicesCallback, N_("Refresh list") );
156         change_action_add( ConfigDevicesCallback, N_("Configure") );
157
158     add_string( "dshow-size", NULL, NULL, SIZE_TEXT, SIZE_LONGTEXT, VLC_FALSE);
159
160     add_string( "dshow-chroma", NULL, NULL, CHROMA_TEXT, CHROMA_LONGTEXT,
161                 VLC_TRUE );
162
163     add_bool( "dshow-config", VLC_FALSE, NULL, CONFIG_TEXT, CONFIG_LONGTEXT,
164               VLC_FALSE );
165
166     add_shortcut( "dshow" );
167     set_capability( "access", 0 );
168     set_callbacks( AccessOpen, AccessClose );
169
170     add_submodule();
171     set_description( _("DirectShow demuxer") );
172     add_shortcut( "dshow" );
173     set_capability( "demux", 200 );
174     set_callbacks( DemuxOpen, DemuxClose );
175
176 vlc_module_end();
177
178 /****************************************************************************
179  * DirectShow elementary stream descriptor
180  ****************************************************************************/
181 typedef struct dshow_stream_t
182 {
183     string          devicename;
184     IBaseFilter     *p_device_filter;
185     CaptureFilter   *p_capture_filter;
186     AM_MEDIA_TYPE   mt;
187     int             i_fourcc;
188     vlc_bool_t      b_invert;
189
190     union
191     {
192       VIDEOINFOHEADER video;
193       WAVEFORMATEX    audio;
194
195     } header;
196
197     vlc_bool_t      b_pts;
198
199 } dshow_stream_t;
200
201 /****************************************************************************
202  * Access descriptor declaration
203  ****************************************************************************/
204 #define MAX_CROSSBAR_DEPTH 10
205
206 typedef struct CrossbarRouteRec {
207     IAMCrossbar *pXbar;
208     LONG        VideoInputIndex;
209     LONG        VideoOutputIndex;
210     LONG        AudioInputIndex;
211     LONG        AudioOutputIndex;
212 } CrossbarRoute;
213
214 struct access_sys_t
215 {
216     vlc_mutex_t lock;
217     vlc_cond_t  wait;
218
219     IFilterGraph           *p_graph;
220     ICaptureGraphBuilder2  *p_capture_graph_builder2;
221     IMediaControl          *p_control;
222
223     int                     i_crossbar_route_depth;
224     CrossbarRoute           crossbar_routes[MAX_CROSSBAR_DEPTH];
225
226     /* header */
227     int     i_header_size;
228     int     i_header_pos;
229     uint8_t *p_header;
230
231     /* list of elementary streams */
232     dshow_stream_t **pp_streams;
233     int            i_streams;
234     int            i_current_stream;
235
236     /* misc properties */
237     int            i_width;
238     int            i_height;
239     int            i_chroma;
240     int            b_audio;
241 };
242
243 /****************************************************************************
244  * DirectShow utility functions
245  ****************************************************************************/
246 static void CreateDirectShowGraph( access_sys_t *p_sys )
247 {
248     p_sys->i_crossbar_route_depth = 0;
249
250     /* Create directshow filter graph */
251     if( SUCCEEDED( CoCreateInstance( CLSID_FilterGraph, 0, CLSCTX_INPROC,
252                        (REFIID)IID_IFilterGraph, (void **)&p_sys->p_graph) ) )
253     {
254         /* Create directshow capture graph builder if available */
255         if( SUCCEEDED( CoCreateInstance( CLSID_CaptureGraphBuilder2, 0,
256                          CLSCTX_INPROC, (REFIID)IID_ICaptureGraphBuilder2,
257                          (void **)&p_sys->p_capture_graph_builder2 ) ) )
258         {
259             p_sys->p_capture_graph_builder2->
260                 SetFiltergraph((IGraphBuilder *)p_sys->p_graph);
261         }
262
263         p_sys->p_graph->QueryInterface( IID_IMediaControl,
264                                         (void **)&p_sys->p_control );
265     }
266 }
267
268 static void DeleteCrossbarRoutes( access_sys_t *p_sys )
269 {
270     /* Remove crossbar filters from graph */
271     for( int i = 0; i < p_sys->i_crossbar_route_depth; i++ )
272     {
273         p_sys->crossbar_routes[i].pXbar->Release();
274     }
275     p_sys->i_crossbar_route_depth = 0;
276 }
277
278 static void DeleteDirectShowGraph( access_sys_t *p_sys )
279 {
280     DeleteCrossbarRoutes( p_sys );
281
282     /* Remove filters from graph */
283     for( int i = 0; i < p_sys->i_streams; i++ )
284     {
285         p_sys->p_graph->RemoveFilter( p_sys->pp_streams[i]->p_capture_filter );
286         p_sys->p_graph->RemoveFilter( p_sys->pp_streams[i]->p_device_filter );
287         p_sys->pp_streams[i]->p_capture_filter->Release();
288         p_sys->pp_streams[i]->p_device_filter->Release();
289     }
290
291     /* Release directshow objects */
292     if( p_sys->p_control )
293     {
294         p_sys->p_control->Release();
295         p_sys->p_control = NULL;
296     }
297     if( p_sys->p_capture_graph_builder2 )
298     {
299         p_sys->p_capture_graph_builder2->Release();
300         p_sys->p_capture_graph_builder2 = NULL;
301     }
302
303     if( p_sys->p_graph )
304     {
305         p_sys->p_graph->Release();
306         p_sys->p_graph = NULL;
307     }
308 }
309
310 static void ReleaseDirectShow( input_thread_t *p_input )
311 {
312     msg_Dbg( p_input, "Releasing DirectShow");
313
314     access_sys_t *p_sys = p_input->p_access_data;
315
316     DeleteDirectShowGraph( p_sys );
317
318     /* Uninitialize OLE/COM */
319     CoUninitialize();
320
321     free( p_sys->p_header );
322     /* Remove filters from graph */
323     for( int i = 0; i < p_sys->i_streams; i++ )
324     {
325         delete p_sys->pp_streams[i];
326     }
327     free( p_sys->pp_streams );
328     free( p_sys );
329
330     p_input->p_access_data = NULL;
331 }
332
333 /*****************************************************************************
334  * Open: open direct show device
335  *****************************************************************************/
336 static int AccessOpen( vlc_object_t *p_this )
337 {
338     input_thread_t *p_input = (input_thread_t *)p_this;
339     access_sys_t   *p_sys;
340     vlc_value_t    val;
341
342     /* Get/parse options and open device(s) */
343     string vdevname, adevname;
344     int i_width = 0, i_height = 0, i_chroma = 0;
345
346     var_Create( p_input, "dshow-config", VLC_VAR_INTEGER | VLC_VAR_DOINHERIT );
347
348     var_Create( p_input, "dshow-vdev", VLC_VAR_STRING | VLC_VAR_DOINHERIT);
349     var_Get( p_input, "dshow-vdev", &val );
350     if( val.psz_string ) vdevname = string( val.psz_string );
351     if( val.psz_string ) free( val.psz_string );
352
353     var_Create( p_input, "dshow-adev", VLC_VAR_STRING | VLC_VAR_DOINHERIT);
354     var_Get( p_input, "dshow-adev", &val );
355     if( val.psz_string ) adevname = string( val.psz_string );
356     if( val.psz_string ) free( val.psz_string );
357
358     var_Create( p_input, "dshow-size", VLC_VAR_STRING | VLC_VAR_DOINHERIT);
359     var_Get( p_input, "dshow-size", &val );
360     if( val.psz_string && *val.psz_string )
361     {
362         if( !strcmp( val.psz_string, "subqcif" ) )
363         {
364             i_width  = 128; i_height = 96;
365         }
366         else if( !strcmp( val.psz_string, "qsif" ) )
367         {
368             i_width  = 160; i_height = 120;
369         }
370         else if( !strcmp( val.psz_string, "qcif" ) )
371         {
372             i_width  = 176; i_height = 144;
373         }
374         else if( !strcmp( val.psz_string, "sif" ) )
375         {
376             i_width  = 320; i_height = 240;
377         }
378         else if( !strcmp( val.psz_string, "cif" ) )
379         {
380             i_width  = 352; i_height = 288;
381         }
382         else if( !strcmp( val.psz_string, "vga" ) )
383         {
384             i_width  = 640; i_height = 480;
385         }
386         else
387         {
388             /* Width x Height */
389             char *psz_parser;
390             i_width = strtol( val.psz_string, &psz_parser, 0 );
391             if( *psz_parser == 'x' || *psz_parser == 'X')
392             {
393                 i_height = strtol( psz_parser + 1, &psz_parser, 0 );
394             }
395             msg_Dbg( p_input, "Width x Height %dx%d", i_width, i_height );
396         }
397     }
398     if( val.psz_string ) free( val.psz_string );
399
400     var_Create( p_input, "dshow-chroma", VLC_VAR_STRING | VLC_VAR_DOINHERIT);
401     var_Get( p_input, "dshow-chroma", &val );
402     if( val.psz_string && strlen( val.psz_string ) >= 4 )
403     {
404         i_chroma = VLC_FOURCC( val.psz_string[0], val.psz_string[1],
405                                val.psz_string[2], val.psz_string[3] );
406     }
407     if( val.psz_string ) free( val.psz_string );
408
409     p_input->pf_read        = Read;
410     p_input->pf_seek        = NULL;
411     p_input->pf_set_area    = NULL;
412     p_input->pf_set_program = NULL;
413
414     vlc_mutex_lock( &p_input->stream.stream_lock );
415     p_input->stream.b_pace_control = 0;
416     p_input->stream.b_seekable = 0;
417     p_input->stream.p_selected_area->i_size = 0;
418     p_input->stream.p_selected_area->i_tell = 0;
419     p_input->stream.i_method = INPUT_METHOD_FILE;
420     vlc_mutex_unlock( &p_input->stream.stream_lock );
421
422     var_Create( p_input, "dshow-caching", VLC_VAR_INTEGER | VLC_VAR_DOINHERIT);
423     var_Get( p_input, "dshow-caching", &val );
424     p_input->i_pts_delay = val.i_int * 1000;
425
426     /* Initialize OLE/COM */
427     CoInitialize( 0 );
428
429     /* create access private data */
430     p_input->p_access_data = p_sys =
431         (access_sys_t *)malloc( sizeof( access_sys_t ) );
432
433     /* Initialize some data */
434     p_sys->i_streams = 0;
435     p_sys->pp_streams = (dshow_stream_t **)malloc( 1 );
436     p_sys->i_width = i_width;
437     p_sys->i_height = i_height;
438     p_sys->i_chroma = i_chroma;
439     p_sys->b_audio = VLC_TRUE;
440
441     /* Create header */
442     p_sys->i_header_size = 8;
443     p_sys->p_header      = (uint8_t *)malloc( p_sys->i_header_size );
444     memcpy(  &p_sys->p_header[0], ".dsh", 4 );
445     SetDWBE( &p_sys->p_header[4], 1 );
446     p_sys->i_header_pos = p_sys->i_header_size;
447
448     p_sys->p_graph = NULL;
449     p_sys->p_capture_graph_builder2 = NULL;
450     p_sys->p_control = NULL;
451
452     /* Build directshow graph */
453     CreateDirectShowGraph( p_sys );
454
455     if( OpenDevice( p_input, vdevname, 0 ) != VLC_SUCCESS )
456     {
457         msg_Err( p_input, "can't open video");
458     }
459
460     if( p_sys->b_audio && OpenDevice( p_input, adevname, 1 ) != VLC_SUCCESS )
461     {
462         msg_Err( p_input, "can't open audio");
463     }
464     
465     for( int i = 0; i < p_sys->i_crossbar_route_depth; i++ )
466     {
467         IAMCrossbar *pXbar = p_sys->crossbar_routes[i].pXbar;
468         LONG VideoInputIndex = p_sys->crossbar_routes[i].VideoInputIndex;
469         LONG VideoOutputIndex = p_sys->crossbar_routes[i].VideoOutputIndex;
470         LONG AudioInputIndex = p_sys->crossbar_routes[i].AudioInputIndex;
471         LONG AudioOutputIndex = p_sys->crossbar_routes[i].AudioOutputIndex;
472
473         if( SUCCEEDED(pXbar->Route(VideoOutputIndex, VideoInputIndex)) )
474         {
475             msg_Dbg( p_input, "Crossbar at depth %d, Routed video ouput %d to "
476                      "video input %d", i, VideoOutputIndex, VideoInputIndex );
477
478             if( AudioOutputIndex != -1 && AudioInputIndex != -1 )
479             {
480                 if( SUCCEEDED( pXbar->Route(AudioOutputIndex,
481                                             AudioInputIndex)) )
482                 {
483                     msg_Dbg(p_input, "Crossbar at depth %d, Routed audio "
484                             "ouput %d to audio input %d", i,
485                             AudioOutputIndex, AudioInputIndex );
486                 }
487             }
488         }
489     }
490
491     if( !p_sys->i_streams )
492     {
493         ReleaseDirectShow( p_input );
494         return VLC_EGENERIC;
495     }
496
497     /* Initialize some data */
498     p_sys->i_current_stream = 0;
499     p_input->i_mtu += p_sys->i_header_size + 16 /* data header size */;
500
501     vlc_mutex_init( p_input, &p_sys->lock );
502     vlc_cond_init( p_input, &p_sys->wait );
503
504     msg_Dbg( p_input, "Playing...");
505
506     /* Everything is ready. Let's rock baby */
507     p_sys->p_control->Run();
508
509     return VLC_SUCCESS;
510 }
511
512 /*****************************************************************************
513  * AccessClose: close device
514  *****************************************************************************/
515 static void AccessClose( vlc_object_t *p_this )
516 {
517     input_thread_t *p_input = (input_thread_t *)p_this;
518     access_sys_t   *p_sys   = p_input->p_access_data;
519
520     /* Stop capturing stuff */
521     p_sys->p_control->Stop();
522
523     ReleaseDirectShow(p_input);
524 }
525
526 /****************************************************************************
527  * RouteCrossbars (Does not AddRef the returned *Pin)
528  ****************************************************************************/
529 static HRESULT GetCrossbarIPinAtIndex( IAMCrossbar *pXbar, LONG PinIndex,
530                                        BOOL IsInputPin, IPin ** ppPin )
531 {
532     LONG         cntInPins, cntOutPins;
533     IPin        *pP = 0;
534     IBaseFilter *pFilter = NULL;
535     IEnumPins   *pins=0;
536     ULONG        n;
537
538     if( !pXbar || !ppPin ) return E_POINTER;
539
540     *ppPin = 0;
541
542     if( S_OK != pXbar->get_PinCounts(&cntOutPins, &cntInPins) ) return E_FAIL;
543
544     LONG TrueIndex = IsInputPin ? PinIndex : PinIndex + cntInPins;
545
546     if( pXbar->QueryInterface(IID_IBaseFilter, (void **)&pFilter) == S_OK )
547     {
548         if( SUCCEEDED(pFilter->EnumPins(&pins)) ) 
549         {
550             LONG i = 0;
551             while( pins->Next(1, &pP, &n) == S_OK ) 
552             {
553                 pP->Release();
554                 if( i == TrueIndex ) 
555                 {
556                     *ppPin = pP;
557                     break;
558                 }
559                 i++;
560             }
561             pins->Release();
562         }
563         pFilter->Release();
564     }
565
566     return *ppPin ? S_OK : E_FAIL; 
567 }
568
569 /****************************************************************************
570  * GetCrossbarIndexFromIPin: Find corresponding index of an IPin on a crossbar
571  ****************************************************************************/
572 static HRESULT GetCrossbarIndexFromIPin( IAMCrossbar * pXbar, LONG * PinIndex,
573                                          BOOL IsInputPin, IPin * pPin )
574 {
575     LONG         cntInPins, cntOutPins;
576     IPin        *pP = 0;
577     IBaseFilter *pFilter = NULL;
578     IEnumPins   *pins = 0;
579     ULONG        n;
580     BOOL         fOK = FALSE;
581
582     if(!pXbar || !PinIndex || !pPin )
583         return E_POINTER;
584
585     if( S_OK != pXbar->get_PinCounts(&cntOutPins, &cntInPins) )
586         return E_FAIL;
587
588     if( pXbar->QueryInterface(IID_IBaseFilter, (void **)&pFilter) == S_OK )
589     {
590         if( SUCCEEDED(pFilter->EnumPins(&pins)) )
591         {
592             LONG i=0;
593
594             while( pins->Next(1, &pP, &n) == S_OK )
595             {
596                 pP->Release();
597                 if( pPin == pP )
598                 {
599                     *PinIndex = IsInputPin ? i : i - cntInPins;
600                     fOK = TRUE;
601                     break;
602                 }
603                 i++;
604             }
605             pins->Release();
606         }
607         pFilter->Release();
608     }
609
610     return fOK ? S_OK : E_FAIL; 
611 }
612
613 /****************************************************************************
614  * FindCrossbarRoutes
615  ****************************************************************************/
616 static HRESULT FindCrossbarRoutes( vlc_object_t *p_this, IPin *p_input_pin,
617                                    LONG physicalType, int depth = 0 )
618 {
619     access_sys_t *p_sys = ((input_thread_t *)p_this)->p_access_data;
620     HRESULT result = S_FALSE;
621
622     IPin *p_output_pin;
623     if( FAILED(p_input_pin->ConnectedTo(&p_output_pin)) ) return S_FALSE;
624
625     // It is connected, so now find out if the filter supports IAMCrossbar
626     PIN_INFO pinInfo;
627     if( FAILED(p_output_pin->QueryPinInfo(&pinInfo)) ||
628         PINDIR_OUTPUT != pinInfo.dir )
629     {
630         p_output_pin->Release ();
631         return S_FALSE;
632     }
633
634     IAMCrossbar *pXbar=0;
635     if( FAILED(pinInfo.pFilter->QueryInterface(IID_IAMCrossbar,
636                                                (void **)&pXbar)) )
637     {
638         pinInfo.pFilter->Release();
639         p_output_pin->Release ();
640         return S_FALSE;
641     }
642
643     LONG inputPinCount, outputPinCount;
644     if( FAILED(pXbar->get_PinCounts(&outputPinCount, &inputPinCount)) )
645     {
646         pXbar->Release();
647         pinInfo.pFilter->Release();
648         p_output_pin->Release ();
649         return S_FALSE;
650     }
651
652     LONG inputPinIndexRelated, outputPinIndexRelated;
653     LONG inputPinPhysicalType, outputPinPhysicalType;
654     LONG inputPinIndex, outputPinIndex;
655     if( FAILED(GetCrossbarIndexFromIPin( pXbar, &outputPinIndex,
656                                          FALSE, p_output_pin )) ||
657         FAILED(pXbar->get_CrossbarPinInfo( FALSE, outputPinIndex,
658                                            &outputPinIndexRelated,
659                                            &outputPinPhysicalType )) )
660     {
661         pXbar->Release();
662         pinInfo.pFilter->Release();
663         p_output_pin->Release ();
664         return S_FALSE;
665     }
666
667     //
668     // for all input pins
669     //
670     for( inputPinIndex = 0; S_OK != result && inputPinIndex < inputPinCount;
671          inputPinIndex++ ) 
672     {
673         if( FAILED(pXbar->get_CrossbarPinInfo( TRUE,  inputPinIndex,
674                 &inputPinIndexRelated, &inputPinPhysicalType )) ) continue;
675    
676         // Is the pin a video pin?
677         if( inputPinPhysicalType != physicalType ) continue;
678
679         // Can we route it?
680         if( FAILED(pXbar->CanRoute(outputPinIndex, inputPinIndex)) ) continue;
681
682         IPin *pPin;
683         if( FAILED(GetCrossbarIPinAtIndex( pXbar, inputPinIndex,
684                                            TRUE, &pPin)) ) continue;
685
686         result = FindCrossbarRoutes( p_this, pPin, physicalType, depth+1 );
687         if( S_OK == result || (S_FALSE == result &&
688               physicalType == inputPinPhysicalType &&
689               (p_sys->i_crossbar_route_depth = depth+1) < MAX_CROSSBAR_DEPTH) )
690         {
691             // hold on crossbar
692             pXbar->AddRef();
693
694             // remember crossbar route
695             p_sys->crossbar_routes[depth].pXbar = pXbar;
696             p_sys->crossbar_routes[depth].VideoInputIndex = inputPinIndex;
697             p_sys->crossbar_routes[depth].VideoOutputIndex = outputPinIndex;
698             p_sys->crossbar_routes[depth].AudioInputIndex = inputPinIndexRelated;
699             p_sys->crossbar_routes[depth].AudioOutputIndex = outputPinIndexRelated;
700
701             msg_Dbg( p_this, "Crossbar at depth %d, Found Route For ouput %ld "
702                      "(type %ld) to input %d (type %ld)", depth,
703                      outputPinIndex, outputPinPhysicalType, inputPinIndex,
704                      inputPinPhysicalType );
705
706             result = S_OK;
707         }
708     }
709
710     pXbar->Release();
711     pinInfo.pFilter->Release();
712     p_output_pin->Release ();
713
714     return result;
715 }
716
717 /****************************************************************************
718  * ConnectFilters
719  ****************************************************************************/
720 static bool ConnectFilters( vlc_object_t *p_this, IBaseFilter *p_filter,
721                             CaptureFilter *p_capture_filter )
722 {
723     access_sys_t *p_sys = ((input_thread_t *)p_this)->p_access_data;
724     CapturePin *p_input_pin = p_capture_filter->CustomGetPin();
725
726     AM_MEDIA_TYPE mediaType = p_input_pin->CustomGetMediaType();
727
728     if( p_sys->p_capture_graph_builder2 )
729     {
730         if( FAILED(p_sys->p_capture_graph_builder2->
731                      RenderStream( &PIN_CATEGORY_CAPTURE, &mediaType.majortype,
732                                    p_filter, NULL,
733                                    (IBaseFilter *)p_capture_filter )) )
734         {
735             return false;
736         }
737
738         // Sort out all the possible video inputs
739         // The class needs to be given the capture filters ANALOGVIDEO input pin
740         IEnumPins *pins = 0;
741         if( mediaType.majortype == MEDIATYPE_Video &&
742             SUCCEEDED(p_filter->EnumPins(&pins)) )
743         {
744             IPin        *pP = 0;
745             ULONG        n;
746             PIN_INFO     pinInfo;
747             BOOL         Found = FALSE;
748             IKsPropertySet *pKs=0;
749             GUID guid;
750             DWORD dw;
751
752             while( !Found && (S_OK == pins->Next(1, &pP, &n)) )
753             {
754                 if(S_OK == pP->QueryPinInfo(&pinInfo))
755                 {
756                     if(pinInfo.dir == PINDIR_INPUT)
757                     {
758                         // is this pin an ANALOGVIDEOIN input pin?
759                         if( pP->QueryInterface(IID_IKsPropertySet,
760                                                (void **)&pKs) == S_OK )
761                         {
762                             if( pKs->Get(AMPROPSETID_Pin,
763                                          AMPROPERTY_PIN_CATEGORY, NULL, 0,
764                                          &guid, sizeof(GUID), &dw) == S_OK )
765                             {
766                                 if( guid == PIN_CATEGORY_ANALOGVIDEOIN )
767                                 {
768                                     // recursively search crossbar routes
769                                     FindCrossbarRoutes( p_this, pP,
770                                                         PhysConn_Video_Tuner );
771                                     // found it
772                                     Found = TRUE;
773                                 }
774                             }
775                             pKs->Release();
776                         }
777                     }
778                     pinInfo.pFilter->Release();
779                 }
780                 pP->Release();
781             }
782             pins->Release();
783         }
784         return true;
785     }
786     else
787     {
788         IEnumPins *p_enumpins;
789         IPin *p_pin;
790
791         if( S_OK != p_filter->EnumPins( &p_enumpins ) ) return false;
792
793         while( S_OK == p_enumpins->Next( 1, &p_pin, NULL ) )
794         {
795             PIN_DIRECTION pin_dir;
796             p_pin->QueryDirection( &pin_dir );
797
798             if( pin_dir == PINDIR_OUTPUT &&
799                 p_sys->p_graph->ConnectDirect( p_pin, (IPin *)p_input_pin,
800                                                0 ) == S_OK )
801             {
802                 p_pin->Release();
803                 p_enumpins->Release();
804                 return true;
805             }
806             p_pin->Release();
807         }
808
809         p_enumpins->Release();
810         return false;
811     }
812 }
813
814 /*
815 ** get fourcc priority from arbritary preference, the higher the better
816 */
817 static int GetFourCCPriority(int i_fourcc)
818 {
819     switch( i_fourcc )
820     {
821         case VLC_FOURCC('I','4','2','0'):
822         case VLC_FOURCC('a','r','a','w'):
823         {
824             return 9;
825         }
826
827         case VLC_FOURCC('Y','V','1','2'):
828         {
829             return 8;
830         }
831
832         case VLC_FOURCC('R','V','2','4'):
833         {
834             return 7;
835         }
836
837         case VLC_FOURCC('Y','U','Y','2'):
838         case VLC_FOURCC('R','V','3','2'):
839         case VLC_FOURCC('R','G','B','A'):
840         case VLC_FOURCC('f','l','3','2'):
841         {
842             return 6;
843         }
844     }
845     return 0;
846 }
847
848 #define MAX_MEDIA_TYPES 32
849
850 static int OpenDevice( input_thread_t *p_input, string devicename,
851                        vlc_bool_t b_audio )
852 {
853     access_sys_t *p_sys = p_input->p_access_data;
854
855     /* See if device is already opened */
856     for( int i = 0; i < p_sys->i_streams; i++ )
857     {
858         if( p_sys->pp_streams[i]->devicename == devicename )
859         {
860             /* Already opened */
861             return VLC_SUCCESS;
862         }
863     }
864
865     list<string> list_devices;
866
867     /* Enumerate devices and display their names */
868     FindCaptureDevice( (vlc_object_t *)p_input, NULL, &list_devices, b_audio );
869
870     if( !list_devices.size() )
871         return VLC_EGENERIC;
872
873     list<string>::iterator iter;
874     for( iter = list_devices.begin(); iter != list_devices.end(); iter++ )
875         msg_Dbg( p_input, "found device: %s", iter->c_str() );
876
877     /* If no device name was specified, pick the 1st one */
878     if( devicename.size() == 0 )
879     {
880         devicename = *list_devices.begin();
881     }
882
883     // Use the system device enumerator and class enumerator to find
884     // a capture/preview device, such as a desktop USB video camera.
885     IBaseFilter *p_device_filter =
886         FindCaptureDevice( (vlc_object_t *)p_input, &devicename,
887                            NULL, b_audio );
888     if( p_device_filter )
889         msg_Dbg( p_input, "using device: %s", devicename.c_str() );
890     else
891     {
892         msg_Err( p_input, "can't use device: %s, unsupported device type", devicename.c_str() );
893         return VLC_EGENERIC;
894     }
895
896     AM_MEDIA_TYPE media_types[MAX_MEDIA_TYPES];
897
898     size_t mt_count = EnumDeviceCaps( (vlc_object_t *)p_input, p_device_filter,
899                                                                 p_sys->i_chroma, p_sys->i_width, p_sys->i_height,
900                                                                 0, 0, 0, media_types, MAX_MEDIA_TYPES );
901
902     if( 0 == mt_count )
903     {
904         msg_Err( p_input, "can't use device: %s, unsupported media types", devicename.c_str() );
905         return VLC_EGENERIC;
906     }
907  
908     AM_MEDIA_TYPE *mt = (AM_MEDIA_TYPE *)malloc( sizeof(AM_MEDIA_TYPE)*mt_count );
909
910     //order and copy returned media types according to arbitrary fourcc priority
911     for( size_t c=0; c<mt_count; c++ )
912     {
913         int slot_priority = GetFourCCPriority(GetFourCCFromMediaType(media_types[c]));
914         int slot_copy = c;
915         for( size_t d=c+1; d<mt_count; d++ )
916         {
917             int priority = GetFourCCPriority(GetFourCCFromMediaType(media_types[d]));
918             if( priority > slot_priority )
919             {
920                 slot_priority = priority;
921                 slot_copy = d;
922             }
923         }
924         if( slot_copy != c )
925         {
926             mt[c] = media_types[slot_copy];
927             media_types[slot_copy] = media_types[c];
928         }
929         else
930         {
931             mt[c] = media_types[c];
932         }
933     }
934
935     /* Create and add our capture filter */
936     CaptureFilter *p_capture_filter = new CaptureFilter( p_input, mt, mt_count );
937     p_sys->p_graph->AddFilter( p_capture_filter, 0 );
938
939     /* Add the device filter to the graph (seems necessary with VfW before
940      * accessing pin attributes). */
941     p_sys->p_graph->AddFilter( p_device_filter, 0 );
942
943     /* Attempt to connect one of this device's capture output pins */
944     msg_Dbg( p_input, "connecting filters" );
945     if( ConnectFilters( VLC_OBJECT(p_input), p_device_filter,
946                         p_capture_filter ) )
947     {
948         /* Success */
949         msg_Dbg( p_input, "filters connected successfully !" );
950
951         dshow_stream_t dshow_stream;
952         dshow_stream.b_invert = VLC_FALSE;
953         dshow_stream.b_pts = VLC_FALSE;
954         dshow_stream.mt =
955             p_capture_filter->CustomGetPin()->CustomGetMediaType();
956
957         /* Show properties. Done here so the VLC stream is setup with the
958          * proper parameters. */
959         vlc_value_t val;
960         var_Get( p_input, "dshow-config", &val );
961         if( val.i_int )
962         {
963             PropertiesPage( VLC_OBJECT(p_input), p_device_filter,
964                             p_sys->p_capture_graph_builder2,
965                             dshow_stream.mt.majortype == MEDIATYPE_Audio );
966         }
967
968         dshow_stream.mt =
969             p_capture_filter->CustomGetPin()->CustomGetMediaType();
970
971         dshow_stream.i_fourcc = GetFourCCFromMediaType(dshow_stream.mt);
972                 if( 0 != dshow_stream.i_fourcc )
973                 {
974                         if( dshow_stream.mt.majortype == MEDIATYPE_Video )
975                         {
976                                 msg_Dbg( p_input, "MEDIATYPE_Video");
977
978                                 dshow_stream.header.video =
979                                         *(VIDEOINFOHEADER *)dshow_stream.mt.pbFormat;
980
981                                 int i_height = dshow_stream.header.video.bmiHeader.biHeight;
982
983                                 /* Check if the image is inverted (bottom to top) */
984                                 if( dshow_stream.i_fourcc == VLC_FOURCC( 'R', 'G', 'B', '1' ) ||
985                                         dshow_stream.i_fourcc == VLC_FOURCC( 'R', 'G', 'B', '4' ) ||
986                                         dshow_stream.i_fourcc == VLC_FOURCC( 'R', 'G', 'B', '8' ) ||
987                                         dshow_stream.i_fourcc == VLC_FOURCC( 'R', 'V', '1', '5' ) ||
988                                         dshow_stream.i_fourcc == VLC_FOURCC( 'R', 'V', '1', '6' ) ||
989                                         dshow_stream.i_fourcc == VLC_FOURCC( 'R', 'V', '2', '4' ) ||
990                                         dshow_stream.i_fourcc == VLC_FOURCC( 'R', 'V', '3', '2' ) ||
991                                         dshow_stream.i_fourcc == VLC_FOURCC( 'R', 'G', 'B', 'A' ) )
992                                 {
993                                         if( i_height > 0 ) dshow_stream.b_invert = VLC_TRUE;
994                                         else i_height = - i_height;
995                                 }
996
997                                 /* Check if we are dealing with a DV stream */
998                                 if( dshow_stream.i_fourcc == VLC_FOURCC( 'd', 'v', 's', 'l' ) ||
999                                         dshow_stream.i_fourcc == VLC_FOURCC( 'd', 'v', 's', 'd' ) ||
1000                                         dshow_stream.i_fourcc == VLC_FOURCC( 'd', 'v', 'h', 'd' ) )
1001                                 {
1002                                         p_input->pf_read = ReadCompressed;
1003                                         if( !p_input->psz_demux || !*p_input->psz_demux )
1004                                         {
1005                                                 p_input->psz_demux = "rawdv";
1006                                         }
1007                                         p_sys->b_audio = VLC_FALSE;
1008                                 }
1009
1010                                 /* Check if we are dealing with an MPEG video stream */
1011                                 if( dshow_stream.i_fourcc == VLC_FOURCC( 'm', 'p', '2', 'v' ) )
1012                                 {
1013                                         p_input->pf_read = ReadCompressed;
1014                                         if( !p_input->psz_demux || !*p_input->psz_demux )
1015                                         {
1016                                                 p_input->psz_demux = "mpgv";
1017                                         }
1018                                         p_sys->b_audio = VLC_FALSE;
1019                                 }
1020
1021                                 /* Add video stream to header */
1022                                 p_sys->i_header_size += 20;
1023                                 p_sys->p_header = (uint8_t *)realloc( p_sys->p_header,
1024                                                                                                           p_sys->i_header_size );
1025                                 memcpy(  &p_sys->p_header[p_sys->i_header_pos], "vids", 4 );
1026                                 memcpy(  &p_sys->p_header[p_sys->i_header_pos + 4],
1027                                                  &dshow_stream.i_fourcc, 4 );
1028                                 SetDWBE( &p_sys->p_header[p_sys->i_header_pos + 8],
1029                                                  dshow_stream.header.video.bmiHeader.biWidth );
1030                                 SetDWBE( &p_sys->p_header[p_sys->i_header_pos + 12], i_height );
1031                                 SetDWBE( &p_sys->p_header[p_sys->i_header_pos + 16], 0 );
1032                                 p_sys->i_header_pos = p_sys->i_header_size;
1033
1034                                 /* Greatly simplifies the reading routine */
1035                                 int i_mtu = dshow_stream.header.video.bmiHeader.biWidth *
1036                                         i_height * 4;
1037                                 p_input->i_mtu = __MAX( p_input->i_mtu, (unsigned int)i_mtu );
1038                         }
1039
1040                         else if( dshow_stream.mt.majortype == MEDIATYPE_Audio )
1041                         {
1042                                 msg_Dbg( p_input, "MEDIATYPE_Audio");
1043
1044                                 dshow_stream.header.audio =
1045                                         *(WAVEFORMATEX *)dshow_stream.mt.pbFormat;
1046
1047                                 /* Add audio stream to header */
1048                                 p_sys->i_header_size += 20;
1049                                 p_sys->p_header = (uint8_t *)realloc( p_sys->p_header,
1050                                                                                                           p_sys->i_header_size );
1051                                 memcpy(  &p_sys->p_header[p_sys->i_header_pos], "auds", 4 );
1052                                 memcpy(  &p_sys->p_header[p_sys->i_header_pos + 4],
1053                                                  &dshow_stream.i_fourcc, 4 );
1054                                 SetDWBE( &p_sys->p_header[p_sys->i_header_pos + 8],
1055                                                  dshow_stream.header.audio.nChannels );
1056                                 SetDWBE( &p_sys->p_header[p_sys->i_header_pos + 12],
1057                                                  dshow_stream.header.audio.nSamplesPerSec );
1058                                 SetDWBE( &p_sys->p_header[p_sys->i_header_pos + 16],
1059                                                  dshow_stream.header.audio.wBitsPerSample );
1060                                 p_sys->i_header_pos = p_sys->i_header_size;
1061
1062                                 /* Greatly simplifies the reading routine */
1063                                 IAMBufferNegotiation *p_ambuf;
1064                                 IPin *p_pin;
1065                                 int i_mtu;
1066
1067                                 p_capture_filter->CustomGetPin()->ConnectedTo( &p_pin );
1068                                 if( SUCCEEDED( p_pin->QueryInterface(
1069                                           IID_IAMBufferNegotiation, (void **)&p_ambuf ) ) )
1070                                 {
1071                                         ALLOCATOR_PROPERTIES AllocProp;
1072                                         memset( &AllocProp, 0, sizeof( ALLOCATOR_PROPERTIES ) );
1073                                         p_ambuf->GetAllocatorProperties( &AllocProp );
1074                                         p_ambuf->Release();
1075                                         i_mtu = AllocProp.cbBuffer;
1076                                 }
1077                                 else
1078                                 {
1079                                         /* Worst case */
1080                                         i_mtu = dshow_stream.header.audio.nSamplesPerSec *
1081                                                         dshow_stream.header.audio.nChannels *
1082                                                         dshow_stream.header.audio.wBitsPerSample / 8;
1083                                 }
1084                                 p_pin->Release();
1085                                 p_input->i_mtu = __MAX( p_input->i_mtu, (unsigned int)i_mtu );
1086                         }
1087
1088                         else if( dshow_stream.mt.majortype == MEDIATYPE_Stream )
1089                         {
1090                                 msg_Dbg( p_input, "MEDIATYPE_Stream" );
1091
1092                                 msg_Dbg( p_input, "selected stream pin accepts format: %4.4s",
1093                                                  (char *)&dshow_stream.i_fourcc);
1094
1095                                 p_sys->b_audio = VLC_FALSE;
1096                                 p_sys->i_header_size = 0;
1097                                 p_sys->i_header_pos = 0;
1098                                 p_input->i_mtu = INPUT_DEFAULT_BUFSIZE;
1099
1100                                 p_input->pf_read = ReadCompressed;
1101                                 p_input->pf_set_program = input_SetProgram;
1102                         }
1103                         else
1104                         {
1105                                 msg_Dbg( p_input, "unknown stream majortype" );
1106                                 goto fail;
1107                         }
1108
1109                         /* Add directshow elementary stream to our list */
1110                         dshow_stream.p_device_filter = p_device_filter;
1111                         dshow_stream.p_capture_filter = p_capture_filter;
1112
1113                         p_sys->pp_streams =
1114                                 (dshow_stream_t **)realloc( p_sys->pp_streams,
1115                                                                                         sizeof(dshow_stream_t *)
1116                                                                                         * (p_sys->i_streams + 1) );
1117                         p_sys->pp_streams[p_sys->i_streams] = new dshow_stream_t;
1118                         *p_sys->pp_streams[p_sys->i_streams++] = dshow_stream;
1119                         SetDWBE( &p_sys->p_header[4], (uint32_t)p_sys->i_streams );
1120
1121                         return VLC_SUCCESS;
1122                 }
1123     }
1124
1125  fail:
1126     /* Remove filters from graph */
1127     p_sys->p_graph->RemoveFilter( p_device_filter );
1128     p_sys->p_graph->RemoveFilter( p_capture_filter );
1129
1130     /* Release objects */
1131     p_device_filter->Release();
1132     p_capture_filter->Release();
1133
1134     return VLC_EGENERIC;
1135 }
1136
1137 static IBaseFilter *
1138 FindCaptureDevice( vlc_object_t *p_this, string *p_devicename,
1139                    list<string> *p_listdevices, vlc_bool_t b_audio )
1140 {
1141     IBaseFilter *p_base_filter = NULL;
1142     IMoniker *p_moniker = NULL;
1143     ULONG i_fetched;
1144     HRESULT hr;
1145
1146     /* Create the system device enumerator */
1147     ICreateDevEnum *p_dev_enum = NULL;
1148
1149     hr = CoCreateInstance( CLSID_SystemDeviceEnum, NULL, CLSCTX_INPROC,
1150                            IID_ICreateDevEnum, (void **)&p_dev_enum );
1151     if( FAILED(hr) )
1152     {
1153         msg_Err( p_this, "failed to create the device enumerator (0x%x)", hr);
1154         return NULL;
1155     }
1156
1157     /* Create an enumerator for the video capture devices */
1158     IEnumMoniker *p_class_enum = NULL;
1159     if( !b_audio )
1160         hr = p_dev_enum->CreateClassEnumerator( CLSID_VideoInputDeviceCategory,
1161                                                 &p_class_enum, 0 );
1162     else
1163         hr = p_dev_enum->CreateClassEnumerator( CLSID_AudioInputDeviceCategory,
1164                                                 &p_class_enum, 0 );
1165     p_dev_enum->Release();
1166     if( FAILED(hr) )
1167     {
1168         msg_Err( p_this, "failed to create the class enumerator (0x%x)", hr );
1169         return NULL;
1170     }
1171
1172     /* If there are no enumerators for the requested type, then
1173      * CreateClassEnumerator will succeed, but p_class_enum will be NULL */
1174     if( p_class_enum == NULL )
1175     {
1176         msg_Err( p_this, "no capture device was detected" );
1177         return NULL;
1178     }
1179
1180     /* Enumerate the devices */
1181
1182     /* Note that if the Next() call succeeds but there are no monikers,
1183      * it will return S_FALSE (which is not a failure). Therefore, we check
1184      * that the return code is S_OK instead of using SUCCEEDED() macro. */
1185
1186     while( p_class_enum->Next( 1, &p_moniker, &i_fetched ) == S_OK )
1187     {
1188         /* Getting the property page to get the device name */
1189         IPropertyBag *p_bag;
1190         hr = p_moniker->BindToStorage( 0, 0, IID_IPropertyBag,
1191                                        (void **)&p_bag );
1192         if( SUCCEEDED(hr) )
1193         {
1194             VARIANT var;
1195             var.vt = VT_BSTR;
1196             hr = p_bag->Read( L"FriendlyName", &var, NULL );
1197             p_bag->Release();
1198             if( SUCCEEDED(hr) )
1199             {
1200                 int i_convert = ( lstrlenW( var.bstrVal ) + 1 ) * 2;
1201                 char *p_buf = (char *)alloca( i_convert ); p_buf[0] = 0;
1202                 WideCharToMultiByte( CP_ACP, 0, var.bstrVal, -1, p_buf,
1203                                      i_convert, NULL, NULL );
1204                 SysFreeString(var.bstrVal);
1205
1206                 if( p_listdevices ) p_listdevices->push_back( p_buf );
1207
1208                 if( p_devicename && *p_devicename == string(p_buf) )
1209                 {
1210                     /* Bind Moniker to a filter object */
1211                     hr = p_moniker->BindToObject( 0, 0, IID_IBaseFilter,
1212                                                   (void **)&p_base_filter );
1213                     if( FAILED(hr) )
1214                     {
1215                         msg_Err( p_this, "couldn't bind moniker to filter "
1216                                  "object (0x%x)", hr );
1217                         p_moniker->Release();
1218                         p_class_enum->Release();
1219                         return NULL;
1220                     }
1221                     p_moniker->Release();
1222                     p_class_enum->Release();
1223                     return p_base_filter;
1224                 }
1225             }
1226         }
1227
1228         p_moniker->Release();
1229     }
1230
1231     p_class_enum->Release();
1232     return NULL;
1233 }
1234
1235 static size_t EnumDeviceCaps( vlc_object_t *p_this,
1236                                      IBaseFilter *p_filter,
1237                                      int i_fourcc, int i_width, int i_height,
1238                                      int i_channels, int i_samplespersec,
1239                                      int i_bitspersample, AM_MEDIA_TYPE *mt, size_t mt_max )
1240 {
1241     IEnumPins *p_enumpins;
1242     IPin *p_output_pin;
1243     IEnumMediaTypes *p_enummt;
1244     size_t mt_count = 0;
1245
1246     if( S_OK != p_filter->EnumPins( &p_enumpins ) ) return 0;
1247
1248     while( S_OK == p_enumpins->Next( 1, &p_output_pin, NULL ) )
1249     {
1250         PIN_INFO info;
1251
1252         if( S_OK == p_output_pin->QueryPinInfo( &info ) )
1253         {
1254             msg_Dbg( p_this, "EnumDeviceCaps: %s pin: %S",
1255                      info.dir == PINDIR_INPUT ? "input" : "output",
1256                      info.achName );
1257             if( info.pFilter ) info.pFilter->Release();
1258         }
1259
1260         p_output_pin->Release();
1261     }
1262     p_enumpins->Reset();
1263
1264     while( (0 == mt_count) && p_enumpins->Next( 1, &p_output_pin, NULL ) == S_OK )
1265     {
1266         PIN_INFO info;
1267
1268         if( S_OK == p_output_pin->QueryPinInfo( &info ) )
1269         {
1270             if( info.pFilter ) info.pFilter->Release();
1271             if( info.dir == PINDIR_INPUT )
1272             {
1273                 p_output_pin->Release();
1274                 continue;
1275             }
1276             msg_Dbg( p_this, "EnumDeviceCaps: trying pin %S", info.achName );
1277         }
1278
1279         /* Probe pin */
1280         if( SUCCEEDED( p_output_pin->EnumMediaTypes( &p_enummt ) ) )
1281         {
1282             AM_MEDIA_TYPE *p_mt;
1283             while( p_enummt->Next( 1, &p_mt, NULL ) == S_OK )
1284             {
1285                 int i_current_fourcc = GetFourCCFromMediaType(*p_mt);
1286                 if( 0 != i_current_fourcc )
1287                 {
1288                     if( p_mt->majortype == MEDIATYPE_Video )
1289                     {
1290                         int i_current_width = p_mt->pbFormat ?
1291                                 ((VIDEOINFOHEADER *)p_mt->pbFormat)->bmiHeader.biWidth : 0;
1292                         int i_current_height = p_mt->pbFormat ?
1293                                 ((VIDEOINFOHEADER *)p_mt->pbFormat)->bmiHeader.biHeight : 0;
1294                         if( i_current_height < 0 )
1295                                 i_current_height = -i_current_height; 
1296
1297                         msg_Dbg( p_this, "EnumDeviceCaps: input pin "
1298                                          "accepts chroma: %4.4s, width:%i, height:%i",
1299                                          (char *)&i_current_fourcc, i_current_width,
1300                                          i_current_height );
1301
1302                         if( ( !i_fourcc || i_fourcc == i_current_fourcc ) &&
1303                                 ( !i_width || i_width == i_current_width ) &&
1304                                 ( !i_height || i_height == i_current_height ) &&
1305                                 (mt_count < mt_max) )
1306                         {
1307                             /* Pick match */
1308                             mt[mt_count++] = *p_mt;
1309                         }
1310                         else
1311                         {
1312                             FreeMediaType( *p_mt );
1313                         }
1314                     }
1315                     else if( p_mt->majortype == MEDIATYPE_Audio )
1316                     {
1317                         int i_current_channels =
1318                                 ((WAVEFORMATEX *)p_mt->pbFormat)->nChannels;
1319                         int i_current_samplespersec =
1320                                 ((WAVEFORMATEX *)p_mt->pbFormat)->nSamplesPerSec;
1321                         int i_current_bitspersample =
1322                                 ((WAVEFORMATEX *)p_mt->pbFormat)->wBitsPerSample;
1323
1324                         msg_Dbg( p_this, "EnumDeviceCaps: input pin "
1325                                          "accepts format: %4.4s, channels:%i, "
1326                                          "samples/sec:%i bits/sample:%i",
1327                                          (char *)&i_current_fourcc, i_current_channels,
1328                                          i_current_samplespersec, i_current_bitspersample);
1329
1330                         if( (!i_channels || i_channels == i_current_channels) &&
1331                                 (!i_samplespersec ||
1332                                  i_samplespersec == i_current_samplespersec) &&
1333                                 (!i_bitspersample ||
1334                                  i_bitspersample == i_current_bitspersample) &&
1335                                 (mt_count < mt_max) )
1336                         {
1337                             /* Pick  match */
1338                             mt[mt_count++] = *p_mt;
1339
1340                             /* Pre-Configure the 1st match, Ugly */
1341                             if( 1 == mt_count ) {
1342                                 /* Setup a few properties like the audio latency */
1343                                 IAMBufferNegotiation *p_ambuf;
1344
1345                                 if( SUCCEEDED( p_output_pin->QueryInterface(
1346                                           IID_IAMBufferNegotiation, (void **)&p_ambuf ) ) )
1347                                 {
1348                                     ALLOCATOR_PROPERTIES AllocProp;
1349                                     AllocProp.cbAlign = -1;
1350                                     AllocProp.cbBuffer = i_current_channels *
1351                                       i_current_samplespersec *
1352                                       i_current_bitspersample / 8 / 10 ; /*100 ms of latency*/
1353                                     AllocProp.cbPrefix = -1;
1354                                     AllocProp.cBuffers = -1;
1355                                     p_ambuf->SuggestAllocatorProperties( &AllocProp );
1356                                     p_ambuf->Release();
1357                                 }
1358                             }
1359                         }
1360                         else
1361                         {
1362                             FreeMediaType( *p_mt );
1363                         }
1364                     }
1365                     else if( p_mt->majortype == MEDIATYPE_Stream )
1366                     {
1367                         msg_Dbg( p_this, "EnumDeviceCaps: MEDIATYPE_Stream" );
1368
1369                         if( ( !i_fourcc || i_fourcc == i_current_fourcc ) &&
1370                                 (mt_count < mt_max) )
1371                         {
1372                                 /* Pick match */
1373                                 mt[mt_count++] = *p_mt;
1374                                 i_fourcc = i_current_fourcc;
1375                         }
1376                         else
1377                         {
1378                                 FreeMediaType( *p_mt );
1379                         }
1380                     }
1381                     else
1382                     {
1383                         msg_Dbg( p_this,
1384                                          "EnumDeviceCaps: input pin: unknown format" );
1385                         FreeMediaType( *p_mt );
1386                     }
1387                 }
1388                 else
1389                 {
1390                     msg_Dbg( p_this,
1391                                      "EnumDeviceCaps: input pin: unknown format" );
1392                     FreeMediaType( *p_mt );
1393                 }
1394                 CoTaskMemFree( (PVOID)p_mt );
1395             }
1396             p_enummt->Release();
1397         }
1398
1399         p_output_pin->Release();
1400     }
1401
1402     p_enumpins->Release();
1403     return mt_count;
1404 }
1405
1406 /*****************************************************************************
1407  * Read: reads from the device into PES packets.
1408  *****************************************************************************
1409  * Returns -1 in case of error, 0 in case of EOF, otherwise the number of
1410  * bytes.
1411  *****************************************************************************/
1412 static ssize_t Read( input_thread_t * p_input, byte_t * p_buffer,
1413                      size_t i_len )
1414 {
1415     access_sys_t   *p_sys = p_input->p_access_data;
1416     dshow_stream_t *p_stream = NULL;
1417     byte_t         *p_buf_orig = p_buffer;
1418     VLCMediaSample  sample;
1419     int             i_data_size;
1420     uint8_t         *p_data;
1421
1422     if( p_sys->i_header_pos )
1423     {
1424         /* First header of the stream */
1425         memcpy( p_buffer, p_sys->p_header, p_sys->i_header_size );
1426         p_buffer += p_sys->i_header_size;
1427         p_sys->i_header_pos = 0;
1428     }
1429
1430     while( 1 )
1431     {
1432         /* Get new sample/frame from next elementary stream.
1433          * We first loop through all the elementary streams and if all our
1434          * fifos are empty we block until we are signaled some new data has
1435          * arrived. */
1436         vlc_mutex_lock( &p_sys->lock );
1437
1438         int i_stream;
1439         for( i_stream = 0; i_stream < p_sys->i_streams; i_stream++ )
1440         {
1441             p_stream = p_sys->pp_streams[i_stream];
1442             if( p_stream->mt.majortype == MEDIATYPE_Audio &&
1443                 p_stream->p_capture_filter &&
1444                 p_stream->p_capture_filter->CustomGetPin()
1445                   ->CustomGetSample( &sample ) == S_OK )
1446             {
1447                 break;
1448             }
1449         }
1450         if( i_stream == p_sys->i_streams )
1451         for( i_stream = 0; i_stream < p_sys->i_streams; i_stream++ )
1452         {
1453             p_stream = p_sys->pp_streams[i_stream];
1454             if( p_stream->p_capture_filter &&
1455                 p_stream->p_capture_filter->CustomGetPin()
1456                   ->CustomGetSample( &sample ) == S_OK )
1457             {
1458                 break;
1459             }
1460         }
1461         if( i_stream == p_sys->i_streams )
1462         {
1463             /* No data available. Wait until some data has arrived */
1464             vlc_cond_wait( &p_sys->wait, &p_sys->lock );
1465             vlc_mutex_unlock( &p_sys->lock );
1466             continue;
1467         }
1468
1469         vlc_mutex_unlock( &p_sys->lock );
1470
1471         /*
1472          * We got our sample
1473          */
1474         i_data_size = sample.p_sample->GetActualDataLength();
1475         sample.p_sample->GetPointer( &p_data );
1476
1477         REFERENCE_TIME i_pts, i_end_date;
1478         HRESULT hr = sample.p_sample->GetTime( &i_pts, &i_end_date );
1479         if( hr != VFW_S_NO_STOP_TIME && hr != S_OK ) i_pts = 0;
1480
1481         if( !i_pts )
1482         {
1483             if( p_stream->mt.majortype == MEDIATYPE_Video || !p_stream->b_pts )
1484             {
1485                 /* Use our data timestamp */
1486                 i_pts = sample.i_timestamp;
1487                 p_stream->b_pts = VLC_TRUE;
1488             }
1489         }
1490
1491 #if 0
1492         msg_Dbg( p_input, "Read() stream: %i PTS: "I64Fd, i_stream, i_pts );
1493 #endif
1494
1495         /* Create pseudo header */
1496         SetDWBE( &p_sys->p_header[0], i_stream );
1497         SetDWBE( &p_sys->p_header[4], i_data_size );
1498         SetQWBE( &p_sys->p_header[8], i_pts  * 9 / 1000 );
1499
1500 #if 0
1501         msg_Info( p_input, "access read %i data_size %i", i_len, i_data_size );
1502 #endif
1503
1504         /* First copy header */
1505         memcpy( p_buffer, p_sys->p_header, 16 /* header size */ );
1506         p_buffer += 16 /* header size */;
1507
1508         /* Then copy stream data if any */
1509         if( !p_stream->b_invert )
1510         {
1511             p_input->p_vlc->pf_memcpy( p_buffer, p_data, i_data_size );
1512             p_buffer += i_data_size;
1513         }
1514         else
1515         {
1516             int i_width = p_stream->header.video.bmiHeader.biWidth;
1517             int i_height = p_stream->header.video.bmiHeader.biHeight;
1518             if( i_height < 0 ) i_height = - i_height;
1519
1520             switch( p_stream->i_fourcc )
1521             {
1522             case VLC_FOURCC( 'R', 'V', '1', '5' ):
1523             case VLC_FOURCC( 'R', 'V', '1', '6' ):
1524                 i_width *= 2;
1525                 break;
1526             case VLC_FOURCC( 'R', 'V', '2', '4' ):
1527                 i_width *= 3;
1528                 break;
1529             case VLC_FOURCC( 'R', 'V', '3', '2' ):
1530             case VLC_FOURCC( 'R', 'G', 'B', 'A' ):
1531                 i_width *= 4;
1532                 break;
1533             }
1534
1535             for( int i = i_height - 1; i >= 0; i-- )
1536             {
1537                 p_input->p_vlc->pf_memcpy( p_buffer,
1538                      &p_data[i * i_width], i_width );
1539
1540                 p_buffer += i_width;
1541             }
1542         }
1543
1544         sample.p_sample->Release();
1545
1546         /* The caller got what he wanted */
1547         return p_buffer - p_buf_orig;
1548     }
1549
1550     return 0; /* never reached */
1551 }
1552
1553 /*****************************************************************************
1554  * ReadCompressed: reads compressed (MPEG/DV) data from the device.
1555  *****************************************************************************
1556  * Returns -1 in case of error, 0 in case of EOF, otherwise the number of
1557  * bytes.
1558  *****************************************************************************/
1559 static ssize_t ReadCompressed( input_thread_t * p_input, byte_t * p_buffer,
1560                                size_t i_len )
1561 {
1562     access_sys_t   *p_sys = p_input->p_access_data;
1563     dshow_stream_t *p_stream = NULL;
1564     VLCMediaSample  sample;
1565     int             i_data_size;
1566     uint8_t         *p_data;
1567
1568     /* Read 1 DV/MPEG frame (they contain the video and audio data) */
1569
1570     /* There must be only 1 elementary stream to produce a valid stream
1571      * of MPEG or DV data */
1572     p_stream = p_sys->pp_streams[0];
1573
1574     while( 1 )
1575     {
1576         if( p_input->b_die || p_input->b_error ) return 0;
1577
1578         /* Get new sample/frame from the elementary stream (blocking). */
1579         vlc_mutex_lock( &p_sys->lock );
1580
1581         if( p_stream->p_capture_filter->CustomGetPin()
1582               ->CustomGetSample( &sample ) != S_OK )
1583         {
1584             /* No data available. Wait until some data has arrived */
1585             vlc_cond_wait( &p_sys->wait, &p_sys->lock );
1586             vlc_mutex_unlock( &p_sys->lock );
1587             continue;
1588         }
1589
1590         vlc_mutex_unlock( &p_sys->lock );
1591
1592         /*
1593          * We got our sample
1594          */
1595         i_data_size = sample.p_sample->GetActualDataLength();
1596         sample.p_sample->GetPointer( &p_data );
1597
1598 #if 0
1599         msg_Info( p_input, "access read %i data_size %i", i_len, i_data_size );
1600 #endif
1601         i_data_size = __MIN( i_data_size, (int)i_len );
1602
1603         p_input->p_vlc->pf_memcpy( p_buffer, p_data, i_data_size );
1604
1605         sample.p_sample->Release();
1606
1607         /* The caller got what he wanted */
1608         return i_data_size;
1609     }
1610
1611     return 0; /* never reached */
1612 }
1613
1614 /*****************************************************************************
1615  * Demux: local prototypes
1616  *****************************************************************************/
1617 struct demux_sys_t
1618 {
1619     int         i_es;
1620     es_out_id_t **es;
1621 };
1622
1623 static int  Demux      ( input_thread_t * );
1624
1625 /****************************************************************************
1626  * DemuxOpen:
1627  ****************************************************************************/
1628 static int DemuxOpen( vlc_object_t *p_this )
1629 {
1630     input_thread_t *p_input = (input_thread_t *)p_this;
1631     demux_sys_t    *p_sys;
1632
1633     uint8_t        *p_peek;
1634     int            i_es;
1635     int            i;
1636
1637     /* a little test to see if it's a dshow stream */
1638     if( stream_Peek( p_input->s, &p_peek, 8 ) < 8 )
1639     {
1640         msg_Warn( p_input, "dshow plugin discarded (cannot peek)" );
1641         return VLC_EGENERIC;
1642     }
1643
1644     if( memcmp( p_peek, ".dsh", 4 ) ||
1645         ( i_es = GetDWBE( &p_peek[4] ) ) <= 0 )
1646     {
1647         msg_Warn( p_input, "dshow plugin discarded (not a valid stream)" );
1648         return VLC_EGENERIC;
1649     }
1650
1651     vlc_mutex_lock( &p_input->stream.stream_lock );
1652     if( input_InitStream( p_input, 0 ) == -1)
1653     {
1654         vlc_mutex_unlock( &p_input->stream.stream_lock );
1655         msg_Err( p_input, "cannot init stream" );
1656         return VLC_EGENERIC;
1657     }
1658     p_input->stream.i_mux_rate =  0 / 50;
1659     vlc_mutex_unlock( &p_input->stream.stream_lock );
1660
1661     p_input->pf_demux = Demux;
1662     p_input->pf_demux_control = demux_vaControlDefault;
1663     p_input->p_demux_data = p_sys =
1664         (demux_sys_t *)malloc( sizeof( demux_sys_t ) );
1665     p_sys->i_es = 0;
1666     p_sys->es   = NULL;
1667
1668     if( stream_Peek( p_input->s, &p_peek, 8 + 20 * i_es ) < 8 + 20 * i_es )
1669     {
1670         msg_Err( p_input, "dshow plugin discarded (cannot peek)" );
1671         return VLC_EGENERIC;
1672     }
1673     p_peek += 8;
1674
1675     for( i = 0; i < i_es; i++ )
1676     {
1677         es_format_t fmt;
1678
1679         if( !memcmp( p_peek, "auds", 4 ) )
1680         {
1681             es_format_Init( &fmt, AUDIO_ES, VLC_FOURCC( p_peek[4], p_peek[5],
1682                                                         p_peek[6], p_peek[7] ) );
1683
1684             fmt.audio.i_channels = GetDWBE( &p_peek[8] );
1685             fmt.audio.i_rate = GetDWBE( &p_peek[12] );
1686             fmt.audio.i_bitspersample = GetDWBE( &p_peek[16] );
1687             fmt.audio.i_blockalign = fmt.audio.i_channels *
1688                                      fmt.audio.i_bitspersample / 8;
1689             fmt.i_bitrate = fmt.audio.i_channels *
1690                             fmt.audio.i_rate *
1691                             fmt.audio.i_bitspersample;
1692
1693             msg_Dbg( p_input, "new audio es %d channels %dHz",
1694                      fmt.audio.i_channels, fmt.audio.i_rate );
1695
1696             p_sys->es = (es_out_id_t **)realloc( p_sys->es,
1697                           sizeof(es_out_id_t *) * (p_sys->i_es + 1) );
1698             p_sys->es[p_sys->i_es++] = es_out_Add( p_input->p_es_out, &fmt );
1699         }
1700         else if( !memcmp( p_peek, "vids", 4 ) )
1701         {
1702             es_format_Init( &fmt, VIDEO_ES, VLC_FOURCC( p_peek[4], p_peek[5],
1703                                                         p_peek[6], p_peek[7] ) );
1704             fmt.video.i_width  = GetDWBE( &p_peek[8] );
1705             fmt.video.i_height = GetDWBE( &p_peek[12] );
1706
1707             msg_Dbg( p_input, "added new video es %4.4s %dx%d",
1708                      (char*)&fmt.i_codec,
1709                      fmt.video.i_width, fmt.video.i_height );
1710
1711             p_sys->es = (es_out_id_t **)realloc( p_sys->es,
1712                           sizeof(es_out_id_t *) * (p_sys->i_es + 1) );
1713             p_sys->es[p_sys->i_es++] = es_out_Add( p_input->p_es_out, &fmt );
1714         }
1715
1716         p_peek += 20;
1717     }
1718
1719     /* Skip header */
1720     stream_Read( p_input->s, NULL, 8 + 20 * i_es );
1721
1722     return VLC_SUCCESS;
1723 }
1724
1725 /****************************************************************************
1726  * DemuxClose:
1727  ****************************************************************************/
1728 static void DemuxClose( vlc_object_t *p_this )
1729 {
1730     input_thread_t *p_input = (input_thread_t *)p_this;
1731     demux_sys_t    *p_sys = p_input->p_demux_data;
1732
1733     if( p_sys->i_es > 0 )
1734     {
1735         free( p_sys->es );
1736     }
1737     free( p_sys );
1738 }
1739
1740 /****************************************************************************
1741  * Demux:
1742  ****************************************************************************/
1743 static int Demux( input_thread_t *p_input )
1744 {
1745     demux_sys_t *p_sys = p_input->p_demux_data;
1746     block_t     *p_block;
1747
1748     int i_es;
1749     int i_size;
1750
1751     uint8_t *p_peek;
1752     mtime_t i_pcr;
1753
1754     if( stream_Peek( p_input->s, &p_peek, 16 ) < 16 )
1755     {
1756         msg_Warn( p_input, "cannot peek (EOF ?)" );
1757         return 0;
1758     }
1759
1760     i_es   = GetDWBE( &p_peek[0] );
1761     if( i_es < 0 || i_es >= p_sys->i_es )
1762     {
1763         msg_Err( p_input, "cannot find ES" );
1764         return -1;
1765     }
1766
1767     i_size = GetDWBE( &p_peek[4] );
1768     i_pcr  = GetQWBE( &p_peek[8] );
1769
1770     if( ( p_block = stream_Block( p_input->s, 16 + i_size ) ) == NULL )
1771     {
1772         msg_Warn( p_input, "cannot read data" );
1773         return 0;
1774     }
1775
1776     p_block->p_buffer += 16;
1777     p_block->i_buffer -= 16;
1778
1779     /* Call the pace control. */
1780     input_ClockManageRef( p_input, p_input->stream.p_selected_program, i_pcr );
1781
1782     p_block->i_dts =
1783     p_block->i_pts = i_pcr <= 0 ? 0 :
1784         input_ClockGetTS( p_input, p_input->stream.p_selected_program, i_pcr );
1785
1786     es_out_Send( p_input->p_es_out, p_sys->es[i_es], p_block );
1787
1788     return 1;
1789 }
1790
1791
1792 /*****************************************************************************
1793  * config variable callback
1794  *****************************************************************************/
1795 static int FindDevicesCallback( vlc_object_t *p_this, char const *psz_name,
1796                                vlc_value_t newval, vlc_value_t oldval, void * )
1797 {
1798     module_config_t *p_item;
1799     vlc_bool_t b_audio = VLC_FALSE;
1800     int i;
1801
1802     p_item = config_FindConfig( p_this, psz_name );
1803     if( !p_item ) return VLC_SUCCESS;
1804
1805     if( !strcmp( psz_name, "dshow-adev" ) ) b_audio = VLC_TRUE;
1806
1807     /* Clear-up the current list */
1808     if( p_item->i_list )
1809     {
1810         /* Keep the 2 first entries */
1811         for( i = 2; i < p_item->i_list; i++ )
1812         {
1813             free( p_item->ppsz_list[i] );
1814             free( p_item->ppsz_list_text[i] );
1815         }
1816         /* TODO: Remove when no more needed */
1817         p_item->ppsz_list[i] = NULL;
1818         p_item->ppsz_list_text[i] = NULL;
1819     }
1820     p_item->i_list = 2;
1821
1822     /* Find list of devices */
1823     list<string> list_devices;
1824
1825     /* Initialize OLE/COM */
1826     CoInitialize( 0 );
1827
1828     FindCaptureDevice( p_this, NULL, &list_devices, b_audio );
1829
1830     /* Uninitialize OLE/COM */
1831     CoUninitialize();
1832
1833     if( !list_devices.size() ) return VLC_SUCCESS;
1834
1835     p_item->ppsz_list =
1836         (char **)realloc( p_item->ppsz_list,
1837                           (list_devices.size()+3) * sizeof(char *) );
1838     p_item->ppsz_list_text =
1839         (char **)realloc( p_item->ppsz_list_text,
1840                           (list_devices.size()+3) * sizeof(char *) );
1841
1842     list<string>::iterator iter;
1843     for( iter = list_devices.begin(), i = 2; iter != list_devices.end();
1844          iter++, i++ )
1845     {
1846         p_item->ppsz_list[i] = strdup( iter->c_str() );
1847         p_item->ppsz_list_text[i] = NULL;
1848         p_item->i_list++;
1849     }
1850     p_item->ppsz_list[i] = NULL;
1851     p_item->ppsz_list_text[i] = NULL;
1852
1853     /* Signal change to the interface */
1854     p_item->b_dirty = VLC_TRUE;
1855
1856     return VLC_SUCCESS;
1857 }
1858
1859 static int ConfigDevicesCallback( vlc_object_t *p_this, char const *psz_name,
1860                                vlc_value_t newval, vlc_value_t oldval, void * )
1861 {
1862     module_config_t *p_item;
1863     vlc_bool_t b_audio = VLC_FALSE;
1864
1865     /* Initialize OLE/COM */
1866     CoInitialize( 0 );
1867
1868     p_item = config_FindConfig( p_this, psz_name );
1869     if( !p_item ) return VLC_SUCCESS;
1870
1871     if( !strcmp( psz_name, "dshow-adev" ) ) b_audio = VLC_TRUE;
1872
1873     string devicename;
1874
1875     if( newval.psz_string && *newval.psz_string )
1876     {
1877         devicename = newval.psz_string;
1878     }
1879     else
1880     {
1881         /* If no device name was specified, pick the 1st one */
1882         list<string> list_devices;
1883
1884         /* Enumerate devices */
1885         FindCaptureDevice( p_this, NULL, &list_devices, b_audio );
1886         if( !list_devices.size() ) return VLC_EGENERIC;
1887         devicename = *list_devices.begin();
1888     }
1889
1890     IBaseFilter *p_device_filter =
1891         FindCaptureDevice( p_this, &devicename, NULL, b_audio );
1892     if( p_device_filter )
1893     {
1894         PropertiesPage( p_this, p_device_filter, NULL, b_audio );
1895     }
1896     else
1897     {
1898         /* Uninitialize OLE/COM */
1899         CoUninitialize();
1900
1901         msg_Err( p_this, "didn't find device: %s", devicename.c_str() );
1902         return VLC_EGENERIC;
1903     }
1904
1905     /* Uninitialize OLE/COM */
1906     CoUninitialize();
1907
1908     return VLC_SUCCESS;
1909 }
1910
1911 static void ShowPropertyPage( IUnknown *obj, CAUUID *cauuid )
1912 {
1913     if( cauuid->cElems > 0 )
1914     {
1915         HWND hwnd_desktop = ::GetDesktopWindow();
1916
1917         OleCreatePropertyFrame( hwnd_desktop, 30, 30, NULL, 1, &obj,
1918                                 cauuid->cElems, cauuid->pElems, 0, 0, NULL );
1919
1920         CoTaskMemFree( cauuid->pElems );
1921     }
1922 }
1923
1924 static void PropertiesPage( vlc_object_t *p_this, IBaseFilter *p_device_filter,
1925                             ICaptureGraphBuilder2 *p_capture_graph,
1926                             vlc_bool_t b_audio )
1927 {
1928     CAUUID cauuid;
1929
1930     msg_Dbg( p_this, "Configuring Device Properties" );
1931
1932     /*
1933      * Video or audio capture filter page
1934      */
1935     ISpecifyPropertyPages *p_spec;
1936
1937     HRESULT hr = p_device_filter->QueryInterface( IID_ISpecifyPropertyPages,
1938                                                   (void **)&p_spec );
1939     if( SUCCEEDED(hr) )
1940     {
1941         if( SUCCEEDED(p_spec->GetPages( &cauuid )) )
1942         {
1943             ShowPropertyPage( p_device_filter, &cauuid );
1944         }
1945         p_spec->Release();
1946     }
1947
1948     msg_Dbg( p_this, "looking for WDM Configuration Pages" );
1949
1950     if( p_capture_graph )
1951         msg_Dbg( p_this, "got capture graph for WDM Configuration Pages" );
1952
1953     /*
1954      * Audio capture pin
1955      */
1956     if( p_capture_graph && b_audio )
1957     {
1958         IAMStreamConfig *p_SC;
1959
1960         hr = p_capture_graph->FindInterface( &PIN_CATEGORY_CAPTURE,
1961                                              &MEDIATYPE_Audio, p_device_filter,
1962                                              IID_IAMStreamConfig,
1963                                              (void **)&p_SC );
1964         if( SUCCEEDED(hr) )
1965         {
1966             hr = p_SC->QueryInterface( IID_ISpecifyPropertyPages,
1967                                        (void **)&p_spec );
1968             if( SUCCEEDED(hr) )
1969             {
1970                 hr = p_spec->GetPages( &cauuid );
1971                 if( SUCCEEDED(hr) )
1972                 {
1973                     for( unsigned int c = 0; c < cauuid.cElems; c++ )
1974                     {
1975                         ShowPropertyPage( p_SC, &cauuid );
1976                     }
1977                     CoTaskMemFree( cauuid.pElems );
1978                 }
1979                 p_spec->Release();
1980             }
1981             p_SC->Release();
1982         }
1983
1984         /*
1985          * TV Audio filter
1986          */
1987         IAMTVAudio *p_TVA;
1988         hr = p_capture_graph->FindInterface( &PIN_CATEGORY_CAPTURE, 
1989                                              &MEDIATYPE_Audio, p_device_filter,
1990                                              IID_IAMTVAudio, (void **)&p_TVA );
1991         if( SUCCEEDED(hr) )
1992         {
1993             hr = p_TVA->QueryInterface( IID_ISpecifyPropertyPages,
1994                                         (void **)&p_spec );
1995             if( SUCCEEDED(hr) )
1996             {
1997                 if( SUCCEEDED( p_spec->GetPages( &cauuid ) ) )
1998                     ShowPropertyPage(p_TVA, &cauuid);
1999
2000                 p_spec->Release();
2001             }
2002             p_TVA->Release();
2003         }
2004     }
2005
2006     /*
2007      * Video capture pin
2008      */
2009     if( p_capture_graph && !b_audio )
2010     {
2011         IAMStreamConfig *p_SC;
2012
2013         hr = p_capture_graph->FindInterface( &PIN_CATEGORY_CAPTURE,
2014                                              &MEDIATYPE_Interleaved,
2015                                              p_device_filter,
2016                                              IID_IAMStreamConfig,
2017                                              (void **)&p_SC );
2018         if( FAILED(hr) )
2019         {
2020             hr = p_capture_graph->FindInterface( &PIN_CATEGORY_CAPTURE,
2021                                                  &MEDIATYPE_Video,
2022                                                  p_device_filter,
2023                                                  IID_IAMStreamConfig,
2024                                                  (void **)&p_SC );
2025         }
2026
2027         if( SUCCEEDED(hr) )
2028         {
2029             hr = p_SC->QueryInterface( IID_ISpecifyPropertyPages,
2030                                        (void **)&p_spec );
2031             if( SUCCEEDED(hr) )
2032             {
2033                 if( SUCCEEDED( p_spec->GetPages(&cauuid) ) )
2034                 {
2035                     ShowPropertyPage(p_SC, &cauuid);
2036                 }
2037                 p_spec->Release();
2038             }
2039             p_SC->Release();
2040         }
2041
2042         /*
2043          * Video crossbar, and a possible second crossbar
2044          */
2045         IAMCrossbar *p_X, *p_X2;
2046         IBaseFilter *p_XF;
2047
2048         hr = p_capture_graph->FindInterface( &PIN_CATEGORY_CAPTURE,
2049                                              &MEDIATYPE_Interleaved,
2050                                              p_device_filter,
2051                                              IID_IAMCrossbar, (void **)&p_X );
2052         if( FAILED(hr) )
2053         {
2054             hr = p_capture_graph->FindInterface( &PIN_CATEGORY_CAPTURE,
2055                                                  &MEDIATYPE_Video,
2056                                                  p_device_filter,
2057                                                  IID_IAMCrossbar,
2058                                                  (void **)&p_X );
2059         }
2060
2061         if( SUCCEEDED(hr) )
2062         {
2063             hr = p_X->QueryInterface( IID_IBaseFilter, (void **)&p_XF );
2064             if( SUCCEEDED(hr) )
2065             {
2066                 hr = p_X->QueryInterface( IID_ISpecifyPropertyPages,
2067                                           (void **)&p_spec );
2068                 if( SUCCEEDED(hr) )
2069                 {
2070                     hr = p_spec->GetPages(&cauuid);
2071                     if( hr == S_OK && cauuid.cElems > 0 )
2072                     {
2073                         ShowPropertyPage( p_X, &cauuid );
2074                     }
2075                     p_spec->Release();
2076                 }
2077
2078                 hr = p_capture_graph->FindInterface( &LOOK_UPSTREAM_ONLY, NULL,
2079                                                      p_XF, IID_IAMCrossbar,
2080                                                      (void **)&p_X2 );
2081                 if( SUCCEEDED(hr) )
2082                 {
2083                     hr = p_X2->QueryInterface( IID_ISpecifyPropertyPages,
2084                                                (void **)&p_spec );
2085                     if( SUCCEEDED(hr) )
2086                     {
2087                         hr = p_spec->GetPages( &cauuid );
2088                         if( SUCCEEDED(hr) )
2089                         {
2090                             ShowPropertyPage( p_X2, &cauuid );
2091                         }
2092                         p_spec->Release();
2093                     }
2094                     p_X2->Release();
2095                 }
2096
2097                 p_XF->Release();
2098             }
2099
2100             p_X->Release();
2101         }
2102
2103         /*
2104          * TV Tuner
2105          */
2106         IAMTVTuner *p_TV;
2107         hr = p_capture_graph->FindInterface( &PIN_CATEGORY_CAPTURE,
2108                                              &MEDIATYPE_Interleaved,
2109                                              p_device_filter,
2110                                              IID_IAMTVTuner, (void **)&p_TV );
2111         if( FAILED(hr) )
2112         {
2113             hr = p_capture_graph->FindInterface( &PIN_CATEGORY_CAPTURE,
2114                                                  &MEDIATYPE_Video,
2115                                                  p_device_filter,
2116                                                  IID_IAMTVTuner,
2117                                                  (void **)&p_TV );
2118         }
2119
2120         if( SUCCEEDED(hr) )
2121         {
2122             hr = p_TV->QueryInterface( IID_ISpecifyPropertyPages,
2123                                        (void **)&p_spec );
2124             if( SUCCEEDED(hr) )
2125             {
2126                 hr = p_spec->GetPages(&cauuid);
2127                 if( SUCCEEDED(hr) )
2128                 {
2129                     ShowPropertyPage(p_TV, &cauuid);
2130                 }
2131                 p_spec->Release();
2132             }
2133             p_TV->Release();
2134         }
2135     }
2136 }