]> git.sesse.net Git - vlc/blob - modules/access/dshow/dshow.cpp
* include/modules_inner.h, include/modules.h: added a shortname field to the module...
[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 AM_MEDIA_TYPE EnumDeviceCaps( vlc_object_t *, IBaseFilter *,
47                                      int, int, int, int, int, int );
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 static int OpenDevice( input_thread_t *p_input, string devicename,
815                        vlc_bool_t b_audio )
816 {
817     access_sys_t *p_sys = p_input->p_access_data;
818
819     /* See if device is already opened */
820     for( int i = 0; i < p_sys->i_streams; i++ )
821     {
822         if( p_sys->pp_streams[i]->devicename == devicename )
823         {
824             /* Already opened */
825             return VLC_SUCCESS;
826         }
827     }
828
829     list<string> list_devices;
830
831     /* Enumerate devices and display their names */
832     FindCaptureDevice( (vlc_object_t *)p_input, NULL, &list_devices, b_audio );
833
834     if( !list_devices.size() )
835         return VLC_EGENERIC;
836
837     list<string>::iterator iter;
838     for( iter = list_devices.begin(); iter != list_devices.end(); iter++ )
839         msg_Dbg( p_input, "found device: %s", iter->c_str() );
840
841     /* If no device name was specified, pick the 1st one */
842     if( devicename.size() == 0 )
843     {
844         devicename = *list_devices.begin();
845     }
846
847     // Use the system device enumerator and class enumerator to find
848     // a capture/preview device, such as a desktop USB video camera.
849     IBaseFilter *p_device_filter =
850         FindCaptureDevice( (vlc_object_t *)p_input, &devicename,
851                            NULL, b_audio );
852     if( p_device_filter )
853         msg_Dbg( p_input, "using device: %s", devicename.c_str() );
854     else
855     {
856         msg_Err( p_input, "can't use device: %s", devicename.c_str() );
857         return VLC_EGENERIC;
858     }
859
860     AM_MEDIA_TYPE media_type =
861         EnumDeviceCaps( (vlc_object_t *)p_input, p_device_filter,
862                         p_sys->i_chroma, p_sys->i_width, p_sys->i_height,
863                         0, 0, 0 );
864
865     /* Create and add our capture filter */
866     CaptureFilter *p_capture_filter = new CaptureFilter( p_input, media_type );
867     p_sys->p_graph->AddFilter( p_capture_filter, 0 );
868
869     /* Add the device filter to the graph (seems necessary with VfW before
870      * accessing pin attributes). */
871     p_sys->p_graph->AddFilter( p_device_filter, 0 );
872
873     /* Attempt to connect one of this device's capture output pins */
874     msg_Dbg( p_input, "connecting filters" );
875     if( ConnectFilters( VLC_OBJECT(p_input), p_device_filter,
876                         p_capture_filter ) )
877     {
878         /* Success */
879         msg_Dbg( p_input, "filters connected successfully !" );
880
881         dshow_stream_t dshow_stream;
882         dshow_stream.b_invert = VLC_FALSE;
883         dshow_stream.b_pts = VLC_FALSE;
884         dshow_stream.mt =
885             p_capture_filter->CustomGetPin()->CustomGetMediaType();
886
887         /* Show properties. Done here so the VLC stream is setup with the
888          * proper parameters. */
889         vlc_value_t val;
890         var_Get( p_input, "dshow-config", &val );
891         if( val.i_int )
892         {
893             PropertiesPage( VLC_OBJECT(p_input), p_device_filter,
894                             p_sys->p_capture_graph_builder2,
895                             dshow_stream.mt.majortype == MEDIATYPE_Audio ||
896                             dshow_stream.mt.formattype == FORMAT_WaveFormatEx);
897         }
898
899         dshow_stream.mt =
900             p_capture_filter->CustomGetPin()->CustomGetMediaType();
901
902         if( dshow_stream.mt.majortype == MEDIATYPE_Video )
903         {
904             msg_Dbg( p_input, "MEDIATYPE_Video");
905
906             /* Packed RGB formats */
907             if( dshow_stream.mt.subtype == MEDIASUBTYPE_RGB1 )
908                 dshow_stream.i_fourcc = VLC_FOURCC( 'R', 'G', 'B', '1' );
909             if( dshow_stream.mt.subtype == MEDIASUBTYPE_RGB4 )
910                 dshow_stream.i_fourcc = VLC_FOURCC( 'R', 'G', 'B', '4' );
911             if( dshow_stream.mt.subtype == MEDIASUBTYPE_RGB8 )
912                 dshow_stream.i_fourcc = VLC_FOURCC( 'R', 'G', 'B', '8' );
913             else if( dshow_stream.mt.subtype == MEDIASUBTYPE_RGB555 )
914                 dshow_stream.i_fourcc = VLC_FOURCC( 'R', 'V', '1', '5' );
915             else if( dshow_stream.mt.subtype == MEDIASUBTYPE_RGB565 )
916                 dshow_stream.i_fourcc = VLC_FOURCC( 'R', 'V', '1', '6' );
917             else if( dshow_stream.mt.subtype == MEDIASUBTYPE_RGB24 )
918                 dshow_stream.i_fourcc = VLC_FOURCC( 'R', 'V', '2', '4' );
919             else if( dshow_stream.mt.subtype == MEDIASUBTYPE_RGB32 )
920                 dshow_stream.i_fourcc = VLC_FOURCC( 'R', 'V', '3', '2' );
921             else if( dshow_stream.mt.subtype == MEDIASUBTYPE_ARGB32 )
922                 dshow_stream.i_fourcc = VLC_FOURCC( 'R', 'G', 'B', 'A' );
923
924             /* Packed YUV formats */
925             else if( dshow_stream.mt.subtype == MEDIASUBTYPE_YVYU )
926                 dshow_stream.i_fourcc = VLC_FOURCC( 'Y', 'V', 'Y', 'U' );
927             else if( dshow_stream.mt.subtype == MEDIASUBTYPE_YUYV )
928                 dshow_stream.i_fourcc = VLC_FOURCC( 'Y', 'U', 'Y', 'V' );
929             else if( dshow_stream.mt.subtype == MEDIASUBTYPE_Y411 )
930                 dshow_stream.i_fourcc = VLC_FOURCC( 'I', '4', '1', 'N' );
931             else if( dshow_stream.mt.subtype == MEDIASUBTYPE_Y211 )
932                 dshow_stream.i_fourcc = VLC_FOURCC( 'Y', '2', '1', '1' );
933             else if( dshow_stream.mt.subtype == MEDIASUBTYPE_YUY2 ||
934                      dshow_stream.mt.subtype == MEDIASUBTYPE_UYVY )
935                 dshow_stream.i_fourcc = VLC_FOURCC( 'Y', 'U', 'Y', '2' );
936
937             /* Planar YUV formats */
938             else if( dshow_stream.mt.subtype == MEDIASUBTYPE_I420 )
939                 dshow_stream.i_fourcc = VLC_FOURCC( 'I', '4', '2', '0' );
940             else if( dshow_stream.mt.subtype == MEDIASUBTYPE_Y41P )
941                 dshow_stream.i_fourcc = VLC_FOURCC( 'I', '4', '1', '1' );
942             else if( dshow_stream.mt.subtype == MEDIASUBTYPE_YV12 ||
943                      dshow_stream.mt.subtype == MEDIASUBTYPE_IYUV )
944                 dshow_stream.i_fourcc = VLC_FOURCC( 'Y', 'V', '1', '2' );
945             else if( dshow_stream.mt.subtype == MEDIASUBTYPE_YVU9 )
946                 dshow_stream.i_fourcc = VLC_FOURCC( 'Y', 'V', 'U', '9' );
947
948             /* DV formats */
949             else if( dshow_stream.mt.subtype == MEDIASUBTYPE_dvsl )
950                 dshow_stream.i_fourcc = VLC_FOURCC( 'd', 'v', 's', 'l' );
951             else if( dshow_stream.mt.subtype == MEDIASUBTYPE_dvsd )
952                 dshow_stream.i_fourcc = VLC_FOURCC( 'd', 'v', 's', 'd' );
953             else if( dshow_stream.mt.subtype == MEDIASUBTYPE_dvhd )
954                 dshow_stream.i_fourcc = VLC_FOURCC( 'd', 'v', 'h', 'd' );
955
956             /* MPEG video formats */
957             else if( dshow_stream.mt.subtype == MEDIASUBTYPE_MPEG2_VIDEO )
958                 dshow_stream.i_fourcc = VLC_FOURCC( 'm', 'p', '2', 'v' );
959
960             else goto fail;
961
962             dshow_stream.header.video =
963                 *(VIDEOINFOHEADER *)dshow_stream.mt.pbFormat;
964
965             int i_height = dshow_stream.header.video.bmiHeader.biHeight;
966
967             /* Check if the image is inverted (bottom to top) */
968             if( dshow_stream.i_fourcc == VLC_FOURCC( 'R', 'G', 'B', '1' ) ||
969                 dshow_stream.i_fourcc == VLC_FOURCC( 'R', 'G', 'B', '4' ) ||
970                 dshow_stream.i_fourcc == VLC_FOURCC( 'R', 'G', 'B', '8' ) ||
971                 dshow_stream.i_fourcc == VLC_FOURCC( 'R', 'V', '1', '5' ) ||
972                 dshow_stream.i_fourcc == VLC_FOURCC( 'R', 'V', '1', '6' ) ||
973                 dshow_stream.i_fourcc == VLC_FOURCC( 'R', 'V', '2', '4' ) ||
974                 dshow_stream.i_fourcc == VLC_FOURCC( 'R', 'V', '3', '2' ) ||
975                 dshow_stream.i_fourcc == VLC_FOURCC( 'R', 'G', 'B', 'A' ) )
976             {
977                 if( i_height > 0 ) dshow_stream.b_invert = VLC_TRUE;
978                 else i_height = - i_height;
979             }
980
981             /* Check if we are dealing with a DV stream */
982             if( dshow_stream.i_fourcc == VLC_FOURCC( 'd', 'v', 's', 'l' ) ||
983                 dshow_stream.i_fourcc == VLC_FOURCC( 'd', 'v', 's', 'd' ) ||
984                 dshow_stream.i_fourcc == VLC_FOURCC( 'd', 'v', 'h', 'd' ) )
985             {
986                 p_input->pf_read = ReadCompressed;
987                 if( !p_input->psz_demux || !*p_input->psz_demux )
988                 {
989                     p_input->psz_demux = "rawdv";
990                 }
991                 p_sys->b_audio = VLC_FALSE;
992             }
993
994             /* Check if we are dealing with an MPEG video stream */
995             if( dshow_stream.i_fourcc == VLC_FOURCC( 'm', 'p', '2', 'v' ) )
996             {
997                 p_input->pf_read = ReadCompressed;
998                 if( !p_input->psz_demux || !*p_input->psz_demux )
999                 {
1000                     p_input->psz_demux = "mpgv";
1001                 }
1002                 p_sys->b_audio = VLC_FALSE;
1003             }
1004
1005             /* Add video stream to header */
1006             p_sys->i_header_size += 20;
1007             p_sys->p_header = (uint8_t *)realloc( p_sys->p_header,
1008                                                   p_sys->i_header_size );
1009             memcpy(  &p_sys->p_header[p_sys->i_header_pos], "vids", 4 );
1010             memcpy(  &p_sys->p_header[p_sys->i_header_pos + 4],
1011                      &dshow_stream.i_fourcc, 4 );
1012             SetDWBE( &p_sys->p_header[p_sys->i_header_pos + 8],
1013                      dshow_stream.header.video.bmiHeader.biWidth );
1014             SetDWBE( &p_sys->p_header[p_sys->i_header_pos + 12], i_height );
1015             SetDWBE( &p_sys->p_header[p_sys->i_header_pos + 16], 0 );
1016             p_sys->i_header_pos = p_sys->i_header_size;
1017
1018             /* Greatly simplifies the reading routine */
1019             int i_mtu = dshow_stream.header.video.bmiHeader.biWidth *
1020                 i_height * 4;
1021             p_input->i_mtu = __MAX( p_input->i_mtu, (unsigned int)i_mtu );
1022         }
1023
1024         else if( dshow_stream.mt.majortype == MEDIATYPE_Audio &&
1025                  dshow_stream.mt.formattype == FORMAT_WaveFormatEx )
1026         {
1027             msg_Dbg( p_input, "MEDIATYPE_Audio");
1028
1029             if( dshow_stream.mt.subtype == MEDIASUBTYPE_PCM )
1030                 dshow_stream.i_fourcc = VLC_FOURCC( 'a', 'r', 'a', 'w' );
1031             else if( dshow_stream.mt.subtype == MEDIASUBTYPE_IEEE_FLOAT )
1032                 dshow_stream.i_fourcc = VLC_FOURCC( 'f', 'l', '3', '2' );
1033             else goto fail;
1034
1035             dshow_stream.header.audio =
1036                 *(WAVEFORMATEX *)dshow_stream.mt.pbFormat;
1037
1038             /* Add audio stream to header */
1039             p_sys->i_header_size += 20;
1040             p_sys->p_header = (uint8_t *)realloc( p_sys->p_header,
1041                                                   p_sys->i_header_size );
1042             memcpy(  &p_sys->p_header[p_sys->i_header_pos], "auds", 4 );
1043             memcpy(  &p_sys->p_header[p_sys->i_header_pos + 4],
1044                      &dshow_stream.i_fourcc, 4 );
1045             SetDWBE( &p_sys->p_header[p_sys->i_header_pos + 8],
1046                      dshow_stream.header.audio.nChannels );
1047             SetDWBE( &p_sys->p_header[p_sys->i_header_pos + 12],
1048                      dshow_stream.header.audio.nSamplesPerSec );
1049             SetDWBE( &p_sys->p_header[p_sys->i_header_pos + 16],
1050                      dshow_stream.header.audio.wBitsPerSample );
1051             p_sys->i_header_pos = p_sys->i_header_size;
1052
1053             /* Greatly simplifies the reading routine */
1054             IAMBufferNegotiation *p_ambuf;
1055             IPin *p_pin;
1056             int i_mtu;
1057
1058             p_capture_filter->CustomGetPin()->ConnectedTo( &p_pin );
1059             if( SUCCEEDED( p_pin->QueryInterface(
1060                   IID_IAMBufferNegotiation, (void **)&p_ambuf ) ) )
1061             {
1062                 ALLOCATOR_PROPERTIES AllocProp;
1063                 memset( &AllocProp, 0, sizeof( ALLOCATOR_PROPERTIES ) );
1064                 p_ambuf->GetAllocatorProperties( &AllocProp );
1065                 p_ambuf->Release();
1066                 i_mtu = AllocProp.cbBuffer;
1067             }
1068             else
1069             {
1070                 /* Worst case */
1071                 i_mtu = dshow_stream.header.audio.nSamplesPerSec *
1072                         dshow_stream.header.audio.nChannels *
1073                         dshow_stream.header.audio.wBitsPerSample / 8;
1074             }
1075             p_pin->Release();
1076             p_input->i_mtu = __MAX( p_input->i_mtu, (unsigned int)i_mtu );
1077         }
1078
1079         else if( dshow_stream.mt.majortype == MEDIATYPE_Stream )
1080         {
1081             msg_Dbg( p_input, "MEDIATYPE_Stream" );
1082
1083             if( dshow_stream.mt.subtype == MEDIASUBTYPE_MPEG2_PROGRAM )
1084                 dshow_stream.i_fourcc = VLC_FOURCC( 'm', 'p', '2', 'p' );
1085             else if( dshow_stream.mt.subtype == MEDIASUBTYPE_MPEG2_TRANSPORT )
1086                 dshow_stream.i_fourcc = VLC_FOURCC( 'm', 'p', '2', 't' );
1087
1088             msg_Dbg( p_input, "selected stream pin accepts format: %4.4s",
1089                      (char *)&dshow_stream.i_fourcc);
1090
1091             p_sys->b_audio = VLC_FALSE;
1092             p_sys->i_header_size = 0;
1093             p_sys->i_header_pos = 0;
1094             p_input->i_mtu = INPUT_DEFAULT_BUFSIZE;
1095
1096             p_input->pf_read = ReadCompressed;
1097             p_input->pf_set_program = input_SetProgram;
1098         }
1099
1100         else
1101         {
1102             msg_Dbg( p_input, "unknown stream majortype" );
1103             goto fail;
1104         }
1105
1106         /* Add directshow elementary stream to our list */
1107         dshow_stream.p_device_filter = p_device_filter;
1108         dshow_stream.p_capture_filter = p_capture_filter;
1109
1110         p_sys->pp_streams =
1111             (dshow_stream_t **)realloc( p_sys->pp_streams,
1112                                         sizeof(dshow_stream_t *)
1113                                         * (p_sys->i_streams + 1) );
1114         p_sys->pp_streams[p_sys->i_streams] = new dshow_stream_t;
1115         *p_sys->pp_streams[p_sys->i_streams++] = dshow_stream;
1116         SetDWBE( &p_sys->p_header[4], (uint32_t)p_sys->i_streams );
1117
1118         return VLC_SUCCESS;
1119     }
1120
1121  fail:
1122     /* Remove filters from graph */
1123     p_sys->p_graph->RemoveFilter( p_device_filter );
1124     p_sys->p_graph->RemoveFilter( p_capture_filter );
1125
1126     /* Release objects */
1127     p_device_filter->Release();
1128     p_capture_filter->Release();
1129
1130     return VLC_EGENERIC;
1131 }
1132
1133 static IBaseFilter *
1134 FindCaptureDevice( vlc_object_t *p_this, string *p_devicename,
1135                    list<string> *p_listdevices, vlc_bool_t b_audio )
1136 {
1137     IBaseFilter *p_base_filter = NULL;
1138     IMoniker *p_moniker = NULL;
1139     ULONG i_fetched;
1140     HRESULT hr;
1141
1142     /* Create the system device enumerator */
1143     ICreateDevEnum *p_dev_enum = NULL;
1144
1145     hr = CoCreateInstance( CLSID_SystemDeviceEnum, NULL, CLSCTX_INPROC,
1146                            IID_ICreateDevEnum, (void **)&p_dev_enum );
1147     if( FAILED(hr) )
1148     {
1149         msg_Err( p_this, "failed to create the device enumerator (0x%x)", hr);
1150         return NULL;
1151     }
1152
1153     /* Create an enumerator for the video capture devices */
1154     IEnumMoniker *p_class_enum = NULL;
1155     if( !b_audio )
1156         hr = p_dev_enum->CreateClassEnumerator( CLSID_VideoInputDeviceCategory,
1157                                                 &p_class_enum, 0 );
1158     else
1159         hr = p_dev_enum->CreateClassEnumerator( CLSID_AudioInputDeviceCategory,
1160                                                 &p_class_enum, 0 );
1161     p_dev_enum->Release();
1162     if( FAILED(hr) )
1163     {
1164         msg_Err( p_this, "failed to create the class enumerator (0x%x)", hr );
1165         return NULL;
1166     }
1167
1168     /* If there are no enumerators for the requested type, then
1169      * CreateClassEnumerator will succeed, but p_class_enum will be NULL */
1170     if( p_class_enum == NULL )
1171     {
1172         msg_Err( p_this, "no capture device was detected" );
1173         return NULL;
1174     }
1175
1176     /* Enumerate the devices */
1177
1178     /* Note that if the Next() call succeeds but there are no monikers,
1179      * it will return S_FALSE (which is not a failure). Therefore, we check
1180      * that the return code is S_OK instead of using SUCCEEDED() macro. */
1181
1182     while( p_class_enum->Next( 1, &p_moniker, &i_fetched ) == S_OK )
1183     {
1184         /* Getting the property page to get the device name */
1185         IPropertyBag *p_bag;
1186         hr = p_moniker->BindToStorage( 0, 0, IID_IPropertyBag,
1187                                        (void **)&p_bag );
1188         if( SUCCEEDED(hr) )
1189         {
1190             VARIANT var;
1191             var.vt = VT_BSTR;
1192             hr = p_bag->Read( L"FriendlyName", &var, NULL );
1193             p_bag->Release();
1194             if( SUCCEEDED(hr) )
1195             {
1196                 int i_convert = ( lstrlenW( var.bstrVal ) + 1 ) * 2;
1197                 char *p_buf = (char *)alloca( i_convert ); p_buf[0] = 0;
1198                 WideCharToMultiByte( CP_ACP, 0, var.bstrVal, -1, p_buf,
1199                                      i_convert, NULL, NULL );
1200                 SysFreeString(var.bstrVal);
1201
1202                 if( p_listdevices ) p_listdevices->push_back( p_buf );
1203
1204                 if( p_devicename && *p_devicename == string(p_buf) )
1205                 {
1206                     /* Bind Moniker to a filter object */
1207                     hr = p_moniker->BindToObject( 0, 0, IID_IBaseFilter,
1208                                                   (void **)&p_base_filter );
1209                     if( FAILED(hr) )
1210                     {
1211                         msg_Err( p_this, "couldn't bind moniker to filter "
1212                                  "object (0x%x)", hr );
1213                         p_moniker->Release();
1214                         p_class_enum->Release();
1215                         return NULL;
1216                     }
1217                     p_moniker->Release();
1218                     p_class_enum->Release();
1219                     return p_base_filter;
1220                 }
1221             }
1222         }
1223
1224         p_moniker->Release();
1225     }
1226
1227     p_class_enum->Release();
1228     return NULL;
1229 }
1230
1231 static AM_MEDIA_TYPE EnumDeviceCaps( vlc_object_t *p_this,
1232                                      IBaseFilter *p_filter,
1233                                      int i_fourcc, int i_width, int i_height,
1234                                      int i_channels, int i_samplespersec,
1235                                      int i_bitspersample )
1236 {
1237     IEnumPins *p_enumpins;
1238     IPin *p_output_pin;
1239     IEnumMediaTypes *p_enummt;
1240     int i_orig_fourcc = i_fourcc;
1241     vlc_bool_t b_found = VLC_FALSE;
1242
1243     AM_MEDIA_TYPE media_type;
1244     media_type.majortype = GUID_NULL;
1245     media_type.subtype = GUID_NULL;
1246     media_type.formattype = GUID_NULL;
1247     media_type.pUnk = NULL;
1248     media_type.cbFormat = 0;
1249     media_type.pbFormat = NULL;
1250
1251     if( S_OK != p_filter->EnumPins( &p_enumpins ) ) return media_type;
1252
1253     while( S_OK == p_enumpins->Next( 1, &p_output_pin, NULL ) )
1254     {
1255         PIN_INFO info;
1256
1257         if( S_OK == p_output_pin->QueryPinInfo( &info ) )
1258         {
1259             msg_Dbg( p_this, "EnumDeviceCaps: %s pin: %S",
1260                      info.dir == PINDIR_INPUT ? "input" : "output",
1261                      info.achName );
1262             if( info.pFilter ) info.pFilter->Release();
1263         }
1264
1265         p_output_pin->Release();
1266     }
1267     p_enumpins->Reset();
1268
1269     while( !b_found && p_enumpins->Next( 1, &p_output_pin, NULL ) == S_OK )
1270     {
1271         PIN_INFO info;
1272
1273         if( S_OK == p_output_pin->QueryPinInfo( &info ) )
1274         {
1275             if( info.pFilter ) info.pFilter->Release();
1276             if( info.dir == PINDIR_INPUT )
1277             {
1278                 p_output_pin->Release();
1279                 continue;
1280             }
1281             msg_Dbg( p_this, "EnumDeviceCaps: trying pin %S", info.achName );
1282         }
1283
1284         /* Probe pin */
1285         if( SUCCEEDED( p_output_pin->EnumMediaTypes( &p_enummt ) ) )
1286         {
1287             AM_MEDIA_TYPE *p_mt;
1288             while( p_enummt->Next( 1, &p_mt, NULL ) == S_OK )
1289             {
1290
1291                 if( p_mt->majortype == MEDIATYPE_Video )
1292                 {
1293                     int i_current_fourcc = VLC_FOURCC(' ', ' ', ' ', ' ');
1294
1295                     /* Packed RGB formats */
1296                     if( p_mt->subtype == MEDIASUBTYPE_RGB1 )
1297                         i_current_fourcc = VLC_FOURCC( 'R', 'G', 'B', '1' );
1298                     if( p_mt->subtype == MEDIASUBTYPE_RGB4 )
1299                         i_current_fourcc = VLC_FOURCC( 'R', 'G', 'B', '4' );
1300                     if( p_mt->subtype == MEDIASUBTYPE_RGB8 )
1301                         i_current_fourcc = VLC_FOURCC( 'R', 'G', 'B', '8' );
1302                     else if( p_mt->subtype == MEDIASUBTYPE_RGB555 )
1303                         i_current_fourcc = VLC_FOURCC( 'R', 'V', '1', '5' );
1304                     else if( p_mt->subtype == MEDIASUBTYPE_RGB565 )
1305                         i_current_fourcc = VLC_FOURCC( 'R', 'V', '1', '6' );
1306                     else if( p_mt->subtype == MEDIASUBTYPE_RGB24 )
1307                         i_current_fourcc = VLC_FOURCC( 'R', 'V', '2', '4' );
1308                     else if( p_mt->subtype == MEDIASUBTYPE_RGB32 )
1309                         i_current_fourcc = VLC_FOURCC( 'R', 'V', '3', '2' );
1310                     else if( p_mt->subtype == MEDIASUBTYPE_ARGB32 )
1311                         i_current_fourcc = VLC_FOURCC( 'R', 'G', 'B', 'A' );
1312
1313                     /* Packed YUV formats */
1314                     else if(  p_mt->subtype == MEDIASUBTYPE_YVYU )
1315                         i_current_fourcc = VLC_FOURCC( 'Y', 'V', 'Y', 'U' );
1316                     else if(  p_mt->subtype == MEDIASUBTYPE_YUYV )
1317                         i_current_fourcc = VLC_FOURCC( 'Y', 'U', 'Y', 'V' );
1318                     else if(  p_mt->subtype == MEDIASUBTYPE_Y411 )
1319                         i_current_fourcc = VLC_FOURCC( 'I', '4', '1', 'N' );
1320                     else if(  p_mt->subtype == MEDIASUBTYPE_Y211 )
1321                         i_current_fourcc = VLC_FOURCC( 'Y', '2', '1', '1' );
1322                     else if(  p_mt->subtype == MEDIASUBTYPE_YUY2 ||
1323                               p_mt->subtype == MEDIASUBTYPE_UYVY )
1324                         i_current_fourcc = VLC_FOURCC( 'Y', 'U', 'Y', '2' );
1325
1326                     /* MPEG2 video elementary stream */
1327                     else if( p_mt->subtype == MEDIASUBTYPE_MPEG2_VIDEO )
1328                         i_current_fourcc = VLC_FOURCC( 'm', 'p', '2', 'v' );
1329
1330                     /* hauppauge pvr video preview */
1331                     else if( p_mt->subtype == MEDIASUBTYPE_PREVIEW_VIDEO )
1332                         i_current_fourcc = VLC_FOURCC( 'P', 'V', 'R', 'V' );
1333
1334                     else i_current_fourcc = *((int *)&p_mt->subtype);
1335
1336                     int i_current_width = p_mt->pbFormat ?
1337                         ((VIDEOINFOHEADER *)p_mt->pbFormat)->bmiHeader.biWidth : 0;
1338                     int i_current_height = p_mt->pbFormat ?
1339                         ((VIDEOINFOHEADER *)p_mt->pbFormat)->bmiHeader.biHeight : 0;
1340                     if( i_current_height < 0 )
1341                         i_current_height = -i_current_height; 
1342
1343                     msg_Dbg( p_this, "EnumDeviceCaps: input pin "
1344                              "accepts chroma: %4.4s, width:%i, height:%i",
1345                              (char *)&i_current_fourcc, i_current_width,
1346                              i_current_height );
1347
1348                     if( ( !i_fourcc || i_fourcc == i_current_fourcc ||
1349                           ( !i_orig_fourcc && i_current_fourcc ==
1350                             VLC_FOURCC('I','4','2','0') ) ) &&
1351                         ( !i_width || i_width == i_current_width ) &&
1352                         ( !i_height || i_height == i_current_height ) )
1353                     {
1354                         /* Pick the 1st match */
1355                         media_type = *p_mt;
1356                         i_fourcc = i_current_fourcc;
1357                         i_width = i_current_width;
1358                         i_height = i_current_height;
1359                         b_found = VLC_TRUE;
1360                     }
1361                     else
1362                     {
1363                         FreeMediaType( *p_mt );
1364                     }
1365                 }
1366                 else if( p_mt->majortype == MEDIATYPE_Audio )
1367                 {
1368                     int i_current_fourcc;
1369                     int i_current_channels =
1370                         ((WAVEFORMATEX *)p_mt->pbFormat)->nChannels;
1371                     int i_current_samplespersec =
1372                         ((WAVEFORMATEX *)p_mt->pbFormat)->nSamplesPerSec;
1373                     int i_current_bitspersample =
1374                         ((WAVEFORMATEX *)p_mt->pbFormat)->wBitsPerSample;
1375
1376                     if( p_mt->subtype == MEDIASUBTYPE_PCM )
1377                         i_current_fourcc = VLC_FOURCC( 'p', 'c', 'm', ' ' );
1378                     else i_current_fourcc = *((int *)&p_mt->subtype);
1379
1380                     msg_Dbg( p_this, "EnumDeviceCaps: input pin "
1381                              "accepts format: %4.4s, channels:%i, "
1382                              "samples/sec:%i bits/sample:%i",
1383                              (char *)&i_current_fourcc, i_current_channels,
1384                              i_current_samplespersec, i_current_bitspersample);
1385
1386                     if( (!i_channels || i_channels == i_current_channels) &&
1387                         (!i_samplespersec ||
1388                          i_samplespersec == i_current_samplespersec) &&
1389                         (!i_bitspersample ||
1390                          i_bitspersample == i_current_bitspersample) )
1391                     {
1392                         /* Pick the 1st match */
1393                         media_type = *p_mt;
1394                         i_channels = i_current_channels;
1395                         i_samplespersec = i_current_samplespersec;
1396                         i_bitspersample = i_current_bitspersample;
1397                         b_found = VLC_TRUE;
1398
1399                         /* Setup a few properties like the audio latency */
1400                         IAMBufferNegotiation *p_ambuf;
1401
1402                         if( SUCCEEDED( p_output_pin->QueryInterface(
1403                               IID_IAMBufferNegotiation, (void **)&p_ambuf ) ) )
1404                         {
1405                             ALLOCATOR_PROPERTIES AllocProp;
1406                             AllocProp.cbAlign = -1;
1407                             AllocProp.cbBuffer = i_channels * i_samplespersec *
1408                               i_bitspersample / 8 / 10 ; /*100 ms of latency*/
1409                             AllocProp.cbPrefix = -1;
1410                             AllocProp.cBuffers = -1;
1411                             p_ambuf->SuggestAllocatorProperties( &AllocProp );
1412                             p_ambuf->Release();
1413                         }
1414                     }
1415                     else
1416                     {
1417                         FreeMediaType( *p_mt );
1418                     }
1419                 }
1420                 else if( p_mt->majortype == MEDIATYPE_Stream )
1421                 {
1422                     msg_Dbg( p_this, "EnumDeviceCaps: MEDIATYPE_Stream" );
1423
1424                     int i_current_fourcc = VLC_FOURCC(' ', ' ', ' ', ' ');
1425
1426                     if( p_mt->subtype == MEDIASUBTYPE_MPEG2_PROGRAM )
1427                         i_current_fourcc = VLC_FOURCC( 'm', 'p', '2', 'p' );
1428                     else if( p_mt->subtype == MEDIASUBTYPE_MPEG2_TRANSPORT )
1429                         i_current_fourcc = VLC_FOURCC( 'm', 'p', '2', 't' );
1430
1431                     if( ( !i_fourcc || i_fourcc == i_current_fourcc ) )
1432                     {
1433                         /* Pick the 1st match */
1434                         media_type = *p_mt;
1435                         i_fourcc = i_current_fourcc;
1436                         b_found = VLC_TRUE;
1437                     }
1438                     else
1439                     {
1440                         FreeMediaType( *p_mt );
1441                     }
1442                 }
1443                 else
1444                 {
1445                     msg_Dbg( p_this,
1446                              "EnumDeviceCaps: input pin: unknown format" );
1447                     FreeMediaType( *p_mt );
1448                 }
1449
1450                 CoTaskMemFree( (PVOID)p_mt );
1451             }
1452             p_enummt->Release();
1453         }
1454
1455         p_output_pin->Release();
1456     }
1457
1458     p_enumpins->Release();
1459     return media_type;
1460 }
1461
1462 /*****************************************************************************
1463  * Read: reads from the device into PES packets.
1464  *****************************************************************************
1465  * Returns -1 in case of error, 0 in case of EOF, otherwise the number of
1466  * bytes.
1467  *****************************************************************************/
1468 static ssize_t Read( input_thread_t * p_input, byte_t * p_buffer,
1469                      size_t i_len )
1470 {
1471     access_sys_t   *p_sys = p_input->p_access_data;
1472     dshow_stream_t *p_stream = NULL;
1473     byte_t         *p_buf_orig = p_buffer;
1474     VLCMediaSample  sample;
1475     int             i_data_size;
1476     uint8_t         *p_data;
1477
1478     if( p_sys->i_header_pos )
1479     {
1480         /* First header of the stream */
1481         memcpy( p_buffer, p_sys->p_header, p_sys->i_header_size );
1482         p_buffer += p_sys->i_header_size;
1483         p_sys->i_header_pos = 0;
1484     }
1485
1486     while( 1 )
1487     {
1488         /* Get new sample/frame from next elementary stream.
1489          * We first loop through all the elementary streams and if all our
1490          * fifos are empty we block until we are signaled some new data has
1491          * arrived. */
1492         vlc_mutex_lock( &p_sys->lock );
1493
1494         int i_stream;
1495         for( i_stream = 0; i_stream < p_sys->i_streams; i_stream++ )
1496         {
1497             p_stream = p_sys->pp_streams[i_stream];
1498             if( p_stream->mt.majortype == MEDIATYPE_Audio &&
1499                 p_stream->p_capture_filter &&
1500                 p_stream->p_capture_filter->CustomGetPin()
1501                   ->CustomGetSample( &sample ) == S_OK )
1502             {
1503                 break;
1504             }
1505         }
1506         if( i_stream == p_sys->i_streams )
1507         for( i_stream = 0; i_stream < p_sys->i_streams; i_stream++ )
1508         {
1509             p_stream = p_sys->pp_streams[i_stream];
1510             if( p_stream->p_capture_filter &&
1511                 p_stream->p_capture_filter->CustomGetPin()
1512                   ->CustomGetSample( &sample ) == S_OK )
1513             {
1514                 break;
1515             }
1516         }
1517         if( i_stream == p_sys->i_streams )
1518         {
1519             /* No data available. Wait until some data has arrived */
1520             vlc_cond_wait( &p_sys->wait, &p_sys->lock );
1521             vlc_mutex_unlock( &p_sys->lock );
1522             continue;
1523         }
1524
1525         vlc_mutex_unlock( &p_sys->lock );
1526
1527         /*
1528          * We got our sample
1529          */
1530         i_data_size = sample.p_sample->GetActualDataLength();
1531         sample.p_sample->GetPointer( &p_data );
1532
1533         REFERENCE_TIME i_pts, i_end_date;
1534         HRESULT hr = sample.p_sample->GetTime( &i_pts, &i_end_date );
1535         if( hr != VFW_S_NO_STOP_TIME && hr != S_OK ) i_pts = 0;
1536
1537         if( !i_pts )
1538         {
1539             if( p_stream->mt.majortype == MEDIATYPE_Video || !p_stream->b_pts )
1540             {
1541                 /* Use our data timestamp */
1542                 i_pts = sample.i_timestamp;
1543                 p_stream->b_pts = VLC_TRUE;
1544             }
1545         }
1546
1547 #if 0
1548         msg_Dbg( p_input, "Read() stream: %i PTS: "I64Fd, i_stream, i_pts );
1549 #endif
1550
1551         /* Create pseudo header */
1552         SetDWBE( &p_sys->p_header[0], i_stream );
1553         SetDWBE( &p_sys->p_header[4], i_data_size );
1554         SetQWBE( &p_sys->p_header[8], i_pts  * 9 / 1000 );
1555
1556 #if 0
1557         msg_Info( p_input, "access read %i data_size %i", i_len, i_data_size );
1558 #endif
1559
1560         /* First copy header */
1561         memcpy( p_buffer, p_sys->p_header, 16 /* header size */ );
1562         p_buffer += 16 /* header size */;
1563
1564         /* Then copy stream data if any */
1565         if( !p_stream->b_invert )
1566         {
1567             p_input->p_vlc->pf_memcpy( p_buffer, p_data, i_data_size );
1568             p_buffer += i_data_size;
1569         }
1570         else
1571         {
1572             int i_width = p_stream->header.video.bmiHeader.biWidth;
1573             int i_height = p_stream->header.video.bmiHeader.biHeight;
1574             if( i_height < 0 ) i_height = - i_height;
1575
1576             switch( p_stream->i_fourcc )
1577             {
1578             case VLC_FOURCC( 'R', 'V', '1', '5' ):
1579             case VLC_FOURCC( 'R', 'V', '1', '6' ):
1580                 i_width *= 2;
1581                 break;
1582             case VLC_FOURCC( 'R', 'V', '2', '4' ):
1583                 i_width *= 3;
1584                 break;
1585             case VLC_FOURCC( 'R', 'V', '3', '2' ):
1586             case VLC_FOURCC( 'R', 'G', 'B', 'A' ):
1587                 i_width *= 4;
1588                 break;
1589             }
1590
1591             for( int i = i_height - 1; i >= 0; i-- )
1592             {
1593                 p_input->p_vlc->pf_memcpy( p_buffer,
1594                      &p_data[i * i_width], i_width );
1595
1596                 p_buffer += i_width;
1597             }
1598         }
1599
1600         sample.p_sample->Release();
1601
1602         /* The caller got what he wanted */
1603         return p_buffer - p_buf_orig;
1604     }
1605
1606     return 0; /* never reached */
1607 }
1608
1609 /*****************************************************************************
1610  * ReadCompressed: reads compressed (MPEG/DV) data from the device.
1611  *****************************************************************************
1612  * Returns -1 in case of error, 0 in case of EOF, otherwise the number of
1613  * bytes.
1614  *****************************************************************************/
1615 static ssize_t ReadCompressed( input_thread_t * p_input, byte_t * p_buffer,
1616                                size_t i_len )
1617 {
1618     access_sys_t   *p_sys = p_input->p_access_data;
1619     dshow_stream_t *p_stream = NULL;
1620     VLCMediaSample  sample;
1621     int             i_data_size;
1622     uint8_t         *p_data;
1623
1624     /* Read 1 DV/MPEG frame (they contain the video and audio data) */
1625
1626     /* There must be only 1 elementary stream to produce a valid stream
1627      * of MPEG or DV data */
1628     p_stream = p_sys->pp_streams[0];
1629
1630     while( 1 )
1631     {
1632         if( p_input->b_die || p_input->b_error ) return 0;
1633
1634         /* Get new sample/frame from the elementary stream (blocking). */
1635         vlc_mutex_lock( &p_sys->lock );
1636
1637         if( p_stream->p_capture_filter->CustomGetPin()
1638               ->CustomGetSample( &sample ) != S_OK )
1639         {
1640             /* No data available. Wait until some data has arrived */
1641             vlc_cond_wait( &p_sys->wait, &p_sys->lock );
1642             vlc_mutex_unlock( &p_sys->lock );
1643             continue;
1644         }
1645
1646         vlc_mutex_unlock( &p_sys->lock );
1647
1648         /*
1649          * We got our sample
1650          */
1651         i_data_size = sample.p_sample->GetActualDataLength();
1652         sample.p_sample->GetPointer( &p_data );
1653
1654 #if 0
1655         msg_Info( p_input, "access read %i data_size %i", i_len, i_data_size );
1656 #endif
1657         i_data_size = __MIN( i_data_size, (int)i_len );
1658
1659         p_input->p_vlc->pf_memcpy( p_buffer, p_data, i_data_size );
1660
1661         sample.p_sample->Release();
1662
1663         /* The caller got what he wanted */
1664         return i_data_size;
1665     }
1666
1667     return 0; /* never reached */
1668 }
1669
1670 /*****************************************************************************
1671  * Demux: local prototypes
1672  *****************************************************************************/
1673 struct demux_sys_t
1674 {
1675     int         i_es;
1676     es_out_id_t **es;
1677 };
1678
1679 static int  Demux      ( input_thread_t * );
1680
1681 /****************************************************************************
1682  * DemuxOpen:
1683  ****************************************************************************/
1684 static int DemuxOpen( vlc_object_t *p_this )
1685 {
1686     input_thread_t *p_input = (input_thread_t *)p_this;
1687     demux_sys_t    *p_sys;
1688
1689     uint8_t        *p_peek;
1690     int            i_es;
1691     int            i;
1692
1693     /* a little test to see if it's a dshow stream */
1694     if( stream_Peek( p_input->s, &p_peek, 8 ) < 8 )
1695     {
1696         msg_Warn( p_input, "dshow plugin discarded (cannot peek)" );
1697         return VLC_EGENERIC;
1698     }
1699
1700     if( memcmp( p_peek, ".dsh", 4 ) ||
1701         ( i_es = GetDWBE( &p_peek[4] ) ) <= 0 )
1702     {
1703         msg_Warn( p_input, "dshow plugin discarded (not a valid stream)" );
1704         return VLC_EGENERIC;
1705     }
1706
1707     vlc_mutex_lock( &p_input->stream.stream_lock );
1708     if( input_InitStream( p_input, 0 ) == -1)
1709     {
1710         vlc_mutex_unlock( &p_input->stream.stream_lock );
1711         msg_Err( p_input, "cannot init stream" );
1712         return VLC_EGENERIC;
1713     }
1714     p_input->stream.i_mux_rate =  0 / 50;
1715     vlc_mutex_unlock( &p_input->stream.stream_lock );
1716
1717     p_input->pf_demux = Demux;
1718     p_input->pf_demux_control = demux_vaControlDefault;
1719     p_input->p_demux_data = p_sys =
1720         (demux_sys_t *)malloc( sizeof( demux_sys_t ) );
1721     p_sys->i_es = 0;
1722     p_sys->es   = NULL;
1723
1724     if( stream_Peek( p_input->s, &p_peek, 8 + 20 * i_es ) < 8 + 20 * i_es )
1725     {
1726         msg_Err( p_input, "dshow plugin discarded (cannot peek)" );
1727         return VLC_EGENERIC;
1728     }
1729     p_peek += 8;
1730
1731     for( i = 0; i < i_es; i++ )
1732     {
1733         es_format_t fmt;
1734
1735         if( !memcmp( p_peek, "auds", 4 ) )
1736         {
1737             es_format_Init( &fmt, AUDIO_ES, VLC_FOURCC( p_peek[4], p_peek[5],
1738                                                         p_peek[6], p_peek[7] ) );
1739
1740             fmt.audio.i_channels = GetDWBE( &p_peek[8] );
1741             fmt.audio.i_rate = GetDWBE( &p_peek[12] );
1742             fmt.audio.i_bitspersample = GetDWBE( &p_peek[16] );
1743             fmt.audio.i_blockalign = fmt.audio.i_channels *
1744                                      fmt.audio.i_bitspersample / 8;
1745             fmt.i_bitrate = fmt.audio.i_channels *
1746                             fmt.audio.i_rate *
1747                             fmt.audio.i_bitspersample;
1748
1749             msg_Dbg( p_input, "new audio es %d channels %dHz",
1750                      fmt.audio.i_channels, fmt.audio.i_rate );
1751
1752             p_sys->es = (es_out_id_t **)realloc( p_sys->es,
1753                           sizeof(es_out_id_t *) * (p_sys->i_es + 1) );
1754             p_sys->es[p_sys->i_es++] = es_out_Add( p_input->p_es_out, &fmt );
1755         }
1756         else if( !memcmp( p_peek, "vids", 4 ) )
1757         {
1758             es_format_Init( &fmt, VIDEO_ES, VLC_FOURCC( p_peek[4], p_peek[5],
1759                                                         p_peek[6], p_peek[7] ) );
1760             fmt.video.i_width  = GetDWBE( &p_peek[8] );
1761             fmt.video.i_height = GetDWBE( &p_peek[12] );
1762
1763             msg_Dbg( p_input, "added new video es %4.4s %dx%d",
1764                      (char*)&fmt.i_codec,
1765                      fmt.video.i_width, fmt.video.i_height );
1766
1767             p_sys->es = (es_out_id_t **)realloc( p_sys->es,
1768                           sizeof(es_out_id_t *) * (p_sys->i_es + 1) );
1769             p_sys->es[p_sys->i_es++] = es_out_Add( p_input->p_es_out, &fmt );
1770         }
1771
1772         p_peek += 20;
1773     }
1774
1775     /* Skip header */
1776     stream_Read( p_input->s, NULL, 8 + 20 * i_es );
1777
1778     return VLC_SUCCESS;
1779 }
1780
1781 /****************************************************************************
1782  * DemuxClose:
1783  ****************************************************************************/
1784 static void DemuxClose( vlc_object_t *p_this )
1785 {
1786     input_thread_t *p_input = (input_thread_t *)p_this;
1787     demux_sys_t    *p_sys = p_input->p_demux_data;
1788
1789     if( p_sys->i_es > 0 )
1790     {
1791         free( p_sys->es );
1792     }
1793     free( p_sys );
1794 }
1795
1796 /****************************************************************************
1797  * Demux:
1798  ****************************************************************************/
1799 static int Demux( input_thread_t *p_input )
1800 {
1801     demux_sys_t *p_sys = p_input->p_demux_data;
1802     block_t     *p_block;
1803
1804     int i_es;
1805     int i_size;
1806
1807     uint8_t *p_peek;
1808     mtime_t i_pcr;
1809
1810     if( stream_Peek( p_input->s, &p_peek, 16 ) < 16 )
1811     {
1812         msg_Warn( p_input, "cannot peek (EOF ?)" );
1813         return 0;
1814     }
1815
1816     i_es   = GetDWBE( &p_peek[0] );
1817     if( i_es < 0 || i_es >= p_sys->i_es )
1818     {
1819         msg_Err( p_input, "cannot find ES" );
1820         return -1;
1821     }
1822
1823     i_size = GetDWBE( &p_peek[4] );
1824     i_pcr  = GetQWBE( &p_peek[8] );
1825
1826     if( ( p_block = stream_Block( p_input->s, 16 + i_size ) ) == NULL )
1827     {
1828         msg_Warn( p_input, "cannot read data" );
1829         return 0;
1830     }
1831
1832     p_block->p_buffer += 16;
1833     p_block->i_buffer -= 16;
1834
1835     /* Call the pace control. */
1836     input_ClockManageRef( p_input, p_input->stream.p_selected_program, i_pcr );
1837
1838     p_block->i_dts =
1839     p_block->i_pts = i_pcr <= 0 ? 0 :
1840         input_ClockGetTS( p_input, p_input->stream.p_selected_program, i_pcr );
1841
1842     es_out_Send( p_input->p_es_out, p_sys->es[i_es], p_block );
1843
1844     return 1;
1845 }
1846
1847
1848 /*****************************************************************************
1849  * config variable callback
1850  *****************************************************************************/
1851 static int FindDevicesCallback( vlc_object_t *p_this, char const *psz_name,
1852                                vlc_value_t newval, vlc_value_t oldval, void * )
1853 {
1854     module_config_t *p_item;
1855     vlc_bool_t b_audio = VLC_FALSE;
1856     int i;
1857
1858     p_item = config_FindConfig( p_this, psz_name );
1859     if( !p_item ) return VLC_SUCCESS;
1860
1861     if( !strcmp( psz_name, "dshow-adev" ) ) b_audio = VLC_TRUE;
1862
1863     /* Clear-up the current list */
1864     if( p_item->i_list )
1865     {
1866         /* Keep the 2 first entries */
1867         for( i = 2; i < p_item->i_list; i++ )
1868         {
1869             free( p_item->ppsz_list[i] );
1870             free( p_item->ppsz_list_text[i] );
1871         }
1872         /* TODO: Remove when no more needed */
1873         p_item->ppsz_list[i] = NULL;
1874         p_item->ppsz_list_text[i] = NULL;
1875     }
1876     p_item->i_list = 2;
1877
1878     /* Find list of devices */
1879     list<string> list_devices;
1880
1881     /* Initialize OLE/COM */
1882     CoInitialize( 0 );
1883
1884     FindCaptureDevice( p_this, NULL, &list_devices, b_audio );
1885
1886     /* Uninitialize OLE/COM */
1887     CoUninitialize();
1888
1889     if( !list_devices.size() ) return VLC_SUCCESS;
1890
1891     p_item->ppsz_list =
1892         (char **)realloc( p_item->ppsz_list,
1893                           (list_devices.size()+3) * sizeof(char *) );
1894     p_item->ppsz_list_text =
1895         (char **)realloc( p_item->ppsz_list_text,
1896                           (list_devices.size()+3) * sizeof(char *) );
1897
1898     list<string>::iterator iter;
1899     for( iter = list_devices.begin(), i = 2; iter != list_devices.end();
1900          iter++, i++ )
1901     {
1902         p_item->ppsz_list[i] = strdup( iter->c_str() );
1903         p_item->ppsz_list_text[i] = NULL;
1904         p_item->i_list++;
1905     }
1906     p_item->ppsz_list[i] = NULL;
1907     p_item->ppsz_list_text[i] = NULL;
1908
1909     /* Signal change to the interface */
1910     p_item->b_dirty = VLC_TRUE;
1911
1912     return VLC_SUCCESS;
1913 }
1914
1915 static int ConfigDevicesCallback( vlc_object_t *p_this, char const *psz_name,
1916                                vlc_value_t newval, vlc_value_t oldval, void * )
1917 {
1918     module_config_t *p_item;
1919     vlc_bool_t b_audio = VLC_FALSE;
1920
1921     /* Initialize OLE/COM */
1922     CoInitialize( 0 );
1923
1924     p_item = config_FindConfig( p_this, psz_name );
1925     if( !p_item ) return VLC_SUCCESS;
1926
1927     if( !strcmp( psz_name, "dshow-adev" ) ) b_audio = VLC_TRUE;
1928
1929     string devicename;
1930
1931     if( newval.psz_string && *newval.psz_string )
1932     {
1933         devicename = newval.psz_string;
1934     }
1935     else
1936     {
1937         /* If no device name was specified, pick the 1st one */
1938         list<string> list_devices;
1939
1940         /* Enumerate devices */
1941         FindCaptureDevice( p_this, NULL, &list_devices, b_audio );
1942         if( !list_devices.size() ) return VLC_EGENERIC;
1943         devicename = *list_devices.begin();
1944     }
1945
1946     IBaseFilter *p_device_filter =
1947         FindCaptureDevice( p_this, &devicename, NULL, b_audio );
1948     if( p_device_filter )
1949     {
1950         PropertiesPage( p_this, p_device_filter, NULL, b_audio );
1951     }
1952     else
1953     {
1954         /* Uninitialize OLE/COM */
1955         CoUninitialize();
1956
1957         msg_Err( p_this, "didn't find device: %s", devicename.c_str() );
1958         return VLC_EGENERIC;
1959     }
1960
1961     /* Uninitialize OLE/COM */
1962     CoUninitialize();
1963
1964     return VLC_SUCCESS;
1965 }
1966
1967 static void ShowPropertyPage( IUnknown *obj, CAUUID *cauuid )
1968 {
1969     if( cauuid->cElems > 0 )
1970     {
1971         HWND hwnd_desktop = ::GetDesktopWindow();
1972
1973         OleCreatePropertyFrame( hwnd_desktop, 30, 30, NULL, 1, &obj,
1974                                 cauuid->cElems, cauuid->pElems, 0, 0, NULL );
1975
1976         CoTaskMemFree( cauuid->pElems );
1977     }
1978 }
1979
1980 static void PropertiesPage( vlc_object_t *p_this, IBaseFilter *p_device_filter,
1981                             ICaptureGraphBuilder2 *p_capture_graph,
1982                             vlc_bool_t b_audio )
1983 {
1984     CAUUID cauuid;
1985
1986     msg_Dbg( p_this, "Configuring Device Properties" );
1987
1988     /*
1989      * Video or audio capture filter page
1990      */
1991     ISpecifyPropertyPages *p_spec;
1992
1993     HRESULT hr = p_device_filter->QueryInterface( IID_ISpecifyPropertyPages,
1994                                                   (void **)&p_spec );
1995     if( SUCCEEDED(hr) )
1996     {
1997         if( SUCCEEDED(p_spec->GetPages( &cauuid )) )
1998         {
1999             ShowPropertyPage( p_device_filter, &cauuid );
2000         }
2001         p_spec->Release();
2002     }
2003
2004     msg_Dbg( p_this, "looking for WDM Configuration Pages" );
2005
2006     if( p_capture_graph )
2007         msg_Dbg( p_this, "got capture graph for WDM Configuration Pages" );
2008
2009     /*
2010      * Audio capture pin
2011      */
2012     if( p_capture_graph && b_audio )
2013     {
2014         IAMStreamConfig *p_SC;
2015
2016         hr = p_capture_graph->FindInterface( &PIN_CATEGORY_CAPTURE,
2017                                              &MEDIATYPE_Audio, p_device_filter,
2018                                              IID_IAMStreamConfig,
2019                                              (void **)&p_SC );
2020         if( SUCCEEDED(hr) )
2021         {
2022             hr = p_SC->QueryInterface( IID_ISpecifyPropertyPages,
2023                                        (void **)&p_spec );
2024             if( SUCCEEDED(hr) )
2025             {
2026                 hr = p_spec->GetPages( &cauuid );
2027                 if( SUCCEEDED(hr) )
2028                 {
2029                     for( unsigned int c = 0; c < cauuid.cElems; c++ )
2030                     {
2031                         ShowPropertyPage( p_SC, &cauuid );
2032                     }
2033                     CoTaskMemFree( cauuid.pElems );
2034                 }
2035                 p_spec->Release();
2036             }
2037             p_SC->Release();
2038         }
2039
2040         /*
2041          * TV Audio filter
2042          */
2043         IAMTVAudio *p_TVA;
2044         hr = p_capture_graph->FindInterface( &PIN_CATEGORY_CAPTURE, 
2045                                              &MEDIATYPE_Audio, p_device_filter,
2046                                              IID_IAMTVAudio, (void **)&p_TVA );
2047         if( SUCCEEDED(hr) )
2048         {
2049             hr = p_TVA->QueryInterface( IID_ISpecifyPropertyPages,
2050                                         (void **)&p_spec );
2051             if( SUCCEEDED(hr) )
2052             {
2053                 if( SUCCEEDED( p_spec->GetPages( &cauuid ) ) )
2054                     ShowPropertyPage(p_TVA, &cauuid);
2055
2056                 p_spec->Release();
2057             }
2058             p_TVA->Release();
2059         }
2060     }
2061
2062     /*
2063      * Video capture pin
2064      */
2065     if( p_capture_graph && !b_audio )
2066     {
2067         IAMStreamConfig *p_SC;
2068
2069         hr = p_capture_graph->FindInterface( &PIN_CATEGORY_CAPTURE,
2070                                              &MEDIATYPE_Interleaved,
2071                                              p_device_filter,
2072                                              IID_IAMStreamConfig,
2073                                              (void **)&p_SC );
2074         if( FAILED(hr) )
2075         {
2076             hr = p_capture_graph->FindInterface( &PIN_CATEGORY_CAPTURE,
2077                                                  &MEDIATYPE_Video,
2078                                                  p_device_filter,
2079                                                  IID_IAMStreamConfig,
2080                                                  (void **)&p_SC );
2081         }
2082
2083         if( SUCCEEDED(hr) )
2084         {
2085             hr = p_SC->QueryInterface( IID_ISpecifyPropertyPages,
2086                                        (void **)&p_spec );
2087             if( SUCCEEDED(hr) )
2088             {
2089                 if( SUCCEEDED( p_spec->GetPages(&cauuid) ) )
2090                 {
2091                     ShowPropertyPage(p_SC, &cauuid);
2092                 }
2093                 p_spec->Release();
2094             }
2095             p_SC->Release();
2096         }
2097
2098         /*
2099          * Video crossbar, and a possible second crossbar
2100          */
2101         IAMCrossbar *p_X, *p_X2;
2102         IBaseFilter *p_XF;
2103
2104         hr = p_capture_graph->FindInterface( &PIN_CATEGORY_CAPTURE,
2105                                              &MEDIATYPE_Interleaved,
2106                                              p_device_filter,
2107                                              IID_IAMCrossbar, (void **)&p_X );
2108         if( FAILED(hr) )
2109         {
2110             hr = p_capture_graph->FindInterface( &PIN_CATEGORY_CAPTURE,
2111                                                  &MEDIATYPE_Video,
2112                                                  p_device_filter,
2113                                                  IID_IAMCrossbar,
2114                                                  (void **)&p_X );
2115         }
2116
2117         if( SUCCEEDED(hr) )
2118         {
2119             hr = p_X->QueryInterface( IID_IBaseFilter, (void **)&p_XF );
2120             if( SUCCEEDED(hr) )
2121             {
2122                 hr = p_X->QueryInterface( IID_ISpecifyPropertyPages,
2123                                           (void **)&p_spec );
2124                 if( SUCCEEDED(hr) )
2125                 {
2126                     hr = p_spec->GetPages(&cauuid);
2127                     if( hr == S_OK && cauuid.cElems > 0 )
2128                     {
2129                         ShowPropertyPage( p_X, &cauuid );
2130                     }
2131                     p_spec->Release();
2132                 }
2133
2134                 hr = p_capture_graph->FindInterface( &LOOK_UPSTREAM_ONLY, NULL,
2135                                                      p_XF, IID_IAMCrossbar,
2136                                                      (void **)&p_X2 );
2137                 if( SUCCEEDED(hr) )
2138                 {
2139                     hr = p_X2->QueryInterface( IID_ISpecifyPropertyPages,
2140                                                (void **)&p_spec );
2141                     if( SUCCEEDED(hr) )
2142                     {
2143                         hr = p_spec->GetPages( &cauuid );
2144                         if( SUCCEEDED(hr) )
2145                         {
2146                             ShowPropertyPage( p_X2, &cauuid );
2147                         }
2148                         p_spec->Release();
2149                     }
2150                     p_X2->Release();
2151                 }
2152
2153                 p_XF->Release();
2154             }
2155
2156             p_X->Release();
2157         }
2158
2159         /*
2160          * TV Tuner
2161          */
2162         IAMTVTuner *p_TV;
2163         hr = p_capture_graph->FindInterface( &PIN_CATEGORY_CAPTURE,
2164                                              &MEDIATYPE_Interleaved,
2165                                              p_device_filter,
2166                                              IID_IAMTVTuner, (void **)&p_TV );
2167         if( FAILED(hr) )
2168         {
2169             hr = p_capture_graph->FindInterface( &PIN_CATEGORY_CAPTURE,
2170                                                  &MEDIATYPE_Video,
2171                                                  p_device_filter,
2172                                                  IID_IAMTVTuner,
2173                                                  (void **)&p_TV );
2174         }
2175
2176         if( SUCCEEDED(hr) )
2177         {
2178             hr = p_TV->QueryInterface( IID_ISpecifyPropertyPages,
2179                                        (void **)&p_spec );
2180             if( SUCCEEDED(hr) )
2181             {
2182                 hr = p_spec->GetPages(&cauuid);
2183                 if( SUCCEEDED(hr) )
2184                 {
2185                     ShowPropertyPage(p_TV, &cauuid);
2186                 }
2187                 p_spec->Release();
2188             }
2189             p_TV->Release();
2190         }
2191     }
2192 }