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