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