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