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