access: dshow: set proper RGB masks
[vlc.git] / modules / access / dshow / dshow.cpp
1 /*****************************************************************************
2  * dshow.cpp : DirectShow access and access_demux module for vlc
3  *****************************************************************************
4  * Copyright (C) 2002-2004, 2006, 2008, 2010 the VideoLAN team
5  * $Id$
6  *
7  * Author: Gildas Bazin <gbazin@videolan.org>
8  *         Damien Fouilleul <damienf@videolan.org>
9  *
10  * This program is free software; you can redistribute it and/or modify
11  * it under the terms of the GNU General Public License as published by
12  * the Free Software Foundation; either version 2 of the License, or
13  * (at your option) any later version.
14  *
15  * This program is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18  * GNU General Public License for more details.
19  *
20  * You should have received a copy of the GNU General Public License
21  * along with this program; if not, write to the Free Software
22  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
23  *****************************************************************************/
24
25 /*****************************************************************************
26  * Preamble
27  *****************************************************************************/
28
29 #ifdef HAVE_CONFIG_H
30 # include "config.h"
31 #endif
32
33 #include <inttypes.h>
34 #include <list>
35 #include <string>
36 #include <assert.h>
37 #include <stdexcept>
38
39 #include <vlc_common.h>
40 #include <vlc_plugin.h>
41 #include <vlc_access.h>
42 #include <vlc_demux.h>
43
44 #include <vlc_dialog.h>      /* vlc_dialog_display_error */
45 #include <vlc_charset.h>     /* FromWide */
46
47 #include <initguid.h>
48 #include "vlc_dshow.h"
49
50 #include "access.h"
51 #include "filter.h"
52
53 #include "../src/win32/mta_holder.h"
54
55 namespace dshow {
56
57 /*****************************************************************************
58  * Access: local prototypes
59  *****************************************************************************/
60 static block_t *ReadCompressed( stream_t *, bool * );
61 static int AccessControl ( stream_t *, int, va_list );
62
63 static int Demux       ( demux_t * );
64 static int DemuxControl( demux_t *, int, va_list );
65
66 static int OpenDevice( vlc_object_t *, access_sys_t *, std::string, bool );
67 static ComPtr<IBaseFilter> FindCaptureDevice( vlc_object_t *, std::string *,
68                                        std::list<std::string> *, bool );
69 static size_t EnumDeviceCaps( vlc_object_t *, IBaseFilter *,
70                               int, int, int, int, int, int,
71                               AM_MEDIA_TYPE *mt, size_t, bool );
72 static bool ConnectFilters( vlc_object_t *, access_sys_t *,
73                             IBaseFilter *, CaptureFilter * );
74 static int FindDevices( const char *, char ***, char *** );
75
76 static void ShowPropertyPage( IUnknown * );
77 static void ShowDeviceProperties( vlc_object_t *, ICaptureGraphBuilder2 *,
78                                   IBaseFilter *, bool );
79 static void ShowTunerProperties( vlc_object_t *, ICaptureGraphBuilder2 *,
80                                  IBaseFilter *, bool );
81 static void ConfigTuner( vlc_object_t *, ICaptureGraphBuilder2 *,
82                          IBaseFilter * );
83
84 /*****************************************************************************
85  * Module descriptor
86  *****************************************************************************/
87 static const int pi_tuner_input[] = { 0, 1, 2 };
88 static const char *const ppsz_tuner_input_text[] =
89     {N_("Default"), N_("Cable"), N_("Antenna")};
90
91 static const int pi_amtuner_mode[]  = { AMTUNER_MODE_DEFAULT,
92                                         AMTUNER_MODE_TV,
93                                         AMTUNER_MODE_FM_RADIO,
94                                         AMTUNER_MODE_AM_RADIO,
95                                         AMTUNER_MODE_DSS };
96 static const char *const ppsz_amtuner_mode_text[] = { N_("Default"),
97                                           N_("TV"),
98                                           N_("FM radio"),
99                                           N_("AM radio"),
100                                           N_("DSS") };
101
102 #define VDEV_TEXT N_("Video device name")
103 #define VDEV_LONGTEXT N_( \
104     "Name of the video device that will be used by the " \
105     "DirectShow plugin. If you don't specify anything, the default device " \
106     "will be used.")
107 #define ADEV_TEXT N_("Audio device name")
108 #define ADEV_LONGTEXT N_( \
109     "Name of the audio device that will be used by the " \
110     "DirectShow plugin. If you don't specify anything, the default device " \
111     "will be used.")
112 #define SIZE_TEXT N_("Video size")
113 #define SIZE_LONGTEXT N_( \
114     "Size of the video that will be displayed by the " \
115     "DirectShow plugin. If you don't specify anything the default size for " \
116     "your device will be used. You can specify a standard size (cif, d1, ...) or <width>x<height>.")
117 #define ASPECT_TEXT N_("Picture aspect-ratio n:m")
118 #define ASPECT_LONGTEXT N_("Define input picture aspect-ratio to use. Default is 4:3" )
119 #define CHROMA_TEXT N_("Video input chroma format")
120 #define CHROMA_LONGTEXT N_( \
121     "Force the DirectShow video input to use a specific chroma format " \
122     "(eg. I420 (default), RV24, etc.)")
123 #define FPS_TEXT N_("Video input frame rate")
124 #define FPS_LONGTEXT N_( \
125     "Force the DirectShow video input to use a specific frame rate " \
126     "(eg. 0 means default, 25, 29.97, 50, 59.94, etc.)")
127 #define CONFIG_TEXT N_("Device properties")
128 #define CONFIG_LONGTEXT N_( \
129     "Show the properties dialog of the selected device before starting the " \
130     "stream.")
131 #define TUNER_TEXT N_("Tuner properties")
132 #define TUNER_LONGTEXT N_( \
133     "Show the tuner properties [channel selection] page." )
134 #define CHANNEL_TEXT N_("Tuner TV Channel")
135 #define CHANNEL_LONGTEXT N_( \
136     "Set the TV channel the tuner will set to " \
137     "(0 means default)." )
138 #define COUNTRY_TEXT N_("Tuner country code")
139 #define COUNTRY_LONGTEXT N_( \
140     "Set the tuner country code that establishes the current " \
141     "channel-to-frequency mapping (0 means default)." )
142 #define TUNER_INPUT_TEXT N_("Tuner input type")
143 #define TUNER_INPUT_LONGTEXT N_( \
144     "Select the tuner input type (Cable/Antenna)." )
145 #define VIDEO_IN_TEXT N_("Video input pin")
146 #define VIDEO_IN_LONGTEXT N_( \
147   "Select the video input source, such as composite, s-video, " \
148   "or tuner. Since these settings are hardware-specific, you should find good " \
149   "settings in the \"Device config\" area, and use those numbers here. -1 " \
150   "means that settings will not be changed.")
151 #define AUDIO_IN_TEXT N_("Audio input pin")
152 #define AUDIO_IN_LONGTEXT N_( \
153   "Select the audio input source. See the \"video input\" option." )
154 #define VIDEO_OUT_TEXT N_("Video output pin")
155 #define VIDEO_OUT_LONGTEXT N_( \
156   "Select the video output type. See the \"video input\" option." )
157 #define AUDIO_OUT_TEXT N_("Audio output pin")
158 #define AUDIO_OUT_LONGTEXT N_( \
159   "Select the audio output type. See the \"video input\" option." )
160
161 #define AMTUNER_MODE_TEXT N_("AM Tuner mode")
162 #define AMTUNER_MODE_LONGTEXT N_( \
163     "AM Tuner mode. Can be one of Default (0), TV (1), " \
164      "AM Radio (2), FM Radio (3) or DSS (4).")
165
166 #define AUDIO_CHANNELS_TEXT N_("Number of audio channels")
167 #define AUDIO_CHANNELS_LONGTEXT N_( \
168     "Select audio input format with the given number of audio channels (if non 0)" )
169
170 #define AUDIO_SAMPLERATE_TEXT N_("Audio sample rate")
171 #define AUDIO_SAMPLERATE_LONGTEXT N_( \
172     "Select audio input format with the given sample rate (if non 0)" )
173
174 #define AUDIO_BITSPERSAMPLE_TEXT N_("Audio bits per sample")
175 #define AUDIO_BITSPERSAMPLE_LONGTEXT N_( \
176     "Select audio input format with the given bits/sample (if non 0)" )
177
178 static int  CommonOpen ( vlc_object_t *, access_sys_t *, bool );
179 static void CommonClose( vlc_object_t *, access_sys_t * );
180
181 static int  AccessOpen ( vlc_object_t * );
182 static void AccessClose( vlc_object_t * );
183
184 static int  DemuxOpen  ( vlc_object_t * );
185 static void DemuxClose ( vlc_object_t * );
186
187 } // namespace
188
189 using namespace dshow;
190
191 vlc_module_begin ()
192     set_shortname( N_("DirectShow") )
193     set_description( N_("DirectShow input") )
194     set_category( CAT_INPUT )
195     set_subcategory( SUBCAT_INPUT_ACCESS )
196     add_string( "dshow-vdev", NULL, VDEV_TEXT, VDEV_LONGTEXT, false)
197         change_string_cb( FindDevices )
198
199     add_string( "dshow-adev", NULL, ADEV_TEXT, ADEV_LONGTEXT, false)
200         change_string_cb( FindDevices )
201
202     add_string( "dshow-size", NULL, SIZE_TEXT, SIZE_LONGTEXT, false)
203         change_safe()
204
205     add_string( "dshow-aspect-ratio", "4:3", ASPECT_TEXT, ASPECT_LONGTEXT, false)
206         change_safe()
207
208     add_string( "dshow-chroma", NULL, CHROMA_TEXT, CHROMA_LONGTEXT, true )
209         change_safe()
210
211     add_float( "dshow-fps", 0.0f, FPS_TEXT, FPS_LONGTEXT, true )
212         change_safe()
213
214     add_bool( "dshow-config", false, CONFIG_TEXT, CONFIG_LONGTEXT, true )
215
216     add_bool( "dshow-tuner", false, TUNER_TEXT, TUNER_LONGTEXT, true )
217
218     add_integer( "dshow-tuner-channel", 0, CHANNEL_TEXT, CHANNEL_LONGTEXT,
219                 true )
220         change_safe()
221
222     add_integer( "dshow-tuner-country", 0, COUNTRY_TEXT, COUNTRY_LONGTEXT,
223                 true )
224
225     add_integer( "dshow-tuner-input", 0, TUNER_INPUT_TEXT,
226                  TUNER_INPUT_LONGTEXT, true )
227         change_integer_list( pi_tuner_input, ppsz_tuner_input_text )
228         change_safe()
229
230     add_integer( "dshow-video-input",  -1, VIDEO_IN_TEXT,
231                  VIDEO_IN_LONGTEXT, true )
232         change_safe()
233
234     add_integer( "dshow-video-output", -1, VIDEO_OUT_TEXT,
235                  VIDEO_OUT_LONGTEXT, true )
236
237     add_integer( "dshow-audio-input",  -1, AUDIO_IN_TEXT,
238                  AUDIO_IN_LONGTEXT, true )
239         change_safe()
240
241     add_integer( "dshow-audio-output", -1, AUDIO_OUT_TEXT,
242                  AUDIO_OUT_LONGTEXT, true )
243
244     add_integer( "dshow-amtuner-mode", AMTUNER_MODE_TV,
245                 AMTUNER_MODE_TEXT, AMTUNER_MODE_LONGTEXT, false)
246         change_integer_list( pi_amtuner_mode, ppsz_amtuner_mode_text )
247         change_safe()
248
249     add_integer( "dshow-audio-channels", 0, AUDIO_CHANNELS_TEXT,
250                  AUDIO_CHANNELS_LONGTEXT, true )
251     add_integer( "dshow-audio-samplerate", 0, AUDIO_SAMPLERATE_TEXT,
252                  AUDIO_SAMPLERATE_LONGTEXT, true )
253     add_integer( "dshow-audio-bitspersample", 0, AUDIO_BITSPERSAMPLE_TEXT,
254                  AUDIO_BITSPERSAMPLE_LONGTEXT, true )
255
256     add_shortcut( "dshow" )
257     set_capability( "access", 1 )
258     set_callbacks( DemuxOpen, DemuxClose )
259
260     add_submodule ()
261     set_description( N_("DirectShow input") )
262     add_shortcut( "dshow" )
263     set_capability( "access", 0 )
264     set_callbacks( AccessOpen, AccessClose )
265
266 vlc_module_end ()
267
268 namespace dshow {
269
270 struct ComContext
271 {
272     ComContext( int mode )
273     {
274         if( FAILED( CoInitializeEx( NULL, mode ) ) )
275             throw std::runtime_error( "CoInitializeEx failed" );
276     }
277     ~ComContext()
278     {
279         CoUninitialize();
280     }
281 };
282
283 /*****************************************************************************
284  * DirectShow elementary stream descriptor
285  *****************************************************************************/
286 struct dshow_stream_t
287 {
288     std::string           devicename;
289     ComPtr<IBaseFilter>   p_device_filter;
290     ComPtr<CaptureFilter> p_capture_filter;
291     AM_MEDIA_TYPE   mt;
292
293     union
294     {
295       VIDEOINFOHEADER video;
296       WAVEFORMATEX    audio;
297
298     } header;
299
300     int             i_fourcc;
301     es_out_id_t     *p_es;
302
303     bool      b_pts;
304
305     std::deque<VLCMediaSample> samples_queue;
306 };
307
308 /*****************************************************************************
309  * DirectShow utility functions
310  *****************************************************************************/
311 static void CreateDirectShowGraph( access_sys_t *p_sys )
312 {
313     p_sys->i_crossbar_route_depth = 0;
314
315     /* Create directshow filter graph */
316     if( SUCCEEDED( CoCreateInstance( CLSID_FilterGraph, 0, CLSCTX_INPROC,
317                        (REFIID)IID_IFilterGraph, (void**)p_sys->p_graph.GetAddressOf() ) ) )
318     {
319         /* Create directshow capture graph builder if available */
320         if( SUCCEEDED( CoCreateInstance( CLSID_CaptureGraphBuilder2, 0,
321                          CLSCTX_INPROC, (REFIID)IID_ICaptureGraphBuilder2,
322                          (void**)p_sys->p_capture_graph_builder2.GetAddressOf() ) ) )
323         {
324             p_sys->p_capture_graph_builder2->
325                 SetFiltergraph((IGraphBuilder *)p_sys->p_graph.Get() );
326         }
327
328         p_sys->p_graph->QueryInterface( IID_IMediaControl,
329                                         (void**)p_sys->p_control.GetAddressOf() );
330     }
331 }
332
333 static void DeleteDirectShowGraph( vlc_object_t *p_this, access_sys_t *p_sys )
334 {
335     DeleteCrossbarRoutes( p_sys );
336
337     /* Remove filters from graph */
338     msg_Dbg( p_this, "DeleteDirectShowGraph: Removing filters" );
339     std::vector<dshow_stream_t*>::iterator it = p_sys->pp_streams.begin();
340     std::vector<dshow_stream_t*>::iterator end = p_sys->pp_streams.end();
341     for( ; it != end; ++it )
342     {
343         /* RemoveFilter does an undocumented Release()
344          * but does not set item to NULL */
345         msg_Dbg( p_this, "DeleteDirectShowGraph: Removing capture filter" );
346         p_sys->p_graph->RemoveFilter( (*it)->p_capture_filter.Get() );
347         (*it)->p_capture_filter.Reset();
348
349         msg_Dbg( p_this, "DeleteDirectShowGraph: Removing device filter" );
350         p_sys->p_graph->RemoveFilter( (*it)->p_device_filter.Get() );
351         (*it)->p_device_filter.Reset();
352     }
353
354     /* Release directshow objects */
355     p_sys->p_control.Reset();
356     p_sys->p_capture_graph_builder2.Reset();
357     p_sys->p_graph.Reset();
358 }
359
360 /*****************************************************************************
361  * CommonOpen: open direct show device
362  *****************************************************************************/
363 static int CommonOpen( vlc_object_t *p_this, access_sys_t *p_sys,
364                        bool b_access_demux )
365 {
366     char *psz_val;
367
368     /* Get/parse options and open device(s) */
369     std::string vdevname, adevname;
370     int i_width = 0, i_height = 0;
371     vlc_fourcc_t i_chroma = 0;
372     bool b_use_audio = true;
373     bool b_use_video = true;
374
375     var_Create( p_this,  "dshow-config", VLC_VAR_BOOL | VLC_VAR_DOINHERIT );
376     var_Create( p_this,  "dshow-tuner", VLC_VAR_BOOL | VLC_VAR_DOINHERIT );
377     psz_val = var_CreateGetString( p_this, "dshow-vdev" );
378     if( psz_val )
379     {
380         msg_Dbg( p_this, "dshow-vdev: %s", psz_val ) ;
381         /* skip none device */
382         if ( strncasecmp( psz_val, "none", 4 ) != 0 )
383             vdevname = std::string( psz_val );
384         else
385             b_use_video = false ;
386     }
387     free( psz_val );
388
389     psz_val = var_CreateGetString( p_this, "dshow-adev" );
390     if( psz_val )
391     {
392         msg_Dbg( p_this, "dshow-adev: %s", psz_val ) ;
393         /* skip none device */
394         if ( strncasecmp( psz_val, "none", 4 ) != 0 )
395             adevname = std::string( psz_val );
396         else
397             b_use_audio = false ;
398     }
399     free( psz_val );
400
401     /* DShow Size */
402     static struct {
403         const char *psz_size;
404         int  i_width;
405         int  i_height;
406     } size_table[] =
407     { { "subqcif", 128, 96  },
408       {    "qsif", 160, 120 },
409       {    "qcif", 176, 144 },
410       {     "sif", 320, 240 },
411       {     "cif", 352, 288 },
412       {      "d1", 640, 480 },
413       { 0, 0, 0 },
414     };
415
416     psz_val = var_CreateGetString( p_this, "dshow-size" );
417     if( !EMPTY_STR(psz_val) )
418     {
419         int i;
420         for( i = 0; size_table[i].psz_size; i++ )
421         {
422             if( !strcmp( psz_val, size_table[i].psz_size ) )
423             {
424                 i_width = size_table[i].i_width;
425                 i_height = size_table[i].i_height;
426                 break;
427             }
428         }
429         if( !size_table[i].psz_size ) /* Try to parse "WidthxHeight" */
430         {
431             char *psz_parser;
432             i_width = strtol( psz_val, &psz_parser, 0 );
433             if( *psz_parser == 'x' || *psz_parser == 'X')
434             {
435                 i_height = strtol( psz_parser + 1, &psz_parser, 0 );
436             }
437             msg_Dbg( p_this, "width x height %dx%d", i_width, i_height );
438         }
439     }
440     free( psz_val );
441
442     /* Chroma */
443     psz_val = var_CreateGetString( p_this, "dshow-chroma" );
444     i_chroma = vlc_fourcc_GetCodecFromString( VIDEO_ES, psz_val );
445     free( psz_val );
446
447     var_Create( p_this, "dshow-fps", VLC_VAR_FLOAT | VLC_VAR_DOINHERIT );
448     var_Create( p_this, "dshow-tuner-channel",
449                 VLC_VAR_INTEGER | VLC_VAR_DOINHERIT );
450     var_Create( p_this, "dshow-tuner-country",
451                 VLC_VAR_INTEGER | VLC_VAR_DOINHERIT );
452     var_Create( p_this, "dshow-tuner-input",
453                 VLC_VAR_INTEGER | VLC_VAR_DOINHERIT );
454
455     var_Create( p_this, "dshow-amtuner-mode",
456                 VLC_VAR_INTEGER | VLC_VAR_DOINHERIT );
457
458     var_Create( p_this, "dshow-video-input", VLC_VAR_INTEGER | VLC_VAR_DOINHERIT );
459     var_Create( p_this, "dshow-audio-input", VLC_VAR_INTEGER | VLC_VAR_DOINHERIT );
460     var_Create( p_this, "dshow-video-output", VLC_VAR_INTEGER | VLC_VAR_DOINHERIT );
461     var_Create( p_this, "dshow-audio-output", VLC_VAR_INTEGER | VLC_VAR_DOINHERIT );
462
463
464     /* Initialize some data */
465     p_sys->i_width = i_width;
466     p_sys->i_height = i_height;
467     p_sys->i_chroma = i_chroma;
468
469     /* Build directshow graph */
470     CreateDirectShowGraph( p_sys );
471
472     vlc_mutex_init( &p_sys->lock );
473     vlc_cond_init( &p_sys->wait );
474
475     if( !b_use_video && !b_use_audio )
476     {
477         vlc_dialog_display_error( p_this, _("Capture failed"),
478                         _("No video or audio device selected.") );
479         return VLC_EGENERIC ;
480     }
481
482     if( !b_use_video )
483         msg_Dbg( p_this, "skipping video device" ) ;
484     bool b_err_video = false ;
485
486     if( b_use_video && OpenDevice( p_this, p_sys, vdevname, 0 ) != VLC_SUCCESS )
487     {
488         msg_Err( p_this, "can't open video device");
489         b_err_video = true ;
490     }
491
492     if ( b_use_video && !b_err_video )
493     {
494         /* Check if we can handle the demuxing ourselves or need to spawn
495          * a demuxer module */
496         dshow_stream_t *p_stream = *(p_sys->pp_streams.rbegin());
497
498         if( p_stream->mt.majortype == MEDIATYPE_Video )
499         {
500             if( /* Raw DV stream */
501                 p_stream->i_fourcc == VLC_CODEC_DV ||
502                 /* Raw MPEG video stream */
503                 p_stream->i_fourcc == VLC_CODEC_MPGV )
504             {
505                 b_use_audio = false;
506
507                 if( b_access_demux )
508                 {
509                     /* Let the access (only) take care of that */
510                     return VLC_EGENERIC;
511                 }
512             }
513         }
514
515         if( p_stream->mt.majortype == MEDIATYPE_Stream )
516         {
517             b_use_audio = false;
518
519             if( b_access_demux )
520             {
521                 /* Let the access (only) take care of that */
522                 return VLC_EGENERIC;
523             }
524
525             if( var_GetBool( p_this, "dshow-tuner" ) )
526             {
527                 /* FIXME: we do MEDIATYPE_Stream here so we don't do
528                  * it twice. */
529                 ShowTunerProperties( p_this, p_sys->p_capture_graph_builder2.Get(),
530                                      p_stream->p_device_filter.Get(), 0 );
531             }
532         }
533     }
534
535     if( !b_use_audio )
536         msg_Dbg( p_this, "skipping audio device") ;
537
538     bool b_err_audio = false ;
539
540     if( b_use_audio && OpenDevice( p_this, p_sys, adevname, 1 ) != VLC_SUCCESS )
541     {
542         msg_Err( p_this, "can't open audio device");
543         b_err_audio = true ;
544     }
545
546     if( ( b_use_video && b_err_video && b_use_audio && b_err_audio ) ||
547         ( !b_use_video && b_use_audio && b_err_audio ) ||
548         ( b_use_video && !b_use_audio && b_err_video ) )
549     {
550         msg_Err( p_this, "FATAL: could not open ANY device" ) ;
551         vlc_dialog_display_error( p_this,  _("Capture failed"),
552                         _("VLC cannot open ANY capture device. "
553                           "Check the error log for details.") );
554         return VLC_EGENERIC ;
555     }
556
557     for( int i = p_sys->i_crossbar_route_depth-1; i >= 0 ; --i )
558     {
559         int i_val = var_GetInteger( p_this, "dshow-video-input" );
560         if( i_val >= 0 )
561             p_sys->crossbar_routes[i].VideoInputIndex = i_val;
562         i_val = var_GetInteger( p_this, "dshow-video-output" );
563         if( i_val >= 0 )
564             p_sys->crossbar_routes[i].VideoOutputIndex = i_val;
565         i_val = var_GetInteger( p_this, "dshow-audio-input" );
566         if( i_val >= 0 )
567             p_sys->crossbar_routes[i].AudioInputIndex = i_val;
568         i_val = var_GetInteger( p_this, "dshow-audio-output" );
569         if( i_val >= 0 )
570             p_sys->crossbar_routes[i].AudioOutputIndex = i_val;
571
572         IAMCrossbar *pXbar = p_sys->crossbar_routes[i].pXbar.Get();
573         LONG VideoInputIndex = p_sys->crossbar_routes[i].VideoInputIndex;
574         LONG VideoOutputIndex = p_sys->crossbar_routes[i].VideoOutputIndex;
575         LONG AudioInputIndex = p_sys->crossbar_routes[i].AudioInputIndex;
576         LONG AudioOutputIndex = p_sys->crossbar_routes[i].AudioOutputIndex;
577
578         if( SUCCEEDED(pXbar->Route(VideoOutputIndex, VideoInputIndex)) )
579         {
580             msg_Dbg( p_this, "crossbar at depth %d, routed video "
581                      "output %ld to video input %ld", i, VideoOutputIndex,
582                      VideoInputIndex );
583
584             if( AudioOutputIndex != -1 && AudioInputIndex != -1 )
585             {
586                 if( SUCCEEDED( pXbar->Route(AudioOutputIndex,
587                                             AudioInputIndex)) )
588                 {
589                     msg_Dbg(p_this, "crossbar at depth %d, routed audio "
590                             "output %ld to audio input %ld", i,
591                             AudioOutputIndex, AudioInputIndex );
592                 }
593             }
594         }
595         else
596             msg_Err( p_this, "crossbar at depth %d could not route video "
597                      "output %ld to input %ld", i, VideoOutputIndex, VideoInputIndex );
598     }
599
600     /*
601     ** Show properties pages from other filters in graph
602     */
603     if( var_GetBool( p_this, "dshow-config" ) )
604     {
605         for( int i = p_sys->i_crossbar_route_depth-1; i >= 0 ; --i )
606         {
607             IAMCrossbar *pXbar = p_sys->crossbar_routes[i].pXbar.Get();
608             ComPtr<IBaseFilter> p_XF;
609
610             if( SUCCEEDED( pXbar->QueryInterface( IID_IBaseFilter,
611                                                   (void**)p_XF.ReleaseAndGetAddressOf() ) ) )
612             {
613                 ShowPropertyPage( p_XF.Get() );
614             }
615         }
616     }
617
618     /* Initialize some data */
619     p_sys->i_current_stream = 0;
620
621     if( p_sys->pp_streams.empty() ) return VLC_EGENERIC;
622
623     return VLC_SUCCESS;
624 }
625
626 static void SetRGBMasks( vlc_fourcc_t i_fourcc, es_format_t *fmt )
627 {
628     switch( i_fourcc )
629     {
630         case VLC_CODEC_RGB15:
631             fmt->video.i_rmask = 0x7c00;
632             fmt->video.i_gmask = 0x03e0;
633             fmt->video.i_bmask = 0x001f;
634             break;
635         case VLC_CODEC_RGB16:
636             fmt->video.i_rmask = 0xf800;
637             fmt->video.i_gmask = 0x07e0;
638             fmt->video.i_bmask = 0x001f;
639             break;
640         case VLC_CODEC_RGB24:
641             /* This is in BGR format */
642             fmt->video.i_bmask = 0x00ff0000;
643             fmt->video.i_gmask = 0x0000ff00;
644             fmt->video.i_rmask = 0x000000ff;
645             break;
646         case VLC_CODEC_RGB32:
647         case VLC_CODEC_RGBA:
648             /* This is in BGRx format */
649             fmt->video.i_bmask = 0xff000000;
650             fmt->video.i_gmask = 0x00ff0000;
651             fmt->video.i_rmask = 0x0000ff00;
652             break;
653         default:
654             return;
655     }
656     fmt->video.i_chroma = i_fourcc;
657     video_format_FixRgb( &fmt->video );
658 }
659
660 /*****************************************************************************
661  * DemuxOpen: open direct show device as an access_demux module
662  *****************************************************************************/
663 static int DemuxOpen( vlc_object_t *p_this )
664 {
665     demux_t      *p_demux = (demux_t *)p_this;
666     access_sys_t *p_sys;
667
668     if (p_demux->out == NULL)
669         return VLC_EGENERIC;
670
671     p_sys = (access_sys_t*)calloc( 1, sizeof( access_sys_t ) );
672     if( !p_sys )
673         return VLC_ENOMEM;
674     p_demux->p_sys = (demux_sys_t *)p_sys;
675
676     ComContext ctx( COINIT_MULTITHREADED );
677
678     if( vlc_mta_acquire( p_this ) == false )
679     {
680         msg_Err( p_this, "Failed to acquire MTA" );
681         return VLC_EGENERIC;
682     }
683
684     if( CommonOpen( p_this, p_sys, true ) != VLC_SUCCESS )
685     {
686         CommonClose( p_this, p_sys );
687         return VLC_EGENERIC;
688     }
689
690     /* Everything is ready. Let's rock baby */
691     msg_Dbg( p_this, "Playing...");
692     if( FAILED( p_sys->p_control->Run() ) )
693     {
694         msg_Err( p_this, "Failed to run graph. Capture device may be in use." );
695         CommonClose( p_this, p_sys );
696         return VLC_EGENERIC;
697     }
698
699     p_demux->pf_demux   = Demux;
700     p_demux->pf_control = DemuxControl;
701
702     std::vector<dshow_stream_t*>::iterator it = p_sys->pp_streams.begin();
703     std::vector<dshow_stream_t*>::iterator end = p_sys->pp_streams.end();
704     for ( ; it != end; ++it )
705     {
706         dshow_stream_t *p_stream = *it;
707         es_format_t fmt;
708
709         if( p_stream->mt.majortype == MEDIATYPE_Video )
710         {
711             char *psz_aspect = var_CreateGetString( p_this, "dshow-aspect-ratio" );
712             char *psz_delim = !EMPTY_STR( psz_aspect ) ? strchr( psz_aspect, ':' ) : NULL;
713
714             es_format_Init( &fmt, VIDEO_ES, p_stream->i_fourcc );
715
716             fmt.video.i_width  = p_stream->header.video.bmiHeader.biWidth;
717             fmt.video.i_height = p_stream->header.video.bmiHeader.biHeight;
718
719             if( psz_delim )
720             {
721                 fmt.video.i_sar_num = atoi( psz_aspect ) * fmt.video.i_height;
722                 fmt.video.i_sar_den = atoi( psz_delim + 1 ) * fmt.video.i_width;
723             }
724             else
725             {
726                 fmt.video.i_sar_num = 4 * fmt.video.i_height;
727                 fmt.video.i_sar_den = 3 * fmt.video.i_width;
728             }
729             free( psz_aspect );
730
731             if( !p_stream->header.video.bmiHeader.biCompression )
732             {
733                 /* RGB DIB are coded from bottom to top */
734                 fmt.video.orientation = ORIENT_BOTTOM_LEFT;
735             }
736
737             /* Setup rgb mask for RGB formats */
738             SetRGBMasks( p_stream->i_fourcc, &fmt );
739
740             if( p_stream->header.video.AvgTimePerFrame )
741             {
742                 fmt.video.i_frame_rate = 10000000;
743                 fmt.video.i_frame_rate_base =
744                     p_stream->header.video.AvgTimePerFrame;
745             }
746         }
747         else if( p_stream->mt.majortype == MEDIATYPE_Audio )
748         {
749             es_format_Init( &fmt, AUDIO_ES, p_stream->i_fourcc );
750
751             fmt.audio.i_channels = p_stream->header.audio.nChannels;
752             fmt.audio.i_rate = p_stream->header.audio.nSamplesPerSec;
753             fmt.audio.i_bitspersample = p_stream->header.audio.wBitsPerSample;
754             fmt.audio.i_blockalign = fmt.audio.i_channels *
755                 fmt.audio.i_bitspersample / 8;
756             fmt.i_bitrate = fmt.audio.i_channels * fmt.audio.i_rate *
757                 fmt.audio.i_bitspersample;
758         }
759
760         p_stream->p_es = es_out_Add( p_demux->out, &fmt );
761     }
762
763     p_sys->i_start = vlc_tick_now();
764     return VLC_SUCCESS;
765 }
766
767 /*****************************************************************************
768  * AccessOpen: open direct show device as an access module
769  *****************************************************************************/
770 static int AccessOpen( vlc_object_t *p_this )
771 {
772     stream_t     *p_access = (stream_t*)p_this;
773     access_sys_t *p_sys;
774
775     p_access->p_sys = p_sys = (access_sys_t*)calloc( 1, sizeof( access_sys_t ) );
776     if( !p_sys )
777         return VLC_ENOMEM;
778
779     ComContext ctx( COINIT_MULTITHREADED );
780
781     if( vlc_mta_acquire( p_this ) == false )
782     {
783         msg_Err( p_this, "Failed to acquire MTA" );
784         return VLC_EGENERIC;
785     }
786
787     if( CommonOpen( p_this, p_sys, false ) != VLC_SUCCESS )
788     {
789         CommonClose( p_this, p_sys );
790         return VLC_EGENERIC;
791     }
792
793     /* Setup Access */
794     p_access->pf_read = NULL;
795     p_access->pf_block = ReadCompressed;
796     p_access->pf_control = AccessControl;
797     p_access->pf_seek = NULL;
798     p_access->p_sys = p_sys;
799
800     /* Everything is ready. Let's rock baby */
801     msg_Dbg( p_this, "Playing...");
802     if( FAILED( p_sys->p_control->Run() ) )
803     {
804         msg_Err( p_this, "Failed to run graph. Capture device may be in use." );
805         CommonClose( p_this, p_sys );
806         return VLC_EGENERIC;
807     }
808
809     return VLC_SUCCESS;
810 }
811
812 /*****************************************************************************
813  * CommonClose: close device
814  *****************************************************************************/
815 static void CommonClose( vlc_object_t *p_this, access_sys_t *p_sys )
816 {
817     msg_Dbg( p_this, "releasing DirectShow");
818
819     DeleteDirectShowGraph( p_this, p_sys );
820
821     vlc_delete_all( p_sys->pp_streams );
822
823     vlc_mutex_destroy( &p_sys->lock );
824     vlc_cond_destroy( &p_sys->wait );
825
826     vlc_mta_release( p_this );
827
828     free( p_sys );
829 }
830
831 /*****************************************************************************
832  * AccessClose: close device
833  *****************************************************************************/
834 static void AccessClose( vlc_object_t *p_this )
835 {
836     stream_t     *p_access = (stream_t *)p_this;
837     access_sys_t *p_sys    = (access_sys_t *)p_access->p_sys;
838
839     ComContext ctx( COINIT_MULTITHREADED );
840
841     /* Stop capturing stuff */
842     p_sys->p_control->Stop();
843
844     CommonClose( p_this, p_sys );
845 }
846
847 /*****************************************************************************
848  * DemuxClose: close device
849  *****************************************************************************/
850 static void DemuxClose( vlc_object_t *p_this )
851 {
852     demux_t      *p_demux = (demux_t *)p_this;
853     access_sys_t *p_sys   = (access_sys_t *)p_demux->p_sys;
854
855     ComContext ctx( COINIT_MULTITHREADED );
856
857     /* Stop capturing stuff */
858     p_sys->p_control->Stop();
859
860     CommonClose( p_this, p_sys );
861 }
862
863 /****************************************************************************
864  * ConnectFilters
865  ****************************************************************************/
866 static bool ConnectFilters( vlc_object_t *p_this, access_sys_t *p_sys,
867                             IBaseFilter *p_filter,
868                             CaptureFilter *p_capture_filter )
869 {
870     ComPtr<CapturePin> p_input_pin = p_capture_filter->CustomGetPin();
871
872     AM_MEDIA_TYPE mediaType = p_input_pin->CustomGetMediaType();
873
874     if( p_sys->p_capture_graph_builder2 )
875     {
876         if( FAILED(p_sys->p_capture_graph_builder2->
877                 RenderStream( &PIN_CATEGORY_CAPTURE, &mediaType.majortype,
878                               p_filter, 0, (IBaseFilter *)p_capture_filter )) )
879         {
880             return false;
881         }
882
883         // Sort out all the possible video inputs
884         // The class needs to be given the capture filters ANALOGVIDEO input pin
885         ComPtr<IEnumPins> pins;
886         if( ( mediaType.majortype == MEDIATYPE_Video ||
887               mediaType.majortype == MEDIATYPE_Stream ) &&
888             SUCCEEDED(p_filter->EnumPins(pins.GetAddressOf())) )
889         {
890             ComPtr<IPin> pP;
891             ULONG        n;
892             PIN_INFO     pinInfo;
893             BOOL         Found = FALSE;
894             GUID guid;
895             DWORD dw;
896
897             while( !Found && ( S_OK == pins->Next(1, pP.ReleaseAndGetAddressOf(), &n) ) )
898             {
899                 if( S_OK == pP->QueryPinInfo(&pinInfo) )
900                 {
901                     ComPtr<IKsPropertySet> pKs;
902                     // is this pin an ANALOGVIDEOIN input pin?
903                     if( pinInfo.dir == PINDIR_INPUT &&
904                         pP->QueryInterface( IID_IKsPropertySet,
905                                             (void**)pKs.GetAddressOf() ) == S_OK )
906                     {
907                         if( pKs->Get( AMPROPSETID_Pin,
908                                       AMPROPERTY_PIN_CATEGORY, NULL, 0,
909                                       &guid, sizeof(GUID), &dw ) == S_OK )
910                         {
911                             if( guid == PIN_CATEGORY_ANALOGVIDEOIN )
912                             {
913                                 // recursively search crossbar routes
914                                 FindCrossbarRoutes( p_this, p_sys, pP.Get(), 0 );
915                                 // found it
916                                 Found = TRUE;
917                             }
918                         }
919                     }
920                     pinInfo.pFilter->Release();
921                 }
922             }
923             msg_Dbg( p_this, "ConnectFilters: graph_builder2 available.") ;
924             if ( !Found )
925                 msg_Warn( p_this, "ConnectFilters: No crossBar routes found (incompatible pin types)" ) ;
926         }
927         return true;
928     }
929     else
930     {
931         ComPtr<IEnumPins> p_enumpins;
932         ComPtr<IPin> p_pin;
933
934         if( S_OK != p_filter->EnumPins( p_enumpins.GetAddressOf() ) ) return false;
935
936         while( S_OK == p_enumpins->Next( 1, p_pin.ReleaseAndGetAddressOf(), NULL ) )
937         {
938             PIN_DIRECTION pin_dir;
939             p_pin->QueryDirection( &pin_dir );
940
941             if( pin_dir == PINDIR_OUTPUT &&
942                 p_sys->p_graph->ConnectDirect( p_pin.Get(), p_input_pin.Get(),
943                                                0 ) == S_OK )
944             {
945                 return true;
946             }
947         }
948         return false;
949     }
950 }
951
952 /*
953  * get fourcc priority from arbritary preference, the higher the better
954  */
955 static int GetFourCCPriority( int i_fourcc )
956 {
957     switch( i_fourcc )
958     {
959     case VLC_CODEC_I420:
960     case VLC_CODEC_FL32:
961         return 9;
962     case VLC_CODEC_YV12:
963     case VLC_FOURCC('a','r','a','w'):
964         return 8;
965     case VLC_CODEC_RGB24:
966         return 7;
967     case VLC_CODEC_YUYV:
968     case VLC_CODEC_RGB32:
969     case VLC_CODEC_RGBA:
970         return 6;
971     }
972
973     return 0;
974 }
975
976 #define MAX_MEDIA_TYPES 32
977
978 static int OpenDevice( vlc_object_t *p_this, access_sys_t *p_sys,
979                        std::string devicename, bool b_audio )
980 {
981     ComPtr<IBaseFilter> p_device_filter;
982
983     /* See if device is already opened */
984     std::vector<dshow_stream_t*>::iterator it = p_sys->pp_streams.begin();
985     std::vector<dshow_stream_t*>::iterator end = p_sys->pp_streams.end();
986     for ( ; it != end; ++it )
987     {
988         if( devicename.size() &&
989             (*it)->devicename == devicename )
990         {
991             /* Already opened */
992             wchar_t *pwsz_devicename = ToWide( devicename.c_str() );
993
994             if( likely( pwsz_devicename ) )
995                 p_sys->p_graph->FindFilterByName( pwsz_devicename, p_device_filter.GetAddressOf() );
996
997             free( pwsz_devicename );
998
999             if( !p_device_filter )
1000             {
1001                 msg_Err( p_this, "Device '%s' already opened, but couldn't be retrieved", devicename.c_str() );
1002                 return VLC_EGENERIC;
1003             }
1004
1005             break;
1006         }
1007     }
1008
1009     if( !p_device_filter )
1010     {
1011         std::list<std::string> list_devices;
1012
1013         /* Enumerate devices and display their names */
1014         FindCaptureDevice( p_this, NULL, &list_devices, b_audio );
1015         if( list_devices.empty() )
1016             return VLC_EGENERIC;
1017
1018         std::list<std::string>::iterator iter;
1019         for( iter = list_devices.begin(); iter != list_devices.end(); ++iter )
1020             msg_Dbg( p_this, "found device: %s", iter->c_str() );
1021
1022         /* If no device name was specified, pick the 1st one */
1023         if( devicename.size() == 0 )
1024         {
1025             /* When none selected */
1026             devicename = *list_devices.begin();
1027             msg_Dbg( p_this, "asking for default device: %s", devicename.c_str() ) ;
1028         }
1029         else
1030             msg_Dbg( p_this, "asking for device: %s", devicename.c_str() ) ;
1031
1032         // Use the system device enumerator and class enumerator to find
1033         // a capture/preview device, such as a desktop USB video camera.
1034         p_device_filter = FindCaptureDevice( p_this, &devicename, NULL, b_audio );
1035
1036         if( p_device_filter )
1037             msg_Dbg( p_this, "using device: %s", devicename.c_str() );
1038         else
1039         {
1040             msg_Err( p_this, "can't use device: %s, unsupported device type",
1041                      devicename.c_str() );
1042             vlc_dialog_display_error( p_this, _("Capture failed"),
1043                             _("The device you selected cannot be used, because its "
1044                               "type is not supported.") );
1045             return VLC_EGENERIC;
1046         }
1047
1048         /* Add the device filter to the graph (seems necessary with VfW before
1049          * accessing pin attributes). */
1050
1051         HRESULT hr = E_FAIL;
1052         wchar_t *pwsz_devicename = ToWide( devicename.c_str() );
1053
1054         if( likely( pwsz_devicename ) )
1055             hr = p_sys->p_graph->AddFilter( p_device_filter.Get(), pwsz_devicename );
1056
1057         free( pwsz_devicename );
1058
1059         if( FAILED( hr ) )
1060         {
1061             msg_Err( p_this, "Error adding device '%s' to the graph", devicename.c_str() );
1062             return VLC_EGENERIC;
1063         }
1064     }
1065
1066     // Retreive acceptable media types supported by device
1067     AM_MEDIA_TYPE media_types[MAX_MEDIA_TYPES];
1068     size_t media_count =
1069         EnumDeviceCaps( p_this, p_device_filter.Get(), b_audio ? 0 : p_sys->i_chroma,
1070                         p_sys->i_width, p_sys->i_height,
1071       b_audio ? var_CreateGetInteger( p_this, "dshow-audio-channels" ) : 0,
1072       b_audio ? var_CreateGetInteger( p_this, "dshow-audio-samplerate" ) : 0,
1073       b_audio ? var_CreateGetInteger( p_this, "dshow-audio-bitspersample" ) : 0,
1074       media_types, MAX_MEDIA_TYPES, b_audio );
1075
1076     AM_MEDIA_TYPE *mt = NULL;
1077
1078     if( media_count > 0 )
1079     {
1080         mt = (AM_MEDIA_TYPE *)CoTaskMemAlloc(sizeof(AM_MEDIA_TYPE) * media_count);
1081
1082         // Order and copy returned media types according to arbitrary
1083         // fourcc priority
1084         for( size_t c = 0; c < media_count; c++ )
1085         {
1086             int slot_priority =
1087                 GetFourCCPriority(GetFourCCFromMediaType(media_types[c]));
1088             size_t slot_copy = c;
1089             for( size_t d = c+1; d < media_count; d++ )
1090             {
1091                 int priority =
1092                     GetFourCCPriority(GetFourCCFromMediaType(media_types[d]));
1093                 if( priority > slot_priority )
1094                 {
1095                     slot_priority = priority;
1096                     slot_copy = d;
1097                 }
1098             }
1099             if( slot_copy != c )
1100             {
1101                 mt[c] = media_types[slot_copy];
1102                 media_types[slot_copy] = media_types[c];
1103             }
1104             else
1105             {
1106                 mt[c] = media_types[c];
1107             }
1108         }
1109     }
1110     else {
1111         /* capture device */
1112         msg_Err( p_this, "capture device '%s' does not support required parameters !", devicename.c_str() );
1113         vlc_dialog_display_error( p_this, _("Capture failed"),
1114                         _("The capture device \"%s\" does not support the "
1115                           "required parameters."), devicename.c_str() );
1116         return VLC_EGENERIC;
1117     }
1118
1119     /* Create and add our capture filter */
1120     ComPtr<CaptureFilter> p_capture_filter(
1121         new CaptureFilter( p_this, p_sys, mt, media_count ) );
1122     p_sys->p_graph->AddFilter( p_capture_filter.Get(), 0 );
1123
1124     /* Attempt to connect one of this device's capture output pins */
1125     msg_Dbg( p_this, "connecting filters" );
1126     if( ConnectFilters( p_this, p_sys, p_device_filter.Get(), p_capture_filter.Get() ) )
1127     {
1128         /* Success */
1129         msg_Dbg( p_this, "filters connected successfully !" );
1130
1131         dshow_stream_t dshow_stream;
1132         dshow_stream.devicename = devicename;
1133         dshow_stream.b_pts = false;
1134         dshow_stream.p_es = 0;
1135         dshow_stream.mt =
1136             p_capture_filter->CustomGetPin()->CustomGetMediaType();
1137
1138         /* Show Device properties. Done here so the VLC stream is setup with
1139          * the proper parameters. */
1140         if( var_GetBool( p_this, "dshow-config" ) )
1141         {
1142             ShowDeviceProperties( p_this, p_sys->p_capture_graph_builder2.Get(),
1143                                   p_device_filter.Get(), b_audio );
1144         }
1145
1146         ConfigTuner( p_this, p_sys->p_capture_graph_builder2.Get(),
1147                      p_device_filter.Get() );
1148
1149         if( var_GetBool( p_this, "dshow-tuner" ) &&
1150             dshow_stream.mt.majortype != MEDIATYPE_Stream )
1151         {
1152             /* FIXME: we do MEDIATYPE_Stream later so we don't do it twice. */
1153             ShowTunerProperties( p_this, p_sys->p_capture_graph_builder2.Get(),
1154                                  p_device_filter.Get(), b_audio );
1155         }
1156
1157         dshow_stream.mt =
1158             p_capture_filter->CustomGetPin()->CustomGetMediaType();
1159
1160         dshow_stream.i_fourcc = GetFourCCFromMediaType( dshow_stream.mt );
1161         if( dshow_stream.i_fourcc )
1162         {
1163             if( dshow_stream.mt.majortype == MEDIATYPE_Video )
1164             {
1165                 dshow_stream.header.video =
1166                     *(VIDEOINFOHEADER *)dshow_stream.mt.pbFormat;
1167                 msg_Dbg( p_this, "MEDIATYPE_Video" );
1168                 msg_Dbg( p_this, "selected video pin accepts format: %4.4s",
1169                          (char *)&dshow_stream.i_fourcc);
1170             }
1171             else if( dshow_stream.mt.majortype == MEDIATYPE_Audio )
1172             {
1173                 dshow_stream.header.audio =
1174                     *(WAVEFORMATEX *)dshow_stream.mt.pbFormat;
1175                 msg_Dbg( p_this, "MEDIATYPE_Audio" );
1176                 msg_Dbg( p_this, "selected audio pin accepts format: %4.4s",
1177                          (char *)&dshow_stream.i_fourcc);
1178             }
1179             else if( dshow_stream.mt.majortype == MEDIATYPE_Stream )
1180             {
1181                 msg_Dbg( p_this, "MEDIATYPE_Stream" );
1182                 msg_Dbg( p_this, "selected stream pin accepts format: %4.4s",
1183                          (char *)&dshow_stream.i_fourcc);
1184             }
1185             else
1186             {
1187                 msg_Dbg( p_this, "unknown stream majortype" );
1188                 goto fail;
1189             }
1190
1191             /* Add directshow elementary stream to our list */
1192             dshow_stream.p_device_filter = p_device_filter;
1193             dshow_stream.p_capture_filter = p_capture_filter;
1194
1195             p_sys->pp_streams.push_back( new dshow_stream_t(dshow_stream) );
1196
1197             return VLC_SUCCESS;
1198         }
1199     }
1200
1201  fail:
1202     /* Remove filters from graph */
1203     msg_Dbg( p_this, "OpenDevice: Removing filters" ) ;
1204     p_sys->p_graph->RemoveFilter( p_device_filter.Get() );
1205     p_sys->p_graph->RemoveFilter( p_capture_filter.Get() );
1206
1207     return VLC_EGENERIC;
1208 }
1209
1210 /* FindCaptureDevices:: This Function had two purposes :
1211     Returns the list of capture devices when p_listdevices != NULL
1212     Creates an IBaseFilter when p_devicename corresponds to an existing devname
1213    These actions *may* be requested whith a single call.
1214 */
1215 static ComPtr<IBaseFilter>
1216 FindCaptureDevice( vlc_object_t *p_this, std::string *p_devicename,
1217                    std::list<std::string> *p_listdevices, bool b_audio )
1218 {
1219     ComPtr<IBaseFilter> p_base_filter;
1220     ComPtr<IMoniker> p_moniker;
1221     ULONG i_fetched;
1222     HRESULT hr;
1223     std::list<std::string> devicelist;
1224
1225     /* Create the system device enumerator */
1226     ComPtr<ICreateDevEnum> p_dev_enum;
1227
1228     hr = CoCreateInstance( CLSID_SystemDeviceEnum, NULL, CLSCTX_INPROC,
1229                            IID_ICreateDevEnum, (void**)p_dev_enum.GetAddressOf() );
1230     if( FAILED(hr) )
1231     {
1232         msg_Err( p_this, "failed to create the device enumerator (0x%lx)", hr);
1233         return p_base_filter;
1234     }
1235
1236     /* Create an enumerator for the video capture devices */
1237     ComPtr<IEnumMoniker> p_class_enum;
1238     if( !b_audio )
1239         hr = p_dev_enum->CreateClassEnumerator( CLSID_VideoInputDeviceCategory,
1240                                                 p_class_enum.GetAddressOf(), 0 );
1241     else
1242         hr = p_dev_enum->CreateClassEnumerator( CLSID_AudioInputDeviceCategory,
1243                                                 p_class_enum.GetAddressOf(), 0 );
1244     if( FAILED(hr) )
1245     {
1246         msg_Err( p_this, "failed to create the class enumerator (0x%lx)", hr );
1247         return p_base_filter;
1248     }
1249
1250     /* If there are no enumerators for the requested type, then
1251      * CreateClassEnumerator will succeed, but p_class_enum will be NULL */
1252     if( p_class_enum == NULL )
1253     {
1254         msg_Err( p_this, "no %s capture device was detected", ( b_audio ? "audio" : "video" ) );
1255         return p_base_filter;
1256     }
1257
1258     /* Enumerate the devices */
1259
1260     /* Note that if the Next() call succeeds but there are no monikers,
1261      * it will return S_FALSE (which is not a failure). Therefore, we check
1262      * that the return code is S_OK instead of using SUCCEEDED() macro. */
1263
1264     while( p_class_enum->Next( 1, p_moniker.ReleaseAndGetAddressOf(), &i_fetched ) == S_OK )
1265     {
1266         /* Getting the property page to get the device name */
1267         ComPtr<IPropertyBag> p_bag;
1268         hr = p_moniker->BindToStorage( 0, 0, IID_IPropertyBag,
1269                                        (void**)p_bag.GetAddressOf() );
1270         if( SUCCEEDED(hr) )
1271         {
1272             VARIANT var;
1273             var.vt = VT_BSTR;
1274             hr = p_bag->Read( L"FriendlyName", &var, NULL );
1275             if( SUCCEEDED(hr) )
1276             {
1277                 char *p_buf = FromWide( var.bstrVal );
1278                 std::string devname(p_buf);
1279                 free( p_buf) ;
1280
1281                 int dup = 0;
1282                 /* find out if this name is already used by a previously found device */
1283                 std::list<std::string>::const_iterator iter = devicelist.begin();
1284                 std::list<std::string>::const_iterator end = devicelist.end();
1285                 std::string ordevname = devname ;
1286                 while ( iter != end )
1287                 {
1288                     if( 0 == (*iter).compare( devname ) )
1289                     { /* devname is on the list. Try another name with sequence
1290                          number apended and then rescan until a unique entry is found*/
1291                          char seq[16];
1292                          snprintf(seq, 16, " #%d", ++dup);
1293                          devname = ordevname + seq;
1294                          iter = devicelist.begin();
1295                     }
1296                     else
1297                          ++iter;
1298                 }
1299                 devicelist.push_back( devname );
1300
1301                 if( p_devicename && *p_devicename == devname )
1302                 {
1303                     msg_Dbg( p_this, "asked for %s, binding to %s", p_devicename->c_str() , devname.c_str() ) ;
1304                     /* NULL possibly means we don't need BindMoniker BindCtx ?? */
1305                     hr = p_moniker->BindToObject( NULL, 0, IID_IBaseFilter,
1306                                                   (void**)p_base_filter.GetAddressOf() );
1307                     if( FAILED(hr) )
1308                     {
1309                         msg_Err( p_this, "couldn't bind moniker to filter "
1310                                  "object (0x%lx)", hr );
1311                         return NULL;
1312                     }
1313                     return p_base_filter;
1314                 }
1315             }
1316         }
1317     }
1318
1319     if( p_listdevices ) {
1320         devicelist.sort();
1321         *p_listdevices = devicelist;
1322     }
1323     return p_base_filter;
1324 }
1325
1326 static size_t EnumDeviceCaps( vlc_object_t *p_this, IBaseFilter *p_filter,
1327                               int i_fourcc, int i_width, int i_height,
1328                               int i_channels, int i_samplespersec,
1329                               int i_bitspersample, AM_MEDIA_TYPE *mt,
1330                               size_t mt_max, bool b_audio )
1331 {
1332     ComPtr<IEnumPins> p_enumpins;
1333     ComPtr<IPin> p_output_pin;
1334     ComPtr<IEnumMediaTypes> p_enummt;
1335     size_t mt_count = 0;
1336
1337     LONGLONG i_AvgTimePerFrame = 0;
1338     float r_fps = var_GetFloat( p_this, "dshow-fps" );
1339     if( r_fps )
1340         i_AvgTimePerFrame = 10000000000LL/(LONGLONG)(r_fps*1000.0f);
1341
1342     if( FAILED(p_filter->EnumPins( p_enumpins.GetAddressOf() )) )
1343     {
1344         msg_Dbg( p_this, "EnumDeviceCaps failed: no pin enumeration !");
1345         return 0;
1346     }
1347
1348     while( S_OK == p_enumpins->Next( 1, p_output_pin.ReleaseAndGetAddressOf(), NULL ) )
1349     {
1350         PIN_INFO info;
1351
1352         if( S_OK == p_output_pin->QueryPinInfo( &info ) )
1353         {
1354             msg_Dbg( p_this, "EnumDeviceCaps: %s pin: %S",
1355                      info.dir == PINDIR_INPUT ? "input" : "output",
1356                      info.achName );
1357             if( info.pFilter ) info.pFilter->Release();
1358         }
1359     }
1360
1361     p_enumpins->Reset();
1362
1363     while( !mt_count && p_enumpins->Next( 1, p_output_pin.ReleaseAndGetAddressOf(), NULL ) == S_OK )
1364     {
1365         PIN_INFO info;
1366
1367         if( S_OK == p_output_pin->QueryPinInfo( &info ) )
1368         {
1369             if( info.pFilter ) info.pFilter->Release();
1370             if( info.dir == PINDIR_INPUT )
1371                 continue;
1372             msg_Dbg( p_this, "EnumDeviceCaps: trying pin %S", info.achName );
1373         }
1374
1375         AM_MEDIA_TYPE *p_mt;
1376
1377         /*
1378         ** Configure pin with a default compatible media if possible
1379         */
1380
1381         ComPtr<IAMStreamConfig> pSC;
1382         if( SUCCEEDED(p_output_pin->QueryInterface( IID_IAMStreamConfig,
1383                                             (void**)pSC.GetAddressOf() )) )
1384         {
1385             int piCount, piSize;
1386             if( SUCCEEDED(pSC->GetNumberOfCapabilities(&piCount, &piSize)) )
1387             {
1388                 BYTE *pSCC= (BYTE *)CoTaskMemAlloc(piSize);
1389                 if( NULL != pSCC )
1390                 {
1391                     int i_priority = ES_PRIORITY_NOT_DEFAULTABLE;
1392                     for( int i=0; i<piCount; ++i )
1393                     {
1394                         if( SUCCEEDED(pSC->GetStreamCaps(i, &p_mt, pSCC)) )
1395                         {
1396                             int i_current_fourcc = GetFourCCFromMediaType( *p_mt );
1397                             int i_current_priority = GetFourCCPriority(i_current_fourcc);
1398
1399                             if( (i_fourcc && (i_current_fourcc != i_fourcc))
1400                              || (i_priority > i_current_priority) )
1401                             {
1402                                 // unwanted chroma, try next media type
1403                                 FreeMediaType( *p_mt );
1404                                 CoTaskMemFree( (PVOID)p_mt );
1405                                 continue;
1406                             }
1407
1408                             if( !b_audio && MEDIATYPE_Video == p_mt->majortype
1409                                     && FORMAT_VideoInfo == p_mt->formattype )
1410                             {
1411                                 VIDEO_STREAM_CONFIG_CAPS *pVSCC = reinterpret_cast<VIDEO_STREAM_CONFIG_CAPS*>(pSCC);
1412                                 VIDEOINFOHEADER *pVih = reinterpret_cast<VIDEOINFOHEADER*>(p_mt->pbFormat);
1413
1414                                 if( i_AvgTimePerFrame )
1415                                 {
1416                                     if( pVSCC->MinFrameInterval > i_AvgTimePerFrame
1417                                       || i_AvgTimePerFrame > pVSCC->MaxFrameInterval )
1418                                     {
1419                                         // required frame rate not compatible, try next media type
1420                                         FreeMediaType( *p_mt );
1421                                         CoTaskMemFree( (PVOID)p_mt );
1422                                         continue;
1423                                     }
1424                                     pVih->AvgTimePerFrame = i_AvgTimePerFrame;
1425                                 }
1426
1427                                 if( i_width )
1428                                 {
1429                                     if((   !pVSCC->OutputGranularityX
1430                                            && i_width != pVSCC->MinOutputSize.cx
1431                                            && i_width != pVSCC->MaxOutputSize.cx)
1432                                        ||
1433                                        (   pVSCC->OutputGranularityX
1434                                            && ((i_width % pVSCC->OutputGranularityX)
1435                                                || pVSCC->MinOutputSize.cx > i_width
1436                                                || i_width > pVSCC->MaxOutputSize.cx )))
1437                                     {
1438                                         // required width not compatible, try next media type
1439                                         FreeMediaType( *p_mt );
1440                                         CoTaskMemFree( (PVOID)p_mt );
1441                                         continue;
1442                                     }
1443                                     pVih->bmiHeader.biWidth = i_width;
1444                                 }
1445
1446                                 if( i_height )
1447                                 {
1448                                     if((   !pVSCC->OutputGranularityY
1449                                            && i_height != pVSCC->MinOutputSize.cy
1450                                            && i_height != pVSCC->MaxOutputSize.cy)
1451                                        ||
1452                                        (   pVSCC->OutputGranularityY
1453                                            && ((i_height % pVSCC->OutputGranularityY)
1454                                                || pVSCC->MinOutputSize.cy > i_height
1455                                                || i_height > pVSCC->MaxOutputSize.cy )))
1456                                     {
1457                                         // required height not compatible, try next media type
1458                                         FreeMediaType( *p_mt );
1459                                         CoTaskMemFree( (PVOID)p_mt );
1460                                         continue;
1461                                     }
1462                                     pVih->bmiHeader.biHeight = i_height;
1463                                 }
1464
1465                                 // Set the sample size and image size.
1466                                 // (Round the image width up to a DWORD boundary.)
1467                                 p_mt->lSampleSize = pVih->bmiHeader.biSizeImage =
1468                                     ((pVih->bmiHeader.biWidth + 3) & ~3) *
1469                                     pVih->bmiHeader.biHeight * (pVih->bmiHeader.biBitCount>>3);
1470
1471                                 // no cropping, use full video input buffer
1472                                 memset(&(pVih->rcSource), 0, sizeof(RECT));
1473                                 memset(&(pVih->rcTarget), 0, sizeof(RECT));
1474
1475                                 // select this format as default
1476                                 if( SUCCEEDED( pSC->SetFormat(p_mt) ) )
1477                                 {
1478                                     i_priority = i_current_priority;
1479                                     if( i_fourcc )
1480                                         // no need to check any more media types
1481                                         i = piCount;
1482                                 }
1483                             }
1484                             else if( b_audio && p_mt->majortype == MEDIATYPE_Audio
1485                                     && p_mt->formattype == FORMAT_WaveFormatEx )
1486                             {
1487                                 AUDIO_STREAM_CONFIG_CAPS *pASCC = reinterpret_cast<AUDIO_STREAM_CONFIG_CAPS*>(pSCC);
1488                                 WAVEFORMATEX *pWfx = reinterpret_cast<WAVEFORMATEX*>(p_mt->pbFormat);
1489
1490                                 if( i_current_fourcc && (WAVE_FORMAT_PCM == pWfx->wFormatTag) )
1491                                 {
1492                                     int val = i_channels;
1493                                     if( ! val )
1494                                         val = 2;
1495
1496                                     if( (   !pASCC->ChannelsGranularity
1497                                             && (unsigned int)val != pASCC->MinimumChannels
1498                                             && (unsigned int)val != pASCC->MaximumChannels)
1499                                         ||
1500                                         (   pASCC->ChannelsGranularity
1501                                             && ((val % pASCC->ChannelsGranularity)
1502                                                 || (unsigned int)val < pASCC->MinimumChannels
1503                                                 || (unsigned int)val > pASCC->MaximumChannels)))
1504                                     {
1505                                         // required number channels not available, try next media type
1506                                         FreeMediaType( *p_mt );
1507                                         CoTaskMemFree( (PVOID)p_mt );
1508                                         continue;
1509                                     }
1510                                     pWfx->nChannels = val;
1511
1512                                     val = i_samplespersec;
1513                                     if( ! val )
1514                                         val = 44100;
1515
1516                                     if( (   !pASCC->SampleFrequencyGranularity
1517                                             && (unsigned int)val != pASCC->MinimumSampleFrequency
1518                                             && (unsigned int)val != pASCC->MaximumSampleFrequency)
1519                                         ||
1520                                         (   pASCC->SampleFrequencyGranularity
1521                                             && ((val % pASCC->SampleFrequencyGranularity)
1522                                                 || (unsigned int)val < pASCC->MinimumSampleFrequency
1523                                                 || (unsigned int)val > pASCC->MaximumSampleFrequency )))
1524                                     {
1525                                         // required sampling rate not available, try next media type
1526                                         FreeMediaType( *p_mt );
1527                                         CoTaskMemFree( (PVOID)p_mt );
1528                                         continue;
1529                                     }
1530                                     pWfx->nSamplesPerSec = val;
1531
1532                                     val = i_bitspersample;
1533                                     if( ! val )
1534                                     {
1535                                         if( VLC_CODEC_FL32 == i_current_fourcc )
1536                                             val = 32;
1537                                         else
1538                                             val = 16;
1539                                     }
1540
1541                                     if( (   !pASCC->BitsPerSampleGranularity
1542                                             && (unsigned int)val != pASCC->MinimumBitsPerSample
1543                                             && (unsigned int)val != pASCC->MaximumBitsPerSample )
1544                                         ||
1545                                         (   pASCC->BitsPerSampleGranularity
1546                                             && ((val % pASCC->BitsPerSampleGranularity)
1547                                                 || (unsigned int)val < pASCC->MinimumBitsPerSample
1548                                                 || (unsigned int)val > pASCC->MaximumBitsPerSample )))
1549                                     {
1550                                         // required sample size not available, try next media type
1551                                         FreeMediaType( *p_mt );
1552                                         CoTaskMemFree( (PVOID)p_mt );
1553                                         continue;
1554                                     }
1555
1556                                     pWfx->wBitsPerSample = val;
1557                                     pWfx->nBlockAlign = (pWfx->wBitsPerSample * pWfx->nChannels)/8;
1558                                     pWfx->nAvgBytesPerSec = pWfx->nSamplesPerSec * pWfx->nBlockAlign;
1559
1560                                     // select this format as default
1561                                     if( SUCCEEDED( pSC->SetFormat(p_mt) ) )
1562                                     {
1563                                         i_priority = i_current_priority;
1564                                     }
1565                                 }
1566                             }
1567                             FreeMediaType( *p_mt );
1568                             CoTaskMemFree( (PVOID)p_mt );
1569                         }
1570                     }
1571                     CoTaskMemFree( (LPVOID)pSCC );
1572                     if( i_priority >= ES_PRIORITY_SELECTABLE_MIN )
1573                         msg_Dbg( p_this, "EnumDeviceCaps: input pin default format configured");
1574                 }
1575             }
1576         }
1577
1578         /*
1579         ** Probe pin for available medias (may be a previously configured one)
1580         */
1581
1582         if( FAILED( p_output_pin->EnumMediaTypes( p_enummt.ReleaseAndGetAddressOf() ) ) )
1583         {
1584             continue;
1585         }
1586
1587         while( p_enummt->Next( 1, &p_mt, NULL ) == S_OK )
1588         {
1589             int i_current_fourcc = GetFourCCFromMediaType( *p_mt );
1590             if( !b_audio && i_current_fourcc && p_mt->majortype == MEDIATYPE_Video
1591                 && p_mt->formattype == FORMAT_VideoInfo )
1592             {
1593                 int i_current_width = ((VIDEOINFOHEADER *)p_mt->pbFormat)->bmiHeader.biWidth;
1594                 int i_current_height = ((VIDEOINFOHEADER *)p_mt->pbFormat)->bmiHeader.biHeight;
1595                 LONGLONG i_current_atpf = ((VIDEOINFOHEADER *)p_mt->pbFormat)->AvgTimePerFrame;
1596
1597                 if( i_current_height < 0 )
1598                     i_current_height = -i_current_height;
1599
1600                 msg_Dbg( p_this, "EnumDeviceCaps: input pin "
1601                          "accepts chroma: %4.4s, width:%i, height:%i, fps:%f",
1602                          (char *)&i_current_fourcc, i_current_width,
1603                          i_current_height, (10000000.0f/((float)i_current_atpf)) );
1604
1605                 if( ( !i_fourcc || i_fourcc == i_current_fourcc ) &&
1606                     ( !i_width || i_width == i_current_width ) &&
1607                     ( !i_height || i_height == i_current_height ) &&
1608                     ( !i_AvgTimePerFrame || i_AvgTimePerFrame == i_current_atpf ) &&
1609                     mt_count < mt_max )
1610                 {
1611                     /* Pick match */
1612                     mt[mt_count++] = *p_mt;
1613                 }
1614                 else FreeMediaType( *p_mt );
1615             }
1616             else if( b_audio && i_current_fourcc && p_mt->majortype == MEDIATYPE_Audio
1617                     && p_mt->formattype == FORMAT_WaveFormatEx)
1618             {
1619                 int i_current_channels =
1620                     ((WAVEFORMATEX *)p_mt->pbFormat)->nChannels;
1621                 int i_current_samplespersec =
1622                     ((WAVEFORMATEX *)p_mt->pbFormat)->nSamplesPerSec;
1623                 int i_current_bitspersample =
1624                     ((WAVEFORMATEX *)p_mt->pbFormat)->wBitsPerSample;
1625
1626                 msg_Dbg( p_this, "EnumDeviceCaps: input pin "
1627                          "accepts format: %4.4s, channels:%i, "
1628                          "samples/sec:%i bits/sample:%i",
1629                          (char *)&i_current_fourcc, i_current_channels,
1630                          i_current_samplespersec, i_current_bitspersample);
1631
1632                 if( (!i_channels || i_channels == i_current_channels) &&
1633                     (!i_samplespersec ||
1634                      i_samplespersec == i_current_samplespersec) &&
1635                     (!i_bitspersample ||
1636                      i_bitspersample == i_current_bitspersample) &&
1637                     mt_count < mt_max )
1638                 {
1639                     /* Pick  match */
1640                     mt[mt_count++] = *p_mt;
1641
1642                     /* Setup a few properties like the audio latency */
1643                     ComPtr<IAMBufferNegotiation> p_ambuf;
1644                     if( SUCCEEDED( p_output_pin->QueryInterface(
1645                           IID_IAMBufferNegotiation, (void **)p_ambuf.GetAddressOf() ) ) )
1646                     {
1647                         ALLOCATOR_PROPERTIES AllocProp;
1648                         AllocProp.cbAlign = -1;
1649
1650                         /* 100 ms of latency */
1651                         AllocProp.cbBuffer = i_current_channels *
1652                           i_current_samplespersec *
1653                           i_current_bitspersample / 8 / 10;
1654
1655                         AllocProp.cbPrefix = -1;
1656                         AllocProp.cBuffers = -1;
1657                         p_ambuf->SuggestAllocatorProperties( &AllocProp );
1658                     }
1659                 }
1660                 else FreeMediaType( *p_mt );
1661             }
1662             else if( i_current_fourcc && p_mt->majortype == MEDIATYPE_Stream )
1663             {
1664                 msg_Dbg( p_this, "EnumDeviceCaps: input pin "
1665                          "accepts stream format: %4.4s",
1666                          (char *)&i_current_fourcc );
1667
1668                 if( ( !i_fourcc || i_fourcc == i_current_fourcc ) &&
1669                     mt_count < mt_max )
1670                 {
1671                     /* Pick match */
1672                     mt[mt_count++] = *p_mt;
1673                     i_fourcc = i_current_fourcc;
1674                 }
1675                 else FreeMediaType( *p_mt );
1676             }
1677             else
1678             {
1679                 const char * psz_type = "unknown";
1680                 if( p_mt->majortype == MEDIATYPE_Video ) psz_type = "video";
1681                 if( p_mt->majortype == MEDIATYPE_Audio ) psz_type = "audio";
1682                 if( p_mt->majortype == MEDIATYPE_Stream ) psz_type = "stream";
1683                 msg_Dbg( p_this, "EnumDeviceCaps: input pin media: unsupported format "
1684                          "(%s %4.4s)", psz_type, (char *)&p_mt->subtype );
1685
1686                 FreeMediaType( *p_mt );
1687             }
1688             CoTaskMemFree( (PVOID)p_mt );
1689         }
1690
1691         if( !mt_count && p_enummt->Reset() == S_OK )
1692         {
1693             // VLC did not find any supported MEDIATYPE for this output pin.
1694             // However the graph builder might insert converter filters in
1695             // the graph if we use a different codec in VLC filter input pin.
1696             // however, in order to avoid nasty surprises, make use of this
1697             // facility only for known unsupported codecs.
1698
1699             while( !mt_count && p_enummt->Next( 1, &p_mt, NULL ) == S_OK )
1700             {
1701                 // the first four bytes of subtype GUID contains the codec FOURCC
1702                 const char *pfcc = (char *)&p_mt->subtype;
1703                 int i_current_fourcc = VLC_FOURCC(pfcc[0], pfcc[1], pfcc[2], pfcc[3]);
1704                 if( VLC_FOURCC('H','C','W','2') == i_current_fourcc
1705                  && p_mt->majortype == MEDIATYPE_Video && !b_audio )
1706                 {
1707                     // output format for 'Hauppauge WinTV PVR PCI II Capture'
1708                     // try I420 as an input format
1709                     i_current_fourcc = VLC_CODEC_I420;
1710                     if( !i_fourcc || i_fourcc == i_current_fourcc )
1711                     {
1712                         // return alternative media type
1713                         AM_MEDIA_TYPE mtr;
1714                         VIDEOINFOHEADER vh;
1715
1716                         mtr.majortype            = MEDIATYPE_Video;
1717                         mtr.subtype              = MEDIASUBTYPE_I420;
1718                         mtr.bFixedSizeSamples    = TRUE;
1719                         mtr.bTemporalCompression = FALSE;
1720                         mtr.pUnk                 = NULL;
1721                         mtr.formattype           = FORMAT_VideoInfo;
1722                         mtr.cbFormat             = sizeof(vh);
1723                         mtr.pbFormat             = (BYTE *)&vh;
1724
1725                         memset(&vh, 0, sizeof(vh));
1726
1727                         vh.bmiHeader.biSize   = sizeof(vh.bmiHeader);
1728                         vh.bmiHeader.biWidth  = i_width > 0 ? i_width :
1729                             ((VIDEOINFOHEADER *)p_mt->pbFormat)->bmiHeader.biWidth;
1730                         vh.bmiHeader.biHeight = i_height > 0 ? i_height :
1731                             ((VIDEOINFOHEADER *)p_mt->pbFormat)->bmiHeader.biHeight;
1732                         vh.bmiHeader.biPlanes      = 3;
1733                         vh.bmiHeader.biBitCount    = 12;
1734                         vh.bmiHeader.biCompression = VLC_CODEC_I420;
1735                         vh.bmiHeader.biSizeImage   = vh.bmiHeader.biWidth * 12 *
1736                             vh.bmiHeader.biHeight / 8;
1737                         mtr.lSampleSize            = vh.bmiHeader.biSizeImage;
1738
1739                         msg_Dbg( p_this, "EnumDeviceCaps: input pin media: using 'I420' in place of unsupported format 'HCW2'");
1740
1741                         if( SUCCEEDED(CopyMediaType(mt+mt_count, &mtr)) )
1742                             ++mt_count;
1743                     }
1744                 }
1745                 FreeMediaType( *p_mt );
1746             }
1747         }
1748     }
1749
1750     return mt_count;
1751 }
1752
1753 /*****************************************************************************
1754  * ReadCompressed: reads compressed (MPEG/DV) data from the device.
1755  *****************************************************************************/
1756 static block_t *ReadCompressed( stream_t *p_access, bool *eof )
1757 {
1758     ComContext ctx( COINIT_MULTITHREADED );
1759
1760     access_sys_t   *p_sys = (access_sys_t *)p_access->p_sys;
1761     /* There must be only 1 elementary stream to produce a valid stream
1762      * of MPEG or DV data */
1763     dshow_stream_t *p_stream = p_sys->pp_streams[0];
1764     VLCMediaSample sample;
1765
1766     /* Read 1 DV/MPEG frame (they contain the video and audio data) */
1767
1768     /* Get new sample/frame from the elementary stream (blocking). */
1769     vlc_mutex_lock( &p_sys->lock );
1770
1771     if( p_stream->p_capture_filter->CustomGetPin()->CustomGetSample(&sample) != S_OK )
1772     {   /* No data available. Wait until some data has arrived */
1773         vlc_cond_wait( &p_sys->wait, &p_sys->lock );
1774         vlc_mutex_unlock( &p_sys->lock );
1775         return NULL;
1776     }
1777     vlc_mutex_unlock( &p_sys->lock );
1778
1779     /*
1780      * We got our sample
1781      */
1782     block_t *p_block = NULL;
1783     uint8_t *p_data;
1784     int i_data_size = sample.p_sample->GetActualDataLength();
1785     if( i_data_size == 0 )
1786         goto out;
1787
1788     p_block = block_Alloc( i_data_size );
1789     if( unlikely(p_block == NULL) )
1790         goto out;
1791
1792     sample.p_sample->GetPointer( &p_data );
1793     memcpy( p_block->p_buffer, p_data, i_data_size );
1794     /* The caller got what he wanted */
1795 out:
1796     (void) eof;
1797     return p_block;
1798 }
1799
1800 /****************************************************************************
1801  * Demux:
1802  ****************************************************************************/
1803 static int Demux( demux_t *p_demux )
1804 {
1805     ComContext ctx( COINIT_MULTITHREADED );
1806
1807     access_sys_t *p_sys = (access_sys_t *)p_demux->p_sys;
1808     int i_found_samples;
1809
1810     i_found_samples = 0;
1811     vlc_mutex_lock( &p_sys->lock );
1812
1813     while ( !i_found_samples )
1814     {
1815         /* Try to grab samples from all streams */
1816         std::vector<dshow_stream_t*>::iterator it = p_sys->pp_streams.begin();
1817         std::vector<dshow_stream_t*>::iterator end = p_sys->pp_streams.end();
1818         for ( ; it != end; ++it )
1819         {
1820             dshow_stream_t *p_stream = *it;
1821             if( p_stream->p_capture_filter &&
1822                 p_stream->p_capture_filter->CustomGetPin()
1823                 ->CustomGetSamples( p_stream->samples_queue ) == S_OK )
1824             {
1825                 i_found_samples = 1;
1826             }
1827         }
1828
1829         if ( !i_found_samples)
1830         {
1831             /* Didn't find any audio nor video sample, just wait till the
1832              * dshow thread pushes some samples */
1833             vlc_cond_wait( &p_sys->wait, &p_sys->lock );
1834             /* Some DShow thread pushed data, or the OS broke the wait all
1835              * by itself. In all cases, it's *strongly* advised to test the
1836              * condition again, so let the loop do the test again */
1837         }
1838     }
1839
1840     vlc_mutex_unlock( &p_sys->lock );
1841
1842     std::vector<dshow_stream_t*>::iterator it = p_sys->pp_streams.begin();
1843     std::vector<dshow_stream_t*>::iterator end = p_sys->pp_streams.end();
1844     for ( ; it != end; ++it )
1845     {
1846         int i_samples;
1847         dshow_stream_t *p_stream = *it;
1848
1849         i_samples = p_stream->samples_queue.size();
1850         while ( i_samples > 0 )
1851         {
1852             int i_data_size;
1853             uint8_t *p_data;
1854             block_t *p_block;
1855             VLCMediaSample sample;
1856
1857             sample = p_stream->samples_queue.front();
1858             p_stream->samples_queue.pop_front();
1859
1860             i_data_size = sample.p_sample->GetActualDataLength();
1861             sample.p_sample->GetPointer( &p_data );
1862
1863             REFERENCE_TIME i_pts, i_end_date;
1864             HRESULT hr = sample.p_sample->GetTime( &i_pts, &i_end_date );
1865             if( hr != S_OK && hr != VFW_S_NO_STOP_TIME )
1866             {
1867                 if( p_stream->mt.majortype == MEDIATYPE_Video || !p_stream->b_pts )
1868                 {
1869                     /* Use our data timestamp */
1870                     i_pts = MSFTIME_FROM_VLC_TICK(sample.i_timestamp);
1871                     p_stream->b_pts = true;
1872                 }
1873                 else
1874                     i_pts = LONG_MIN;
1875             }
1876
1877             if( i_pts != LONG_MIN ) {
1878                 i_pts += 5;
1879             }
1880 #if 0
1881             msg_Dbg( p_demux, "Read() stream: %i, size: %i, PTS: %" PRId64,
1882                      i_stream, i_data_size, VLC_TICK_FROM_MSFTIME(i_pts) );
1883 #endif
1884
1885             p_block = block_Alloc( i_data_size );
1886             memcpy( p_block->p_buffer, p_data, i_data_size );
1887             p_block->i_pts = p_block->i_dts = i_pts == LONG_MIN ?
1888                         VLC_TICK_INVALID : (VLC_TICK_FROM_MSFTIME(i_pts) + VLC_TICK_0);
1889
1890             if( p_block->i_pts != VLC_TICK_INVALID )
1891                 es_out_SetPCR( p_demux->out, p_block->i_pts );
1892             es_out_Send( p_demux->out, p_stream->p_es, p_block );
1893
1894             i_samples--;
1895         }
1896     }
1897
1898     return 1;
1899 }
1900
1901 /*****************************************************************************
1902  * AccessControl:
1903  *****************************************************************************/
1904 static int AccessControl( stream_t *p_access, int i_query, va_list args )
1905 {
1906     access_sys_t *sys = (access_sys_t *)p_access->p_sys;
1907     bool    *pb_bool;
1908
1909     switch( i_query )
1910     {
1911     case STREAM_CAN_SEEK:
1912     case STREAM_CAN_FASTSEEK:
1913     case STREAM_CAN_PAUSE:
1914     case STREAM_CAN_CONTROL_PACE:
1915         pb_bool = va_arg( args, bool * );
1916         *pb_bool = false;
1917         break;
1918
1919     case STREAM_GET_PTS_DELAY:
1920         *va_arg( args, vlc_tick_t * ) =
1921             VLC_TICK_FROM_MS( var_InheritInteger( p_access, "live-caching" ) );
1922         break;
1923
1924     case STREAM_GET_CONTENT_TYPE:
1925     {
1926         dshow_stream_t *p_stream = sys->pp_streams[0];
1927         char **type = va_arg( args, char ** );
1928
1929         /* Check if we need to force demuxers */
1930         if( p_stream->i_fourcc == VLC_CODEC_DV )
1931             *type = strdup( "video/dv" );
1932         else if( p_stream->i_fourcc == VLC_CODEC_MPGV )
1933             *type = strdup( "video/MP2P" );
1934         else
1935             return VLC_EGENERIC;
1936         break;
1937     }
1938
1939     default:
1940         return VLC_EGENERIC;
1941     }
1942
1943     return VLC_SUCCESS;
1944 }
1945
1946 /****************************************************************************
1947  * DemuxControl:
1948  ****************************************************************************/
1949 static int DemuxControl( demux_t *p_demux, int i_query, va_list args )
1950 {
1951     bool    *pb;
1952     int64_t *pi64;
1953
1954     access_sys_t *p_sys = ( access_sys_t * ) p_demux->p_sys;
1955
1956     switch( i_query )
1957     {
1958     /* Special for access_demux */
1959     case DEMUX_CAN_PAUSE:
1960     case DEMUX_CAN_SEEK:
1961     case DEMUX_SET_PAUSE_STATE:
1962     case DEMUX_CAN_CONTROL_PACE:
1963         pb = va_arg( args, bool * );
1964         *pb = false;
1965         return VLC_SUCCESS;
1966
1967     case DEMUX_GET_PTS_DELAY:
1968         *va_arg( args, vlc_tick_t * ) =
1969             VLC_TICK_FROM_MS( var_InheritInteger( p_demux, "live-caching" ) );
1970         return VLC_SUCCESS;
1971
1972     case DEMUX_GET_TIME:
1973         pi64 = va_arg( args, int64_t * );
1974         *pi64 = vlc_tick_now() - p_sys->i_start;
1975         return VLC_SUCCESS;
1976
1977     /* TODO implement others */
1978     default:
1979         return VLC_EGENERIC;
1980     }
1981
1982     return VLC_EGENERIC;
1983 }
1984
1985 static int AppendAudioEnabledVDevs( vlc_object_t *p_this, std::list<std::string> &audio_list,
1986                                     std::list<std::string> &video_list )
1987 {
1988     ComPtr<IFilterGraph> p_graph;
1989     ComPtr<IGraphBuilder> p_gbuilder;
1990     ComPtr<ICaptureGraphBuilder2> p_cgbuilder;
1991
1992     if( FAILED( CoCreateInstance( CLSID_FilterGraph, NULL, CLSCTX_INPROC_SERVER, IID_IFilterGraph,
1993                                   ( void ** ) p_graph.GetAddressOf() ) ) )
1994         return VLC_EGENERIC;
1995
1996     if( FAILED( p_graph->QueryInterface( IID_IGraphBuilder, ( void ** ) p_gbuilder.GetAddressOf() ) ) )
1997         return VLC_EGENERIC;
1998
1999     if( FAILED( CoCreateInstance( CLSID_CaptureGraphBuilder2, NULL, CLSCTX_INPROC_SERVER,
2000                                   IID_ICaptureGraphBuilder2, ( void ** ) p_cgbuilder.GetAddressOf() ) ) )
2001         return VLC_EGENERIC;
2002
2003     if( FAILED( p_cgbuilder->SetFiltergraph( p_gbuilder.Get() ) ) )
2004         return VLC_EGENERIC;
2005
2006     for( std::list<std::string>::iterator iter = video_list.begin();
2007          iter != video_list.end();
2008          ++iter )
2009     {
2010         ComPtr<IBaseFilter> p_device;
2011         ComPtr<IPin> p_pin;
2012
2013         p_device = FindCaptureDevice( p_this, &( *iter ), NULL, false );
2014         if( !p_device ) continue;
2015
2016         if( FAILED( p_gbuilder->AddFilter( p_device.Get(), NULL ) ) )
2017             continue;
2018
2019         if( SUCCEEDED( p_cgbuilder->FindPin( p_device.Get(), PINDIR_OUTPUT, NULL, &MEDIATYPE_Audio,
2020                                             true, 0, p_pin.GetAddressOf() ) ) )
2021             audio_list.push_back( *iter );
2022
2023         p_gbuilder->RemoveFilter( p_device.Get() );
2024     }
2025
2026     return VLC_SUCCESS;
2027 }
2028
2029 /*****************************************************************************
2030  * config variable callback
2031  *****************************************************************************/
2032 static int FindDevices( const char *psz_name, char ***vp, char ***tp )
2033 {
2034     /* Find list of devices */
2035     std::list<std::string> list_devices;
2036     try
2037     {
2038         bool b_audio = !strcmp( psz_name, "dshow-adev" );
2039
2040         // Use STA as this most likely comes from a Qt thread, which is
2041         // initialized as STA.
2042         ComContext ctx( COINIT_APARTMENTTHREADED );
2043
2044         FindCaptureDevice( NULL, NULL, &list_devices, b_audio );
2045
2046         if( b_audio )
2047         {
2048             std::list<std::string> list_vdevs;
2049             FindCaptureDevice( NULL, NULL, &list_vdevs, false );
2050             if( !list_vdevs.empty() )
2051                 AppendAudioEnabledVDevs( NULL, list_devices, list_vdevs );
2052         }
2053     }
2054     catch (const std::runtime_error& ex)
2055     {
2056         msg_Err( (vlc_object_t *)NULL, "Failed fetch devices: %s", ex.what() );
2057     }
2058
2059     unsigned count = 2 + list_devices.size(), i = 2;
2060     char **values = (char **)xmalloc( count * sizeof(*values) );
2061     char **texts = (char **)xmalloc( count * sizeof(*texts) );
2062
2063     values[0] = strdup( "" );
2064     texts[0] = strdup( _("Default") );
2065     values[1] = strdup( "none" );
2066     texts[1] = strdup( _("None") );
2067
2068     for( std::list<std::string>::iterator iter = list_devices.begin();
2069          iter != list_devices.end();
2070          ++iter )
2071     {
2072         assert( i < count );
2073         values[i] = strdup( iter->c_str() );
2074         texts[i] = strdup( iter->c_str() );
2075         i++;
2076     }
2077
2078     *vp = values;
2079     *tp = texts;
2080     return count;
2081 }
2082
2083 /*****************************************************************************
2084  * Properties
2085  *****************************************************************************/
2086
2087 static void ShowPropertyPage( IUnknown *obj )
2088 {
2089     ComPtr<ISpecifyPropertyPages> p_spec;
2090     CAUUID cauuid;
2091
2092     HRESULT hr = obj->QueryInterface( IID_ISpecifyPropertyPages,
2093                                       (void **)p_spec.GetAddressOf() );
2094     if( FAILED(hr) ) return;
2095
2096     if( SUCCEEDED(p_spec->GetPages( &cauuid )) )
2097     {
2098         if( cauuid.cElems > 0 )
2099         {
2100             HWND hwnd_desktop = ::GetDesktopWindow();
2101
2102             OleCreatePropertyFrame( hwnd_desktop, 30, 30, NULL, 1, &obj,
2103                                     cauuid.cElems, cauuid.pElems, 0, 0, NULL );
2104
2105             CoTaskMemFree( cauuid.pElems );
2106         }
2107     }
2108 }
2109
2110 static void ShowDeviceProperties( vlc_object_t *p_this,
2111                                   ICaptureGraphBuilder2 *p_graph,
2112                                   IBaseFilter *p_device_filter,
2113                                   bool b_audio )
2114 {
2115     HRESULT hr;
2116     msg_Dbg( p_this, "configuring Device Properties" );
2117
2118     /*
2119      * Video or audio capture filter page
2120      */
2121     ShowPropertyPage( p_device_filter );
2122
2123     /*
2124      * Audio capture pin
2125      */
2126     if( p_graph && b_audio )
2127     {
2128         ComPtr<IAMStreamConfig> p_SC;
2129
2130         msg_Dbg( p_this, "showing WDM Audio Configuration Pages" );
2131
2132         hr = p_graph->FindInterface( &PIN_CATEGORY_CAPTURE,
2133                                      &MEDIATYPE_Audio, p_device_filter,
2134                                      IID_IAMStreamConfig, (void **)p_SC.GetAddressOf() );
2135         if( SUCCEEDED(hr) )
2136         {
2137             ShowPropertyPage(p_SC.Get());
2138         }
2139
2140         /*
2141          * TV Audio filter
2142          */
2143         ComPtr<IAMTVAudio> p_TVA;
2144         HRESULT hr = p_graph->FindInterface( &PIN_CATEGORY_CAPTURE,
2145                                              &MEDIATYPE_Audio, p_device_filter,
2146                                              IID_IAMTVAudio, (void **)p_TVA.GetAddressOf() );
2147         if( SUCCEEDED(hr) )
2148         {
2149             ShowPropertyPage(p_TVA.Get());
2150         }
2151     }
2152
2153     /*
2154      * Video capture pin
2155      */
2156     if( p_graph && !b_audio )
2157     {
2158         ComPtr<IAMStreamConfig> p_SC;
2159
2160         msg_Dbg( p_this, "showing WDM Video Configuration Pages" );
2161
2162         hr = p_graph->FindInterface( &PIN_CATEGORY_CAPTURE,
2163                                      &MEDIATYPE_Interleaved, p_device_filter,
2164                                      IID_IAMStreamConfig, (void **)p_SC.GetAddressOf() );
2165         if( FAILED(hr) )
2166         {
2167             hr = p_graph->FindInterface( &PIN_CATEGORY_CAPTURE,
2168                                          &MEDIATYPE_Video, p_device_filter,
2169                                          IID_IAMStreamConfig, (void **)p_SC.GetAddressOf() );
2170         }
2171
2172         if( FAILED(hr) )
2173         {
2174             hr = p_graph->FindInterface( &PIN_CATEGORY_CAPTURE,
2175                                          &MEDIATYPE_Stream, p_device_filter,
2176                                          IID_IAMStreamConfig, (void **)p_SC.GetAddressOf() );
2177         }
2178
2179         if( SUCCEEDED(hr) )
2180         {
2181             ShowPropertyPage(p_SC.Get());
2182         }
2183     }
2184 }
2185
2186 static void ShowTunerProperties( vlc_object_t *p_this,
2187                                  ICaptureGraphBuilder2 *p_graph,
2188                                  IBaseFilter *p_device_filter,
2189                                  bool b_audio )
2190 {
2191     HRESULT hr;
2192     msg_Dbg( p_this, "configuring Tuner Properties" );
2193
2194     if( !p_graph || b_audio ) return;
2195
2196     ComPtr<IAMTVTuner> p_TV;
2197     hr = p_graph->FindInterface( &PIN_CATEGORY_CAPTURE,
2198                                  &MEDIATYPE_Interleaved, p_device_filter,
2199                                  IID_IAMTVTuner, (void **)p_TV.GetAddressOf() );
2200     if( FAILED(hr) )
2201     {
2202         hr = p_graph->FindInterface( &PIN_CATEGORY_CAPTURE,
2203                                      &MEDIATYPE_Video, p_device_filter,
2204                                      IID_IAMTVTuner, (void **)p_TV.GetAddressOf() );
2205     }
2206
2207     if( FAILED(hr) )
2208     {
2209         hr = p_graph->FindInterface( &PIN_CATEGORY_CAPTURE,
2210                                      &MEDIATYPE_Stream, p_device_filter,
2211                                      IID_IAMTVTuner, (void **)p_TV.GetAddressOf() );
2212     }
2213
2214     if( SUCCEEDED(hr) )
2215     {
2216         ShowPropertyPage(p_TV.Get());
2217     }
2218 }
2219
2220 static void ConfigTuner( vlc_object_t *p_this, ICaptureGraphBuilder2 *p_graph,
2221                          IBaseFilter *p_device_filter )
2222 {
2223     int i_channel, i_country, i_input, i_amtuner_mode;
2224     long l_modes = 0;
2225     unsigned i_frequency;
2226     ComPtr<IAMTVTuner> p_TV;
2227     HRESULT hr;
2228
2229     if( !p_graph ) return;
2230
2231     i_channel = var_GetInteger( p_this, "dshow-tuner-channel" );
2232     i_country = var_GetInteger( p_this, "dshow-tuner-country" );
2233     i_input = var_GetInteger( p_this, "dshow-tuner-input" );
2234     i_amtuner_mode = var_GetInteger( p_this, "dshow-amtuner-mode" );
2235
2236     if( !i_channel && !i_country && !i_input ) return; /* Nothing to do */
2237
2238     msg_Dbg( p_this, "tuner config: channel %i, country %i, input type %i",
2239              i_channel, i_country, i_input );
2240
2241     hr = p_graph->FindInterface( &PIN_CATEGORY_CAPTURE, &MEDIATYPE_Interleaved,
2242                                  p_device_filter, IID_IAMTVTuner,
2243                                  (void **)p_TV.GetAddressOf() );
2244     if( FAILED(hr) )
2245     {
2246         hr = p_graph->FindInterface( &PIN_CATEGORY_CAPTURE, &MEDIATYPE_Video,
2247                                      p_device_filter, IID_IAMTVTuner,
2248                                      (void **)p_TV.GetAddressOf() );
2249     }
2250
2251     if( FAILED(hr) )
2252     {
2253         hr = p_graph->FindInterface( &PIN_CATEGORY_CAPTURE, &MEDIATYPE_Stream,
2254                                      p_device_filter, IID_IAMTVTuner,
2255                                      (void **)p_TV.GetAddressOf() );
2256     }
2257
2258     if( FAILED(hr) )
2259     {
2260         msg_Dbg( p_this, "couldn't find tuner interface" );
2261         return;
2262     }
2263
2264     hr = p_TV->GetAvailableModes( &l_modes );
2265     if( SUCCEEDED(hr) && (l_modes & i_amtuner_mode) )
2266     {
2267         p_TV->put_Mode( (AMTunerModeType)i_amtuner_mode );
2268     }
2269
2270     if( i_input == 1 ) p_TV->put_InputType( 0, TunerInputCable );
2271     else if( i_input == 2 ) p_TV->put_InputType( 0, TunerInputAntenna );
2272
2273     p_TV->put_CountryCode( i_country );
2274     p_TV->put_Channel( i_channel, AMTUNER_SUBCHAN_NO_TUNE,
2275                        AMTUNER_SUBCHAN_NO_TUNE );
2276     p_TV->Release();
2277 }
2278
2279 } // namespace