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