Dshow: relicense to LGPL
[vlc.git] / modules / access / dshow / dshow.cpp
blob1c0702a9429e55167f592779c94d1efc233792c4
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$
7 * Author: Gildas Bazin <gbazin@videolan.org>
8 * Damien Fouilleul <damienf@videolan.org>
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.
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.
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 *****************************************************************************/
25 /*****************************************************************************
26 * Preamble
27 *****************************************************************************/
29 #ifdef HAVE_CONFIG_H
30 # include "config.h"
31 #endif
33 #include <inttypes.h>
34 #include <list>
35 #include <string>
36 #include <assert.h>
37 #include <stdexcept>
39 #include <vlc_common.h>
40 #include <vlc_plugin.h>
41 #include <vlc_access.h>
42 #include <vlc_demux.h>
44 #include <vlc_dialog.h> /* vlc_dialog_display_error */
45 #include <vlc_charset.h> /* FromWide */
47 #include <initguid.h>
48 #include "vlc_dshow.h"
50 #include "access.h"
51 #include "filter.h"
53 #include "../src/win32/mta_holder.h"
55 namespace dshow {
57 /*****************************************************************************
58 * Access: local prototypes
59 *****************************************************************************/
60 static block_t *ReadCompressed( stream_t *, bool * );
61 static int AccessControl ( stream_t *, int, va_list );
63 static int Demux ( demux_t * );
64 static int DemuxControl( demux_t *, int, va_list );
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 *** );
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 * );
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")};
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") };
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." )
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).")
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)" )
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)" )
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)" )
178 static int CommonOpen ( vlc_object_t *, access_sys_t *, bool );
179 static void CommonClose( vlc_object_t *, access_sys_t * );
181 static int AccessOpen ( vlc_object_t * );
182 static void AccessClose( vlc_object_t * );
184 static int DemuxOpen ( vlc_object_t * );
185 static void DemuxClose ( vlc_object_t * );
187 } // namespace
189 using namespace dshow;
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 )
199 add_string( "dshow-adev", NULL, ADEV_TEXT, ADEV_LONGTEXT, false)
200 change_string_cb( FindDevices )
202 add_string( "dshow-size", NULL, SIZE_TEXT, SIZE_LONGTEXT, false)
203 change_safe()
205 add_string( "dshow-aspect-ratio", "4:3", ASPECT_TEXT, ASPECT_LONGTEXT, false)
206 change_safe()
208 add_string( "dshow-chroma", NULL, CHROMA_TEXT, CHROMA_LONGTEXT, true )
209 change_safe()
211 add_float( "dshow-fps", 0.0f, FPS_TEXT, FPS_LONGTEXT, true )
212 change_safe()
214 add_bool( "dshow-config", false, CONFIG_TEXT, CONFIG_LONGTEXT, true )
216 add_bool( "dshow-tuner", false, TUNER_TEXT, TUNER_LONGTEXT, true )
218 add_integer( "dshow-tuner-channel", 0, CHANNEL_TEXT, CHANNEL_LONGTEXT,
219 true )
220 change_safe()
222 add_integer( "dshow-tuner-country", 0, COUNTRY_TEXT, COUNTRY_LONGTEXT,
223 true )
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()
230 add_integer( "dshow-video-input", -1, VIDEO_IN_TEXT,
231 VIDEO_IN_LONGTEXT, true )
232 change_safe()
234 add_integer( "dshow-video-output", -1, VIDEO_OUT_TEXT,
235 VIDEO_OUT_LONGTEXT, true )
237 add_integer( "dshow-audio-input", -1, AUDIO_IN_TEXT,
238 AUDIO_IN_LONGTEXT, true )
239 change_safe()
241 add_integer( "dshow-audio-output", -1, AUDIO_OUT_TEXT,
242 AUDIO_OUT_LONGTEXT, true )
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()
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 )
256 add_shortcut( "dshow" )
257 set_capability( "access", 1 )
258 set_callbacks( DemuxOpen, DemuxClose )
260 add_submodule ()
261 set_description( N_("DirectShow input") )
262 add_shortcut( "dshow" )
263 set_capability( "access", 0 )
264 set_callbacks( AccessOpen, AccessClose )
266 vlc_module_end ()
268 namespace dshow {
270 struct ComContext
272 ComContext( int mode )
274 if( FAILED( CoInitializeEx( NULL, mode ) ) )
275 throw std::runtime_error( "CoInitializeEx failed" );
277 ~ComContext()
279 CoUninitialize();
283 /*****************************************************************************
284 * DirectShow elementary stream descriptor
285 *****************************************************************************/
286 struct dshow_stream_t
288 std::string devicename;
289 ComPtr<IBaseFilter> p_device_filter;
290 ComPtr<CaptureFilter> p_capture_filter;
291 AM_MEDIA_TYPE mt;
293 union
295 VIDEOINFOHEADER video;
296 WAVEFORMATEX audio;
298 } header;
300 int i_fourcc;
301 es_out_id_t *p_es;
303 bool b_pts;
305 std::deque<VLCMediaSample> samples_queue;
308 /*****************************************************************************
309 * DirectShow utility functions
310 *****************************************************************************/
311 static void CreateDirectShowGraph( access_sys_t *p_sys )
313 p_sys->i_crossbar_route_depth = 0;
315 /* Create directshow filter graph */
316 if( SUCCEEDED( CoCreateInstance( CLSID_FilterGraph, 0, CLSCTX_INPROC,
317 (REFIID)IID_IFilterGraph, (void**)p_sys->p_graph.GetAddressOf() ) ) )
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() ) ) )
324 p_sys->p_capture_graph_builder2->
325 SetFiltergraph((IGraphBuilder *)p_sys->p_graph.Get() );
328 p_sys->p_graph->QueryInterface( IID_IMediaControl,
329 (void**)p_sys->p_control.GetAddressOf() );
333 static void DeleteDirectShowGraph( vlc_object_t *p_this, access_sys_t *p_sys )
335 DeleteCrossbarRoutes( p_sys );
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 )
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();
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();
354 /* Release directshow objects */
355 p_sys->p_control.Reset();
356 p_sys->p_capture_graph_builder2.Reset();
357 p_sys->p_graph.Reset();
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 )
366 char *psz_val;
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;
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 )
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 ;
387 free( psz_val );
389 psz_val = var_CreateGetString( p_this, "dshow-adev" );
390 if( psz_val )
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 ;
399 free( psz_val );
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 },
416 psz_val = var_CreateGetString( p_this, "dshow-size" );
417 if( !EMPTY_STR(psz_val) )
419 int i;
420 for( i = 0; size_table[i].psz_size; i++ )
422 if( !strcmp( psz_val, size_table[i].psz_size ) )
424 i_width = size_table[i].i_width;
425 i_height = size_table[i].i_height;
426 break;
429 if( !size_table[i].psz_size ) /* Try to parse "WidthxHeight" */
431 char *psz_parser;
432 i_width = strtol( psz_val, &psz_parser, 0 );
433 if( *psz_parser == 'x' || *psz_parser == 'X')
435 i_height = strtol( psz_parser + 1, &psz_parser, 0 );
437 msg_Dbg( p_this, "width x height %dx%d", i_width, i_height );
440 free( psz_val );
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 );
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 );
455 var_Create( p_this, "dshow-amtuner-mode",
456 VLC_VAR_INTEGER | VLC_VAR_DOINHERIT );
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 );
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;
469 /* Build directshow graph */
470 CreateDirectShowGraph( p_sys );
472 vlc_mutex_init( &p_sys->lock );
473 vlc_cond_init( &p_sys->wait );
475 if( !b_use_video && !b_use_audio )
477 vlc_dialog_display_error( p_this, _("Capture failed"),
478 _("No video or audio device selected.") );
479 return VLC_EGENERIC ;
482 if( !b_use_video )
483 msg_Dbg( p_this, "skipping video device" ) ;
484 bool b_err_video = false ;
486 if( b_use_video && OpenDevice( p_this, p_sys, vdevname, 0 ) != VLC_SUCCESS )
488 msg_Err( p_this, "can't open video device");
489 b_err_video = true ;
492 if ( b_use_video && !b_err_video )
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());
498 if( p_stream->mt.majortype == MEDIATYPE_Video )
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 )
505 b_use_audio = false;
507 if( b_access_demux )
509 /* Let the access (only) take care of that */
510 return VLC_EGENERIC;
515 if( p_stream->mt.majortype == MEDIATYPE_Stream )
517 b_use_audio = false;
519 if( b_access_demux )
521 /* Let the access (only) take care of that */
522 return VLC_EGENERIC;
525 if( var_GetBool( p_this, "dshow-tuner" ) )
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 );
535 if( !b_use_audio )
536 msg_Dbg( p_this, "skipping audio device") ;
538 bool b_err_audio = false ;
540 if( b_use_audio && OpenDevice( p_this, p_sys, adevname, 1 ) != VLC_SUCCESS )
542 msg_Err( p_this, "can't open audio device");
543 b_err_audio = true ;
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 ) )
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 ;
557 for( int i = p_sys->i_crossbar_route_depth-1; i >= 0 ; --i )
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;
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;
578 if( SUCCEEDED(pXbar->Route(VideoOutputIndex, VideoInputIndex)) )
580 msg_Dbg( p_this, "crossbar at depth %d, routed video "
581 "output %ld to video input %ld", i, VideoOutputIndex,
582 VideoInputIndex );
584 if( AudioOutputIndex != -1 && AudioInputIndex != -1 )
586 if( SUCCEEDED( pXbar->Route(AudioOutputIndex,
587 AudioInputIndex)) )
589 msg_Dbg(p_this, "crossbar at depth %d, routed audio "
590 "output %ld to audio input %ld", i,
591 AudioOutputIndex, AudioInputIndex );
595 else
596 msg_Err( p_this, "crossbar at depth %d could not route video "
597 "output %ld to input %ld", i, VideoOutputIndex, VideoInputIndex );
601 ** Show properties pages from other filters in graph
603 if( var_GetBool( p_this, "dshow-config" ) )
605 for( int i = p_sys->i_crossbar_route_depth-1; i >= 0 ; --i )
607 IAMCrossbar *pXbar = p_sys->crossbar_routes[i].pXbar.Get();
608 ComPtr<IBaseFilter> p_XF;
610 if( SUCCEEDED( pXbar->QueryInterface( IID_IBaseFilter,
611 (void**)p_XF.ReleaseAndGetAddressOf() ) ) )
613 ShowPropertyPage( p_XF.Get() );
618 /* Initialize some data */
619 p_sys->i_current_stream = 0;
621 if( p_sys->pp_streams.empty() ) return VLC_EGENERIC;
623 return VLC_SUCCESS;
626 /*****************************************************************************
627 * DemuxOpen: open direct show device as an access_demux module
628 *****************************************************************************/
629 static int DemuxOpen( vlc_object_t *p_this )
631 demux_t *p_demux = (demux_t *)p_this;
632 access_sys_t *p_sys;
634 if (p_demux->out == NULL)
635 return VLC_EGENERIC;
637 p_sys = (access_sys_t*)calloc( 1, sizeof( access_sys_t ) );
638 if( !p_sys )
639 return VLC_ENOMEM;
640 p_demux->p_sys = (demux_sys_t *)p_sys;
642 ComContext ctx( COINIT_MULTITHREADED );
644 if( vlc_mta_acquire( p_this ) == false )
646 msg_Err( p_this, "Failed to acquire MTA" );
647 return VLC_EGENERIC;
650 if( CommonOpen( p_this, p_sys, true ) != VLC_SUCCESS )
652 CommonClose( p_this, p_sys );
653 return VLC_EGENERIC;
656 /* Everything is ready. Let's rock baby */
657 msg_Dbg( p_this, "Playing...");
658 if( FAILED( p_sys->p_control->Run() ) )
660 msg_Err( p_this, "Failed to run graph. Capture device may be in use." );
661 CommonClose( p_this, p_sys );
662 return VLC_EGENERIC;
665 p_demux->pf_demux = Demux;
666 p_demux->pf_control = DemuxControl;
668 std::vector<dshow_stream_t*>::iterator it = p_sys->pp_streams.begin();
669 std::vector<dshow_stream_t*>::iterator end = p_sys->pp_streams.end();
670 for ( ; it != end; ++it )
672 dshow_stream_t *p_stream = *it;
673 es_format_t fmt;
675 if( p_stream->mt.majortype == MEDIATYPE_Video )
677 char *psz_aspect = var_CreateGetString( p_this, "dshow-aspect-ratio" );
678 char *psz_delim = !EMPTY_STR( psz_aspect ) ? strchr( psz_aspect, ':' ) : NULL;
680 es_format_Init( &fmt, VIDEO_ES, p_stream->i_fourcc );
682 fmt.video.i_width = p_stream->header.video.bmiHeader.biWidth;
683 fmt.video.i_height = p_stream->header.video.bmiHeader.biHeight;
685 if( psz_delim )
687 fmt.video.i_sar_num = atoi( psz_aspect ) * fmt.video.i_height;
688 fmt.video.i_sar_den = atoi( psz_delim + 1 ) * fmt.video.i_width;
690 else
692 fmt.video.i_sar_num = 4 * fmt.video.i_height;
693 fmt.video.i_sar_den = 3 * fmt.video.i_width;
695 free( psz_aspect );
697 if( !p_stream->header.video.bmiHeader.biCompression )
699 /* RGB DIB are coded from bottom to top */
700 fmt.video.orientation = ORIENT_BOTTOM_LEFT;
703 /* Setup rgb mask for RGB formats */
704 if( p_stream->i_fourcc == VLC_CODEC_RGB24 )
706 /* This is in RGB format
707 http://msdn.microsoft.com/en-us/library/dd407253%28VS.85%29.aspx?ppud=4
709 fmt.video.i_rmask = 0x00ff0000;
710 fmt.video.i_gmask = 0x0000ff00;
711 fmt.video.i_bmask = 0x000000ff;
714 if( p_stream->header.video.AvgTimePerFrame )
716 fmt.video.i_frame_rate = 10000000;
717 fmt.video.i_frame_rate_base =
718 p_stream->header.video.AvgTimePerFrame;
721 else if( p_stream->mt.majortype == MEDIATYPE_Audio )
723 es_format_Init( &fmt, AUDIO_ES, p_stream->i_fourcc );
725 fmt.audio.i_channels = p_stream->header.audio.nChannels;
726 fmt.audio.i_rate = p_stream->header.audio.nSamplesPerSec;
727 fmt.audio.i_bitspersample = p_stream->header.audio.wBitsPerSample;
728 fmt.audio.i_blockalign = fmt.audio.i_channels *
729 fmt.audio.i_bitspersample / 8;
730 fmt.i_bitrate = fmt.audio.i_channels * fmt.audio.i_rate *
731 fmt.audio.i_bitspersample;
734 p_stream->p_es = es_out_Add( p_demux->out, &fmt );
737 p_sys->i_start = vlc_tick_now();
738 return VLC_SUCCESS;
741 /*****************************************************************************
742 * AccessOpen: open direct show device as an access module
743 *****************************************************************************/
744 static int AccessOpen( vlc_object_t *p_this )
746 stream_t *p_access = (stream_t*)p_this;
747 access_sys_t *p_sys;
749 p_access->p_sys = p_sys = (access_sys_t*)calloc( 1, sizeof( access_sys_t ) );
750 if( !p_sys )
751 return VLC_ENOMEM;
753 ComContext ctx( COINIT_MULTITHREADED );
755 if( vlc_mta_acquire( p_this ) == false )
757 msg_Err( p_this, "Failed to acquire MTA" );
758 return VLC_EGENERIC;
761 if( CommonOpen( p_this, p_sys, false ) != VLC_SUCCESS )
763 CommonClose( p_this, p_sys );
764 return VLC_EGENERIC;
767 /* Setup Access */
768 p_access->pf_read = NULL;
769 p_access->pf_block = ReadCompressed;
770 p_access->pf_control = AccessControl;
771 p_access->pf_seek = NULL;
772 p_access->p_sys = p_sys;
774 /* Everything is ready. Let's rock baby */
775 msg_Dbg( p_this, "Playing...");
776 if( FAILED( p_sys->p_control->Run() ) )
778 msg_Err( p_this, "Failed to run graph. Capture device may be in use." );
779 CommonClose( p_this, p_sys );
780 return VLC_EGENERIC;
783 return VLC_SUCCESS;
786 /*****************************************************************************
787 * CommonClose: close device
788 *****************************************************************************/
789 static void CommonClose( vlc_object_t *p_this, access_sys_t *p_sys )
791 msg_Dbg( p_this, "releasing DirectShow");
793 DeleteDirectShowGraph( p_this, p_sys );
795 vlc_delete_all( p_sys->pp_streams );
797 vlc_mutex_destroy( &p_sys->lock );
798 vlc_cond_destroy( &p_sys->wait );
800 vlc_mta_release( p_this );
802 free( p_sys );
805 /*****************************************************************************
806 * AccessClose: close device
807 *****************************************************************************/
808 static void AccessClose( vlc_object_t *p_this )
810 stream_t *p_access = (stream_t *)p_this;
811 access_sys_t *p_sys = (access_sys_t *)p_access->p_sys;
813 ComContext ctx( COINIT_MULTITHREADED );
815 /* Stop capturing stuff */
816 p_sys->p_control->Stop();
818 CommonClose( p_this, p_sys );
821 /*****************************************************************************
822 * DemuxClose: close device
823 *****************************************************************************/
824 static void DemuxClose( vlc_object_t *p_this )
826 demux_t *p_demux = (demux_t *)p_this;
827 access_sys_t *p_sys = (access_sys_t *)p_demux->p_sys;
829 ComContext ctx( COINIT_MULTITHREADED );
831 /* Stop capturing stuff */
832 p_sys->p_control->Stop();
834 CommonClose( p_this, p_sys );
837 /****************************************************************************
838 * ConnectFilters
839 ****************************************************************************/
840 static bool ConnectFilters( vlc_object_t *p_this, access_sys_t *p_sys,
841 IBaseFilter *p_filter,
842 CaptureFilter *p_capture_filter )
844 ComPtr<CapturePin> p_input_pin = p_capture_filter->CustomGetPin();
846 AM_MEDIA_TYPE mediaType = p_input_pin->CustomGetMediaType();
848 if( p_sys->p_capture_graph_builder2 )
850 if( FAILED(p_sys->p_capture_graph_builder2->
851 RenderStream( &PIN_CATEGORY_CAPTURE, &mediaType.majortype,
852 p_filter, 0, (IBaseFilter *)p_capture_filter )) )
854 return false;
857 // Sort out all the possible video inputs
858 // The class needs to be given the capture filters ANALOGVIDEO input pin
859 ComPtr<IEnumPins> pins;
860 if( ( mediaType.majortype == MEDIATYPE_Video ||
861 mediaType.majortype == MEDIATYPE_Stream ) &&
862 SUCCEEDED(p_filter->EnumPins(pins.GetAddressOf())) )
864 ComPtr<IPin> pP;
865 ULONG n;
866 PIN_INFO pinInfo;
867 BOOL Found = FALSE;
868 GUID guid;
869 DWORD dw;
871 while( !Found && ( S_OK == pins->Next(1, pP.ReleaseAndGetAddressOf(), &n) ) )
873 if( S_OK == pP->QueryPinInfo(&pinInfo) )
875 ComPtr<IKsPropertySet> pKs;
876 // is this pin an ANALOGVIDEOIN input pin?
877 if( pinInfo.dir == PINDIR_INPUT &&
878 pP->QueryInterface( IID_IKsPropertySet,
879 (void**)pKs.GetAddressOf() ) == S_OK )
881 if( pKs->Get( AMPROPSETID_Pin,
882 AMPROPERTY_PIN_CATEGORY, NULL, 0,
883 &guid, sizeof(GUID), &dw ) == S_OK )
885 if( guid == PIN_CATEGORY_ANALOGVIDEOIN )
887 // recursively search crossbar routes
888 FindCrossbarRoutes( p_this, p_sys, pP.Get(), 0 );
889 // found it
890 Found = TRUE;
894 pinInfo.pFilter->Release();
897 msg_Dbg( p_this, "ConnectFilters: graph_builder2 available.") ;
898 if ( !Found )
899 msg_Warn( p_this, "ConnectFilters: No crossBar routes found (incompatible pin types)" ) ;
901 return true;
903 else
905 ComPtr<IEnumPins> p_enumpins;
906 ComPtr<IPin> p_pin;
908 if( S_OK != p_filter->EnumPins( p_enumpins.GetAddressOf() ) ) return false;
910 while( S_OK == p_enumpins->Next( 1, p_pin.ReleaseAndGetAddressOf(), NULL ) )
912 PIN_DIRECTION pin_dir;
913 p_pin->QueryDirection( &pin_dir );
915 if( pin_dir == PINDIR_OUTPUT &&
916 p_sys->p_graph->ConnectDirect( p_pin.Get(), p_input_pin.Get(),
917 0 ) == S_OK )
919 return true;
922 return false;
927 * get fourcc priority from arbritary preference, the higher the better
929 static int GetFourCCPriority( int i_fourcc )
931 switch( i_fourcc )
933 case VLC_CODEC_I420:
934 case VLC_CODEC_FL32:
935 return 9;
936 case VLC_CODEC_YV12:
937 case VLC_FOURCC('a','r','a','w'):
938 return 8;
939 case VLC_CODEC_RGB24:
940 return 7;
941 case VLC_CODEC_YUYV:
942 case VLC_CODEC_RGB32:
943 case VLC_CODEC_RGBA:
944 return 6;
947 return 0;
950 #define MAX_MEDIA_TYPES 32
952 static int OpenDevice( vlc_object_t *p_this, access_sys_t *p_sys,
953 std::string devicename, bool b_audio )
955 ComPtr<IBaseFilter> p_device_filter;
957 /* See if device is already opened */
958 std::vector<dshow_stream_t*>::iterator it = p_sys->pp_streams.begin();
959 std::vector<dshow_stream_t*>::iterator end = p_sys->pp_streams.end();
960 for ( ; it != end; ++it )
962 if( devicename.size() &&
963 (*it)->devicename == devicename )
965 /* Already opened */
966 wchar_t *pwsz_devicename = ToWide( devicename.c_str() );
968 if( likely( pwsz_devicename ) )
969 p_sys->p_graph->FindFilterByName( pwsz_devicename, p_device_filter.GetAddressOf() );
971 free( pwsz_devicename );
973 if( !p_device_filter )
975 msg_Err( p_this, "Device '%s' already opened, but couldn't be retrieved", devicename.c_str() );
976 return VLC_EGENERIC;
979 break;
983 if( !p_device_filter )
985 std::list<std::string> list_devices;
987 /* Enumerate devices and display their names */
988 FindCaptureDevice( p_this, NULL, &list_devices, b_audio );
989 if( list_devices.empty() )
990 return VLC_EGENERIC;
992 std::list<std::string>::iterator iter;
993 for( iter = list_devices.begin(); iter != list_devices.end(); ++iter )
994 msg_Dbg( p_this, "found device: %s", iter->c_str() );
996 /* If no device name was specified, pick the 1st one */
997 if( devicename.size() == 0 )
999 /* When none selected */
1000 devicename = *list_devices.begin();
1001 msg_Dbg( p_this, "asking for default device: %s", devicename.c_str() ) ;
1003 else
1004 msg_Dbg( p_this, "asking for device: %s", devicename.c_str() ) ;
1006 // Use the system device enumerator and class enumerator to find
1007 // a capture/preview device, such as a desktop USB video camera.
1008 p_device_filter = FindCaptureDevice( p_this, &devicename, NULL, b_audio );
1010 if( p_device_filter )
1011 msg_Dbg( p_this, "using device: %s", devicename.c_str() );
1012 else
1014 msg_Err( p_this, "can't use device: %s, unsupported device type",
1015 devicename.c_str() );
1016 vlc_dialog_display_error( p_this, _("Capture failed"),
1017 _("The device you selected cannot be used, because its "
1018 "type is not supported.") );
1019 return VLC_EGENERIC;
1022 /* Add the device filter to the graph (seems necessary with VfW before
1023 * accessing pin attributes). */
1025 HRESULT hr = E_FAIL;
1026 wchar_t *pwsz_devicename = ToWide( devicename.c_str() );
1028 if( likely( pwsz_devicename ) )
1029 hr = p_sys->p_graph->AddFilter( p_device_filter.Get(), pwsz_devicename );
1031 free( pwsz_devicename );
1033 if( FAILED( hr ) )
1035 msg_Err( p_this, "Error adding device '%s' to the graph", devicename.c_str() );
1036 return VLC_EGENERIC;
1040 // Retreive acceptable media types supported by device
1041 AM_MEDIA_TYPE media_types[MAX_MEDIA_TYPES];
1042 size_t media_count =
1043 EnumDeviceCaps( p_this, p_device_filter.Get(), b_audio ? 0 : p_sys->i_chroma,
1044 p_sys->i_width, p_sys->i_height,
1045 b_audio ? var_CreateGetInteger( p_this, "dshow-audio-channels" ) : 0,
1046 b_audio ? var_CreateGetInteger( p_this, "dshow-audio-samplerate" ) : 0,
1047 b_audio ? var_CreateGetInteger( p_this, "dshow-audio-bitspersample" ) : 0,
1048 media_types, MAX_MEDIA_TYPES, b_audio );
1050 AM_MEDIA_TYPE *mt = NULL;
1052 if( media_count > 0 )
1054 mt = (AM_MEDIA_TYPE *)CoTaskMemAlloc(sizeof(AM_MEDIA_TYPE) * media_count);
1056 // Order and copy returned media types according to arbitrary
1057 // fourcc priority
1058 for( size_t c = 0; c < media_count; c++ )
1060 int slot_priority =
1061 GetFourCCPriority(GetFourCCFromMediaType(media_types[c]));
1062 size_t slot_copy = c;
1063 for( size_t d = c+1; d < media_count; d++ )
1065 int priority =
1066 GetFourCCPriority(GetFourCCFromMediaType(media_types[d]));
1067 if( priority > slot_priority )
1069 slot_priority = priority;
1070 slot_copy = d;
1073 if( slot_copy != c )
1075 mt[c] = media_types[slot_copy];
1076 media_types[slot_copy] = media_types[c];
1078 else
1080 mt[c] = media_types[c];
1084 else {
1085 /* capture device */
1086 msg_Err( p_this, "capture device '%s' does not support required parameters !", devicename.c_str() );
1087 vlc_dialog_display_error( p_this, _("Capture failed"),
1088 _("The capture device \"%s\" does not support the "
1089 "required parameters."), devicename.c_str() );
1090 return VLC_EGENERIC;
1093 /* Create and add our capture filter */
1094 ComPtr<CaptureFilter> p_capture_filter(
1095 new CaptureFilter( p_this, p_sys, mt, media_count ) );
1096 p_sys->p_graph->AddFilter( p_capture_filter.Get(), 0 );
1098 /* Attempt to connect one of this device's capture output pins */
1099 msg_Dbg( p_this, "connecting filters" );
1100 if( ConnectFilters( p_this, p_sys, p_device_filter.Get(), p_capture_filter.Get() ) )
1102 /* Success */
1103 msg_Dbg( p_this, "filters connected successfully !" );
1105 dshow_stream_t dshow_stream;
1106 dshow_stream.devicename = devicename;
1107 dshow_stream.b_pts = false;
1108 dshow_stream.p_es = 0;
1109 dshow_stream.mt =
1110 p_capture_filter->CustomGetPin()->CustomGetMediaType();
1112 /* Show Device properties. Done here so the VLC stream is setup with
1113 * the proper parameters. */
1114 if( var_GetBool( p_this, "dshow-config" ) )
1116 ShowDeviceProperties( p_this, p_sys->p_capture_graph_builder2.Get(),
1117 p_device_filter.Get(), b_audio );
1120 ConfigTuner( p_this, p_sys->p_capture_graph_builder2.Get(),
1121 p_device_filter.Get() );
1123 if( var_GetBool( p_this, "dshow-tuner" ) &&
1124 dshow_stream.mt.majortype != MEDIATYPE_Stream )
1126 /* FIXME: we do MEDIATYPE_Stream later so we don't do it twice. */
1127 ShowTunerProperties( p_this, p_sys->p_capture_graph_builder2.Get(),
1128 p_device_filter.Get(), b_audio );
1131 dshow_stream.mt =
1132 p_capture_filter->CustomGetPin()->CustomGetMediaType();
1134 dshow_stream.i_fourcc = GetFourCCFromMediaType( dshow_stream.mt );
1135 if( dshow_stream.i_fourcc )
1137 if( dshow_stream.mt.majortype == MEDIATYPE_Video )
1139 dshow_stream.header.video =
1140 *(VIDEOINFOHEADER *)dshow_stream.mt.pbFormat;
1141 msg_Dbg( p_this, "MEDIATYPE_Video" );
1142 msg_Dbg( p_this, "selected video pin accepts format: %4.4s",
1143 (char *)&dshow_stream.i_fourcc);
1145 else if( dshow_stream.mt.majortype == MEDIATYPE_Audio )
1147 dshow_stream.header.audio =
1148 *(WAVEFORMATEX *)dshow_stream.mt.pbFormat;
1149 msg_Dbg( p_this, "MEDIATYPE_Audio" );
1150 msg_Dbg( p_this, "selected audio pin accepts format: %4.4s",
1151 (char *)&dshow_stream.i_fourcc);
1153 else if( dshow_stream.mt.majortype == MEDIATYPE_Stream )
1155 msg_Dbg( p_this, "MEDIATYPE_Stream" );
1156 msg_Dbg( p_this, "selected stream pin accepts format: %4.4s",
1157 (char *)&dshow_stream.i_fourcc);
1159 else
1161 msg_Dbg( p_this, "unknown stream majortype" );
1162 goto fail;
1165 /* Add directshow elementary stream to our list */
1166 dshow_stream.p_device_filter = p_device_filter;
1167 dshow_stream.p_capture_filter = p_capture_filter;
1169 p_sys->pp_streams.push_back( new dshow_stream_t(dshow_stream) );
1171 return VLC_SUCCESS;
1175 fail:
1176 /* Remove filters from graph */
1177 msg_Dbg( p_this, "OpenDevice: Removing filters" ) ;
1178 p_sys->p_graph->RemoveFilter( p_device_filter.Get() );
1179 p_sys->p_graph->RemoveFilter( p_capture_filter.Get() );
1181 return VLC_EGENERIC;
1184 /* FindCaptureDevices:: This Function had two purposes :
1185 Returns the list of capture devices when p_listdevices != NULL
1186 Creates an IBaseFilter when p_devicename corresponds to an existing devname
1187 These actions *may* be requested whith a single call.
1189 static ComPtr<IBaseFilter>
1190 FindCaptureDevice( vlc_object_t *p_this, std::string *p_devicename,
1191 std::list<std::string> *p_listdevices, bool b_audio )
1193 ComPtr<IBaseFilter> p_base_filter;
1194 ComPtr<IMoniker> p_moniker;
1195 ULONG i_fetched;
1196 HRESULT hr;
1197 std::list<std::string> devicelist;
1199 /* Create the system device enumerator */
1200 ComPtr<ICreateDevEnum> p_dev_enum;
1202 hr = CoCreateInstance( CLSID_SystemDeviceEnum, NULL, CLSCTX_INPROC,
1203 IID_ICreateDevEnum, (void**)p_dev_enum.GetAddressOf() );
1204 if( FAILED(hr) )
1206 msg_Err( p_this, "failed to create the device enumerator (0x%lx)", hr);
1207 return p_base_filter;
1210 /* Create an enumerator for the video capture devices */
1211 ComPtr<IEnumMoniker> p_class_enum;
1212 if( !b_audio )
1213 hr = p_dev_enum->CreateClassEnumerator( CLSID_VideoInputDeviceCategory,
1214 p_class_enum.GetAddressOf(), 0 );
1215 else
1216 hr = p_dev_enum->CreateClassEnumerator( CLSID_AudioInputDeviceCategory,
1217 p_class_enum.GetAddressOf(), 0 );
1218 if( FAILED(hr) )
1220 msg_Err( p_this, "failed to create the class enumerator (0x%lx)", hr );
1221 return p_base_filter;
1224 /* If there are no enumerators for the requested type, then
1225 * CreateClassEnumerator will succeed, but p_class_enum will be NULL */
1226 if( p_class_enum == NULL )
1228 msg_Err( p_this, "no %s capture device was detected", ( b_audio ? "audio" : "video" ) );
1229 return p_base_filter;
1232 /* Enumerate the devices */
1234 /* Note that if the Next() call succeeds but there are no monikers,
1235 * it will return S_FALSE (which is not a failure). Therefore, we check
1236 * that the return code is S_OK instead of using SUCCEEDED() macro. */
1238 while( p_class_enum->Next( 1, p_moniker.ReleaseAndGetAddressOf(), &i_fetched ) == S_OK )
1240 /* Getting the property page to get the device name */
1241 ComPtr<IPropertyBag> p_bag;
1242 hr = p_moniker->BindToStorage( 0, 0, IID_IPropertyBag,
1243 (void**)p_bag.GetAddressOf() );
1244 if( SUCCEEDED(hr) )
1246 VARIANT var;
1247 var.vt = VT_BSTR;
1248 hr = p_bag->Read( L"FriendlyName", &var, NULL );
1249 if( SUCCEEDED(hr) )
1251 char *p_buf = FromWide( var.bstrVal );
1252 std::string devname(p_buf);
1253 free( p_buf) ;
1255 int dup = 0;
1256 /* find out if this name is already used by a previously found device */
1257 std::list<std::string>::const_iterator iter = devicelist.begin();
1258 std::list<std::string>::const_iterator end = devicelist.end();
1259 std::string ordevname = devname ;
1260 while ( iter != end )
1262 if( 0 == (*iter).compare( devname ) )
1263 { /* devname is on the list. Try another name with sequence
1264 number apended and then rescan until a unique entry is found*/
1265 char seq[16];
1266 snprintf(seq, 16, " #%d", ++dup);
1267 devname = ordevname + seq;
1268 iter = devicelist.begin();
1270 else
1271 ++iter;
1273 devicelist.push_back( devname );
1275 if( p_devicename && *p_devicename == devname )
1277 msg_Dbg( p_this, "asked for %s, binding to %s", p_devicename->c_str() , devname.c_str() ) ;
1278 /* NULL possibly means we don't need BindMoniker BindCtx ?? */
1279 hr = p_moniker->BindToObject( NULL, 0, IID_IBaseFilter,
1280 (void**)p_base_filter.GetAddressOf() );
1281 if( FAILED(hr) )
1283 msg_Err( p_this, "couldn't bind moniker to filter "
1284 "object (0x%lx)", hr );
1285 return NULL;
1287 return p_base_filter;
1293 if( p_listdevices ) {
1294 devicelist.sort();
1295 *p_listdevices = devicelist;
1297 return p_base_filter;
1300 static size_t EnumDeviceCaps( vlc_object_t *p_this, IBaseFilter *p_filter,
1301 int i_fourcc, int i_width, int i_height,
1302 int i_channels, int i_samplespersec,
1303 int i_bitspersample, AM_MEDIA_TYPE *mt,
1304 size_t mt_max, bool b_audio )
1306 ComPtr<IEnumPins> p_enumpins;
1307 ComPtr<IPin> p_output_pin;
1308 ComPtr<IEnumMediaTypes> p_enummt;
1309 size_t mt_count = 0;
1311 LONGLONG i_AvgTimePerFrame = 0;
1312 float r_fps = var_GetFloat( p_this, "dshow-fps" );
1313 if( r_fps )
1314 i_AvgTimePerFrame = 10000000000LL/(LONGLONG)(r_fps*1000.0f);
1316 if( FAILED(p_filter->EnumPins( p_enumpins.GetAddressOf() )) )
1318 msg_Dbg( p_this, "EnumDeviceCaps failed: no pin enumeration !");
1319 return 0;
1322 while( S_OK == p_enumpins->Next( 1, p_output_pin.ReleaseAndGetAddressOf(), NULL ) )
1324 PIN_INFO info;
1326 if( S_OK == p_output_pin->QueryPinInfo( &info ) )
1328 msg_Dbg( p_this, "EnumDeviceCaps: %s pin: %S",
1329 info.dir == PINDIR_INPUT ? "input" : "output",
1330 info.achName );
1331 if( info.pFilter ) info.pFilter->Release();
1335 p_enumpins->Reset();
1337 while( !mt_count && p_enumpins->Next( 1, p_output_pin.ReleaseAndGetAddressOf(), NULL ) == S_OK )
1339 PIN_INFO info;
1341 if( S_OK == p_output_pin->QueryPinInfo( &info ) )
1343 if( info.pFilter ) info.pFilter->Release();
1344 if( info.dir == PINDIR_INPUT )
1345 continue;
1346 msg_Dbg( p_this, "EnumDeviceCaps: trying pin %S", info.achName );
1349 AM_MEDIA_TYPE *p_mt;
1352 ** Configure pin with a default compatible media if possible
1355 ComPtr<IAMStreamConfig> pSC;
1356 if( SUCCEEDED(p_output_pin->QueryInterface( IID_IAMStreamConfig,
1357 (void**)pSC.GetAddressOf() )) )
1359 int piCount, piSize;
1360 if( SUCCEEDED(pSC->GetNumberOfCapabilities(&piCount, &piSize)) )
1362 BYTE *pSCC= (BYTE *)CoTaskMemAlloc(piSize);
1363 if( NULL != pSCC )
1365 int i_priority = ES_PRIORITY_NOT_DEFAULTABLE;
1366 for( int i=0; i<piCount; ++i )
1368 if( SUCCEEDED(pSC->GetStreamCaps(i, &p_mt, pSCC)) )
1370 int i_current_fourcc = GetFourCCFromMediaType( *p_mt );
1371 int i_current_priority = GetFourCCPriority(i_current_fourcc);
1373 if( (i_fourcc && (i_current_fourcc != i_fourcc))
1374 || (i_priority > i_current_priority) )
1376 // unwanted chroma, try next media type
1377 FreeMediaType( *p_mt );
1378 CoTaskMemFree( (PVOID)p_mt );
1379 continue;
1382 if( !b_audio && MEDIATYPE_Video == p_mt->majortype
1383 && FORMAT_VideoInfo == p_mt->formattype )
1385 VIDEO_STREAM_CONFIG_CAPS *pVSCC = reinterpret_cast<VIDEO_STREAM_CONFIG_CAPS*>(pSCC);
1386 VIDEOINFOHEADER *pVih = reinterpret_cast<VIDEOINFOHEADER*>(p_mt->pbFormat);
1388 if( i_AvgTimePerFrame )
1390 if( pVSCC->MinFrameInterval > i_AvgTimePerFrame
1391 || i_AvgTimePerFrame > pVSCC->MaxFrameInterval )
1393 // required frame rate not compatible, try next media type
1394 FreeMediaType( *p_mt );
1395 CoTaskMemFree( (PVOID)p_mt );
1396 continue;
1398 pVih->AvgTimePerFrame = i_AvgTimePerFrame;
1401 if( i_width )
1403 if(( !pVSCC->OutputGranularityX
1404 && i_width != pVSCC->MinOutputSize.cx
1405 && i_width != pVSCC->MaxOutputSize.cx)
1407 ( pVSCC->OutputGranularityX
1408 && ((i_width % pVSCC->OutputGranularityX)
1409 || pVSCC->MinOutputSize.cx > i_width
1410 || i_width > pVSCC->MaxOutputSize.cx )))
1412 // required width not compatible, try next media type
1413 FreeMediaType( *p_mt );
1414 CoTaskMemFree( (PVOID)p_mt );
1415 continue;
1417 pVih->bmiHeader.biWidth = i_width;
1420 if( i_height )
1422 if(( !pVSCC->OutputGranularityY
1423 && i_height != pVSCC->MinOutputSize.cy
1424 && i_height != pVSCC->MaxOutputSize.cy)
1426 ( pVSCC->OutputGranularityY
1427 && ((i_height % pVSCC->OutputGranularityY)
1428 || pVSCC->MinOutputSize.cy > i_height
1429 || i_height > pVSCC->MaxOutputSize.cy )))
1431 // required height not compatible, try next media type
1432 FreeMediaType( *p_mt );
1433 CoTaskMemFree( (PVOID)p_mt );
1434 continue;
1436 pVih->bmiHeader.biHeight = i_height;
1439 // Set the sample size and image size.
1440 // (Round the image width up to a DWORD boundary.)
1441 p_mt->lSampleSize = pVih->bmiHeader.biSizeImage =
1442 ((pVih->bmiHeader.biWidth + 3) & ~3) *
1443 pVih->bmiHeader.biHeight * (pVih->bmiHeader.biBitCount>>3);
1445 // no cropping, use full video input buffer
1446 memset(&(pVih->rcSource), 0, sizeof(RECT));
1447 memset(&(pVih->rcTarget), 0, sizeof(RECT));
1449 // select this format as default
1450 if( SUCCEEDED( pSC->SetFormat(p_mt) ) )
1452 i_priority = i_current_priority;
1453 if( i_fourcc )
1454 // no need to check any more media types
1455 i = piCount;
1458 else if( b_audio && p_mt->majortype == MEDIATYPE_Audio
1459 && p_mt->formattype == FORMAT_WaveFormatEx )
1461 AUDIO_STREAM_CONFIG_CAPS *pASCC = reinterpret_cast<AUDIO_STREAM_CONFIG_CAPS*>(pSCC);
1462 WAVEFORMATEX *pWfx = reinterpret_cast<WAVEFORMATEX*>(p_mt->pbFormat);
1464 if( i_current_fourcc && (WAVE_FORMAT_PCM == pWfx->wFormatTag) )
1466 int val = i_channels;
1467 if( ! val )
1468 val = 2;
1470 if( ( !pASCC->ChannelsGranularity
1471 && (unsigned int)val != pASCC->MinimumChannels
1472 && (unsigned int)val != pASCC->MaximumChannels)
1474 ( pASCC->ChannelsGranularity
1475 && ((val % pASCC->ChannelsGranularity)
1476 || (unsigned int)val < pASCC->MinimumChannels
1477 || (unsigned int)val > pASCC->MaximumChannels)))
1479 // required number channels not available, try next media type
1480 FreeMediaType( *p_mt );
1481 CoTaskMemFree( (PVOID)p_mt );
1482 continue;
1484 pWfx->nChannels = val;
1486 val = i_samplespersec;
1487 if( ! val )
1488 val = 44100;
1490 if( ( !pASCC->SampleFrequencyGranularity
1491 && (unsigned int)val != pASCC->MinimumSampleFrequency
1492 && (unsigned int)val != pASCC->MaximumSampleFrequency)
1494 ( pASCC->SampleFrequencyGranularity
1495 && ((val % pASCC->SampleFrequencyGranularity)
1496 || (unsigned int)val < pASCC->MinimumSampleFrequency
1497 || (unsigned int)val > pASCC->MaximumSampleFrequency )))
1499 // required sampling rate not available, try next media type
1500 FreeMediaType( *p_mt );
1501 CoTaskMemFree( (PVOID)p_mt );
1502 continue;
1504 pWfx->nSamplesPerSec = val;
1506 val = i_bitspersample;
1507 if( ! val )
1509 if( VLC_CODEC_FL32 == i_current_fourcc )
1510 val = 32;
1511 else
1512 val = 16;
1515 if( ( !pASCC->BitsPerSampleGranularity
1516 && (unsigned int)val != pASCC->MinimumBitsPerSample
1517 && (unsigned int)val != pASCC->MaximumBitsPerSample )
1519 ( pASCC->BitsPerSampleGranularity
1520 && ((val % pASCC->BitsPerSampleGranularity)
1521 || (unsigned int)val < pASCC->MinimumBitsPerSample
1522 || (unsigned int)val > pASCC->MaximumBitsPerSample )))
1524 // required sample size not available, try next media type
1525 FreeMediaType( *p_mt );
1526 CoTaskMemFree( (PVOID)p_mt );
1527 continue;
1530 pWfx->wBitsPerSample = val;
1531 pWfx->nBlockAlign = (pWfx->wBitsPerSample * pWfx->nChannels)/8;
1532 pWfx->nAvgBytesPerSec = pWfx->nSamplesPerSec * pWfx->nBlockAlign;
1534 // select this format as default
1535 if( SUCCEEDED( pSC->SetFormat(p_mt) ) )
1537 i_priority = i_current_priority;
1541 FreeMediaType( *p_mt );
1542 CoTaskMemFree( (PVOID)p_mt );
1545 CoTaskMemFree( (LPVOID)pSCC );
1546 if( i_priority >= ES_PRIORITY_SELECTABLE_MIN )
1547 msg_Dbg( p_this, "EnumDeviceCaps: input pin default format configured");
1553 ** Probe pin for available medias (may be a previously configured one)
1556 if( FAILED( p_output_pin->EnumMediaTypes( p_enummt.ReleaseAndGetAddressOf() ) ) )
1558 continue;
1561 while( p_enummt->Next( 1, &p_mt, NULL ) == S_OK )
1563 int i_current_fourcc = GetFourCCFromMediaType( *p_mt );
1564 if( !b_audio && i_current_fourcc && p_mt->majortype == MEDIATYPE_Video
1565 && p_mt->formattype == FORMAT_VideoInfo )
1567 int i_current_width = ((VIDEOINFOHEADER *)p_mt->pbFormat)->bmiHeader.biWidth;
1568 int i_current_height = ((VIDEOINFOHEADER *)p_mt->pbFormat)->bmiHeader.biHeight;
1569 LONGLONG i_current_atpf = ((VIDEOINFOHEADER *)p_mt->pbFormat)->AvgTimePerFrame;
1571 if( i_current_height < 0 )
1572 i_current_height = -i_current_height;
1574 msg_Dbg( p_this, "EnumDeviceCaps: input pin "
1575 "accepts chroma: %4.4s, width:%i, height:%i, fps:%f",
1576 (char *)&i_current_fourcc, i_current_width,
1577 i_current_height, (10000000.0f/((float)i_current_atpf)) );
1579 if( ( !i_fourcc || i_fourcc == i_current_fourcc ) &&
1580 ( !i_width || i_width == i_current_width ) &&
1581 ( !i_height || i_height == i_current_height ) &&
1582 ( !i_AvgTimePerFrame || i_AvgTimePerFrame == i_current_atpf ) &&
1583 mt_count < mt_max )
1585 /* Pick match */
1586 mt[mt_count++] = *p_mt;
1588 else FreeMediaType( *p_mt );
1590 else if( b_audio && i_current_fourcc && p_mt->majortype == MEDIATYPE_Audio
1591 && p_mt->formattype == FORMAT_WaveFormatEx)
1593 int i_current_channels =
1594 ((WAVEFORMATEX *)p_mt->pbFormat)->nChannels;
1595 int i_current_samplespersec =
1596 ((WAVEFORMATEX *)p_mt->pbFormat)->nSamplesPerSec;
1597 int i_current_bitspersample =
1598 ((WAVEFORMATEX *)p_mt->pbFormat)->wBitsPerSample;
1600 msg_Dbg( p_this, "EnumDeviceCaps: input pin "
1601 "accepts format: %4.4s, channels:%i, "
1602 "samples/sec:%i bits/sample:%i",
1603 (char *)&i_current_fourcc, i_current_channels,
1604 i_current_samplespersec, i_current_bitspersample);
1606 if( (!i_channels || i_channels == i_current_channels) &&
1607 (!i_samplespersec ||
1608 i_samplespersec == i_current_samplespersec) &&
1609 (!i_bitspersample ||
1610 i_bitspersample == i_current_bitspersample) &&
1611 mt_count < mt_max )
1613 /* Pick match */
1614 mt[mt_count++] = *p_mt;
1616 /* Setup a few properties like the audio latency */
1617 ComPtr<IAMBufferNegotiation> p_ambuf;
1618 if( SUCCEEDED( p_output_pin->QueryInterface(
1619 IID_IAMBufferNegotiation, (void **)p_ambuf.GetAddressOf() ) ) )
1621 ALLOCATOR_PROPERTIES AllocProp;
1622 AllocProp.cbAlign = -1;
1624 /* 100 ms of latency */
1625 AllocProp.cbBuffer = i_current_channels *
1626 i_current_samplespersec *
1627 i_current_bitspersample / 8 / 10;
1629 AllocProp.cbPrefix = -1;
1630 AllocProp.cBuffers = -1;
1631 p_ambuf->SuggestAllocatorProperties( &AllocProp );
1634 else FreeMediaType( *p_mt );
1636 else if( i_current_fourcc && p_mt->majortype == MEDIATYPE_Stream )
1638 msg_Dbg( p_this, "EnumDeviceCaps: input pin "
1639 "accepts stream format: %4.4s",
1640 (char *)&i_current_fourcc );
1642 if( ( !i_fourcc || i_fourcc == i_current_fourcc ) &&
1643 mt_count < mt_max )
1645 /* Pick match */
1646 mt[mt_count++] = *p_mt;
1647 i_fourcc = i_current_fourcc;
1649 else FreeMediaType( *p_mt );
1651 else
1653 const char * psz_type = "unknown";
1654 if( p_mt->majortype == MEDIATYPE_Video ) psz_type = "video";
1655 if( p_mt->majortype == MEDIATYPE_Audio ) psz_type = "audio";
1656 if( p_mt->majortype == MEDIATYPE_Stream ) psz_type = "stream";
1657 msg_Dbg( p_this, "EnumDeviceCaps: input pin media: unsupported format "
1658 "(%s %4.4s)", psz_type, (char *)&p_mt->subtype );
1660 FreeMediaType( *p_mt );
1662 CoTaskMemFree( (PVOID)p_mt );
1665 if( !mt_count && p_enummt->Reset() == S_OK )
1667 // VLC did not find any supported MEDIATYPE for this output pin.
1668 // However the graph builder might insert converter filters in
1669 // the graph if we use a different codec in VLC filter input pin.
1670 // however, in order to avoid nasty surprises, make use of this
1671 // facility only for known unsupported codecs.
1673 while( !mt_count && p_enummt->Next( 1, &p_mt, NULL ) == S_OK )
1675 // the first four bytes of subtype GUID contains the codec FOURCC
1676 const char *pfcc = (char *)&p_mt->subtype;
1677 int i_current_fourcc = VLC_FOURCC(pfcc[0], pfcc[1], pfcc[2], pfcc[3]);
1678 if( VLC_FOURCC('H','C','W','2') == i_current_fourcc
1679 && p_mt->majortype == MEDIATYPE_Video && !b_audio )
1681 // output format for 'Hauppauge WinTV PVR PCI II Capture'
1682 // try I420 as an input format
1683 i_current_fourcc = VLC_CODEC_I420;
1684 if( !i_fourcc || i_fourcc == i_current_fourcc )
1686 // return alternative media type
1687 AM_MEDIA_TYPE mtr;
1688 VIDEOINFOHEADER vh;
1690 mtr.majortype = MEDIATYPE_Video;
1691 mtr.subtype = MEDIASUBTYPE_I420;
1692 mtr.bFixedSizeSamples = TRUE;
1693 mtr.bTemporalCompression = FALSE;
1694 mtr.pUnk = NULL;
1695 mtr.formattype = FORMAT_VideoInfo;
1696 mtr.cbFormat = sizeof(vh);
1697 mtr.pbFormat = (BYTE *)&vh;
1699 memset(&vh, 0, sizeof(vh));
1701 vh.bmiHeader.biSize = sizeof(vh.bmiHeader);
1702 vh.bmiHeader.biWidth = i_width > 0 ? i_width :
1703 ((VIDEOINFOHEADER *)p_mt->pbFormat)->bmiHeader.biWidth;
1704 vh.bmiHeader.biHeight = i_height > 0 ? i_height :
1705 ((VIDEOINFOHEADER *)p_mt->pbFormat)->bmiHeader.biHeight;
1706 vh.bmiHeader.biPlanes = 3;
1707 vh.bmiHeader.biBitCount = 12;
1708 vh.bmiHeader.biCompression = VLC_CODEC_I420;
1709 vh.bmiHeader.biSizeImage = vh.bmiHeader.biWidth * 12 *
1710 vh.bmiHeader.biHeight / 8;
1711 mtr.lSampleSize = vh.bmiHeader.biSizeImage;
1713 msg_Dbg( p_this, "EnumDeviceCaps: input pin media: using 'I420' in place of unsupported format 'HCW2'");
1715 if( SUCCEEDED(CopyMediaType(mt+mt_count, &mtr)) )
1716 ++mt_count;
1719 FreeMediaType( *p_mt );
1724 return mt_count;
1727 /*****************************************************************************
1728 * ReadCompressed: reads compressed (MPEG/DV) data from the device.
1729 *****************************************************************************/
1730 static block_t *ReadCompressed( stream_t *p_access, bool *eof )
1732 ComContext ctx( COINIT_MULTITHREADED );
1734 access_sys_t *p_sys = (access_sys_t *)p_access->p_sys;
1735 /* There must be only 1 elementary stream to produce a valid stream
1736 * of MPEG or DV data */
1737 dshow_stream_t *p_stream = p_sys->pp_streams[0];
1738 VLCMediaSample sample;
1740 /* Read 1 DV/MPEG frame (they contain the video and audio data) */
1742 /* Get new sample/frame from the elementary stream (blocking). */
1743 vlc_mutex_lock( &p_sys->lock );
1745 if( p_stream->p_capture_filter->CustomGetPin()->CustomGetSample(&sample) != S_OK )
1746 { /* No data available. Wait until some data has arrived */
1747 vlc_cond_wait( &p_sys->wait, &p_sys->lock );
1748 vlc_mutex_unlock( &p_sys->lock );
1749 return NULL;
1751 vlc_mutex_unlock( &p_sys->lock );
1754 * We got our sample
1756 block_t *p_block = NULL;
1757 uint8_t *p_data;
1758 int i_data_size = sample.p_sample->GetActualDataLength();
1759 if( i_data_size == 0 )
1760 goto out;
1762 p_block = block_Alloc( i_data_size );
1763 if( unlikely(p_block == NULL) )
1764 goto out;
1766 sample.p_sample->GetPointer( &p_data );
1767 memcpy( p_block->p_buffer, p_data, i_data_size );
1768 /* The caller got what he wanted */
1769 out:
1770 (void) eof;
1771 return p_block;
1774 /****************************************************************************
1775 * Demux:
1776 ****************************************************************************/
1777 static int Demux( demux_t *p_demux )
1779 ComContext ctx( COINIT_MULTITHREADED );
1781 access_sys_t *p_sys = (access_sys_t *)p_demux->p_sys;
1782 int i_found_samples;
1784 i_found_samples = 0;
1785 vlc_mutex_lock( &p_sys->lock );
1787 while ( !i_found_samples )
1789 /* Try to grab samples from all streams */
1790 std::vector<dshow_stream_t*>::iterator it = p_sys->pp_streams.begin();
1791 std::vector<dshow_stream_t*>::iterator end = p_sys->pp_streams.end();
1792 for ( ; it != end; ++it )
1794 dshow_stream_t *p_stream = *it;
1795 if( p_stream->p_capture_filter &&
1796 p_stream->p_capture_filter->CustomGetPin()
1797 ->CustomGetSamples( p_stream->samples_queue ) == S_OK )
1799 i_found_samples = 1;
1803 if ( !i_found_samples)
1805 /* Didn't find any audio nor video sample, just wait till the
1806 * dshow thread pushes some samples */
1807 vlc_cond_wait( &p_sys->wait, &p_sys->lock );
1808 /* Some DShow thread pushed data, or the OS broke the wait all
1809 * by itself. In all cases, it's *strongly* advised to test the
1810 * condition again, so let the loop do the test again */
1814 vlc_mutex_unlock( &p_sys->lock );
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 )
1820 int i_samples;
1821 dshow_stream_t *p_stream = *it;
1823 i_samples = p_stream->samples_queue.size();
1824 while ( i_samples > 0 )
1826 int i_data_size;
1827 uint8_t *p_data;
1828 block_t *p_block;
1829 VLCMediaSample sample;
1831 sample = p_stream->samples_queue.front();
1832 p_stream->samples_queue.pop_front();
1834 i_data_size = sample.p_sample->GetActualDataLength();
1835 sample.p_sample->GetPointer( &p_data );
1837 REFERENCE_TIME i_pts, i_end_date;
1838 HRESULT hr = sample.p_sample->GetTime( &i_pts, &i_end_date );
1839 if( hr != S_OK && hr != VFW_S_NO_STOP_TIME )
1841 if( p_stream->mt.majortype == MEDIATYPE_Video || !p_stream->b_pts )
1843 /* Use our data timestamp */
1844 i_pts = MSFTIME_FROM_VLC_TICK(sample.i_timestamp);
1845 p_stream->b_pts = true;
1847 else
1848 i_pts = LONG_MIN;
1851 if( i_pts != LONG_MIN ) {
1852 i_pts += 5;
1854 #if 0
1855 msg_Dbg( p_demux, "Read() stream: %i, size: %i, PTS: %" PRId64,
1856 i_stream, i_data_size, VLC_TICK_FROM_MSFTIME(i_pts) );
1857 #endif
1859 p_block = block_Alloc( i_data_size );
1860 memcpy( p_block->p_buffer, p_data, i_data_size );
1861 p_block->i_pts = p_block->i_dts = i_pts == LONG_MIN ?
1862 VLC_TICK_INVALID : (VLC_TICK_FROM_MSFTIME(i_pts) + VLC_TICK_0);
1864 if( p_block->i_pts != VLC_TICK_INVALID )
1865 es_out_SetPCR( p_demux->out, p_block->i_pts );
1866 es_out_Send( p_demux->out, p_stream->p_es, p_block );
1868 i_samples--;
1872 return 1;
1875 /*****************************************************************************
1876 * AccessControl:
1877 *****************************************************************************/
1878 static int AccessControl( stream_t *p_access, int i_query, va_list args )
1880 access_sys_t *sys = (access_sys_t *)p_access->p_sys;
1881 bool *pb_bool;
1883 switch( i_query )
1885 case STREAM_CAN_SEEK:
1886 case STREAM_CAN_FASTSEEK:
1887 case STREAM_CAN_PAUSE:
1888 case STREAM_CAN_CONTROL_PACE:
1889 pb_bool = va_arg( args, bool * );
1890 *pb_bool = false;
1891 break;
1893 case STREAM_GET_PTS_DELAY:
1894 *va_arg( args, vlc_tick_t * ) =
1895 VLC_TICK_FROM_MS( var_InheritInteger( p_access, "live-caching" ) );
1896 break;
1898 case STREAM_GET_CONTENT_TYPE:
1900 dshow_stream_t *p_stream = sys->pp_streams[0];
1901 char **type = va_arg( args, char ** );
1903 /* Check if we need to force demuxers */
1904 if( p_stream->i_fourcc == VLC_CODEC_DV )
1905 *type = strdup( "video/dv" );
1906 else if( p_stream->i_fourcc == VLC_CODEC_MPGV )
1907 *type = strdup( "video/MP2P" );
1908 else
1909 return VLC_EGENERIC;
1910 break;
1913 default:
1914 return VLC_EGENERIC;
1917 return VLC_SUCCESS;
1920 /****************************************************************************
1921 * DemuxControl:
1922 ****************************************************************************/
1923 static int DemuxControl( demux_t *p_demux, int i_query, va_list args )
1925 bool *pb;
1926 int64_t *pi64;
1928 access_sys_t *p_sys = ( access_sys_t * ) p_demux->p_sys;
1930 switch( i_query )
1932 /* Special for access_demux */
1933 case DEMUX_CAN_PAUSE:
1934 case DEMUX_CAN_SEEK:
1935 case DEMUX_SET_PAUSE_STATE:
1936 case DEMUX_CAN_CONTROL_PACE:
1937 pb = va_arg( args, bool * );
1938 *pb = false;
1939 return VLC_SUCCESS;
1941 case DEMUX_GET_PTS_DELAY:
1942 *va_arg( args, vlc_tick_t * ) =
1943 VLC_TICK_FROM_MS( var_InheritInteger( p_demux, "live-caching" ) );
1944 return VLC_SUCCESS;
1946 case DEMUX_GET_TIME:
1947 pi64 = va_arg( args, int64_t * );
1948 *pi64 = vlc_tick_now() - p_sys->i_start;
1949 return VLC_SUCCESS;
1951 /* TODO implement others */
1952 default:
1953 return VLC_EGENERIC;
1956 return VLC_EGENERIC;
1959 static int AppendAudioEnabledVDevs( vlc_object_t *p_this, std::list<std::string> &audio_list,
1960 std::list<std::string> &video_list )
1962 ComPtr<IFilterGraph> p_graph;
1963 ComPtr<IGraphBuilder> p_gbuilder;
1964 ComPtr<ICaptureGraphBuilder2> p_cgbuilder;
1966 if( FAILED( CoCreateInstance( CLSID_FilterGraph, NULL, CLSCTX_INPROC_SERVER, IID_IFilterGraph,
1967 ( void ** ) p_graph.GetAddressOf() ) ) )
1968 return VLC_EGENERIC;
1970 if( FAILED( p_graph->QueryInterface( IID_IGraphBuilder, ( void ** ) p_gbuilder.GetAddressOf() ) ) )
1971 return VLC_EGENERIC;
1973 if( FAILED( CoCreateInstance( CLSID_CaptureGraphBuilder2, NULL, CLSCTX_INPROC_SERVER,
1974 IID_ICaptureGraphBuilder2, ( void ** ) p_cgbuilder.GetAddressOf() ) ) )
1975 return VLC_EGENERIC;
1977 if( FAILED( p_cgbuilder->SetFiltergraph( p_gbuilder.Get() ) ) )
1978 return VLC_EGENERIC;
1980 for( std::list<std::string>::iterator iter = video_list.begin();
1981 iter != video_list.end();
1982 ++iter )
1984 ComPtr<IBaseFilter> p_device;
1985 ComPtr<IPin> p_pin;
1987 p_device = FindCaptureDevice( p_this, &( *iter ), NULL, false );
1988 if( !p_device ) continue;
1990 if( FAILED( p_gbuilder->AddFilter( p_device.Get(), NULL ) ) )
1991 continue;
1993 if( SUCCEEDED( p_cgbuilder->FindPin( p_device.Get(), PINDIR_OUTPUT, NULL, &MEDIATYPE_Audio,
1994 true, 0, p_pin.GetAddressOf() ) ) )
1995 audio_list.push_back( *iter );
1997 p_gbuilder->RemoveFilter( p_device.Get() );
2000 return VLC_SUCCESS;
2003 /*****************************************************************************
2004 * config variable callback
2005 *****************************************************************************/
2006 static int FindDevices( const char *psz_name, char ***vp, char ***tp )
2008 /* Find list of devices */
2009 std::list<std::string> list_devices;
2012 bool b_audio = !strcmp( psz_name, "dshow-adev" );
2014 // Use STA as this most likely comes from a Qt thread, which is
2015 // initialized as STA.
2016 ComContext ctx( COINIT_APARTMENTTHREADED );
2018 FindCaptureDevice( NULL, NULL, &list_devices, b_audio );
2020 if( b_audio )
2022 std::list<std::string> list_vdevs;
2023 FindCaptureDevice( NULL, NULL, &list_vdevs, false );
2024 if( !list_vdevs.empty() )
2025 AppendAudioEnabledVDevs( NULL, list_devices, list_vdevs );
2028 catch (const std::runtime_error& ex)
2030 msg_Err( (vlc_object_t *)NULL, "Failed fetch devices: %s", ex.what() );
2033 unsigned count = 2 + list_devices.size(), i = 2;
2034 char **values = (char **)xmalloc( count * sizeof(*values) );
2035 char **texts = (char **)xmalloc( count * sizeof(*texts) );
2037 values[0] = strdup( "" );
2038 texts[0] = strdup( _("Default") );
2039 values[1] = strdup( "none" );
2040 texts[1] = strdup( _("None") );
2042 for( std::list<std::string>::iterator iter = list_devices.begin();
2043 iter != list_devices.end();
2044 ++iter )
2046 assert( i < count );
2047 values[i] = strdup( iter->c_str() );
2048 texts[i] = strdup( iter->c_str() );
2049 i++;
2052 *vp = values;
2053 *tp = texts;
2054 return count;
2057 /*****************************************************************************
2058 * Properties
2059 *****************************************************************************/
2061 static void ShowPropertyPage( IUnknown *obj )
2063 ComPtr<ISpecifyPropertyPages> p_spec;
2064 CAUUID cauuid;
2066 HRESULT hr = obj->QueryInterface( IID_ISpecifyPropertyPages,
2067 (void **)p_spec.GetAddressOf() );
2068 if( FAILED(hr) ) return;
2070 if( SUCCEEDED(p_spec->GetPages( &cauuid )) )
2072 if( cauuid.cElems > 0 )
2074 HWND hwnd_desktop = ::GetDesktopWindow();
2076 OleCreatePropertyFrame( hwnd_desktop, 30, 30, NULL, 1, &obj,
2077 cauuid.cElems, cauuid.pElems, 0, 0, NULL );
2079 CoTaskMemFree( cauuid.pElems );
2084 static void ShowDeviceProperties( vlc_object_t *p_this,
2085 ICaptureGraphBuilder2 *p_graph,
2086 IBaseFilter *p_device_filter,
2087 bool b_audio )
2089 HRESULT hr;
2090 msg_Dbg( p_this, "configuring Device Properties" );
2093 * Video or audio capture filter page
2095 ShowPropertyPage( p_device_filter );
2098 * Audio capture pin
2100 if( p_graph && b_audio )
2102 ComPtr<IAMStreamConfig> p_SC;
2104 msg_Dbg( p_this, "showing WDM Audio Configuration Pages" );
2106 hr = p_graph->FindInterface( &PIN_CATEGORY_CAPTURE,
2107 &MEDIATYPE_Audio, p_device_filter,
2108 IID_IAMStreamConfig, (void **)p_SC.GetAddressOf() );
2109 if( SUCCEEDED(hr) )
2111 ShowPropertyPage(p_SC.Get());
2115 * TV Audio filter
2117 ComPtr<IAMTVAudio> p_TVA;
2118 HRESULT hr = p_graph->FindInterface( &PIN_CATEGORY_CAPTURE,
2119 &MEDIATYPE_Audio, p_device_filter,
2120 IID_IAMTVAudio, (void **)p_TVA.GetAddressOf() );
2121 if( SUCCEEDED(hr) )
2123 ShowPropertyPage(p_TVA.Get());
2128 * Video capture pin
2130 if( p_graph && !b_audio )
2132 ComPtr<IAMStreamConfig> p_SC;
2134 msg_Dbg( p_this, "showing WDM Video Configuration Pages" );
2136 hr = p_graph->FindInterface( &PIN_CATEGORY_CAPTURE,
2137 &MEDIATYPE_Interleaved, p_device_filter,
2138 IID_IAMStreamConfig, (void **)p_SC.GetAddressOf() );
2139 if( FAILED(hr) )
2141 hr = p_graph->FindInterface( &PIN_CATEGORY_CAPTURE,
2142 &MEDIATYPE_Video, p_device_filter,
2143 IID_IAMStreamConfig, (void **)p_SC.GetAddressOf() );
2146 if( FAILED(hr) )
2148 hr = p_graph->FindInterface( &PIN_CATEGORY_CAPTURE,
2149 &MEDIATYPE_Stream, p_device_filter,
2150 IID_IAMStreamConfig, (void **)p_SC.GetAddressOf() );
2153 if( SUCCEEDED(hr) )
2155 ShowPropertyPage(p_SC.Get());
2160 static void ShowTunerProperties( vlc_object_t *p_this,
2161 ICaptureGraphBuilder2 *p_graph,
2162 IBaseFilter *p_device_filter,
2163 bool b_audio )
2165 HRESULT hr;
2166 msg_Dbg( p_this, "configuring Tuner Properties" );
2168 if( !p_graph || b_audio ) return;
2170 ComPtr<IAMTVTuner> p_TV;
2171 hr = p_graph->FindInterface( &PIN_CATEGORY_CAPTURE,
2172 &MEDIATYPE_Interleaved, p_device_filter,
2173 IID_IAMTVTuner, (void **)p_TV.GetAddressOf() );
2174 if( FAILED(hr) )
2176 hr = p_graph->FindInterface( &PIN_CATEGORY_CAPTURE,
2177 &MEDIATYPE_Video, p_device_filter,
2178 IID_IAMTVTuner, (void **)p_TV.GetAddressOf() );
2181 if( FAILED(hr) )
2183 hr = p_graph->FindInterface( &PIN_CATEGORY_CAPTURE,
2184 &MEDIATYPE_Stream, p_device_filter,
2185 IID_IAMTVTuner, (void **)p_TV.GetAddressOf() );
2188 if( SUCCEEDED(hr) )
2190 ShowPropertyPage(p_TV.Get());
2194 static void ConfigTuner( vlc_object_t *p_this, ICaptureGraphBuilder2 *p_graph,
2195 IBaseFilter *p_device_filter )
2197 int i_channel, i_country, i_input, i_amtuner_mode;
2198 long l_modes = 0;
2199 unsigned i_frequency;
2200 ComPtr<IAMTVTuner> p_TV;
2201 HRESULT hr;
2203 if( !p_graph ) return;
2205 i_channel = var_GetInteger( p_this, "dshow-tuner-channel" );
2206 i_country = var_GetInteger( p_this, "dshow-tuner-country" );
2207 i_input = var_GetInteger( p_this, "dshow-tuner-input" );
2208 i_amtuner_mode = var_GetInteger( p_this, "dshow-amtuner-mode" );
2210 if( !i_channel && !i_country && !i_input ) return; /* Nothing to do */
2212 msg_Dbg( p_this, "tuner config: channel %i, country %i, input type %i",
2213 i_channel, i_country, i_input );
2215 hr = p_graph->FindInterface( &PIN_CATEGORY_CAPTURE, &MEDIATYPE_Interleaved,
2216 p_device_filter, IID_IAMTVTuner,
2217 (void **)p_TV.GetAddressOf() );
2218 if( FAILED(hr) )
2220 hr = p_graph->FindInterface( &PIN_CATEGORY_CAPTURE, &MEDIATYPE_Video,
2221 p_device_filter, IID_IAMTVTuner,
2222 (void **)p_TV.GetAddressOf() );
2225 if( FAILED(hr) )
2227 hr = p_graph->FindInterface( &PIN_CATEGORY_CAPTURE, &MEDIATYPE_Stream,
2228 p_device_filter, IID_IAMTVTuner,
2229 (void **)p_TV.GetAddressOf() );
2232 if( FAILED(hr) )
2234 msg_Dbg( p_this, "couldn't find tuner interface" );
2235 return;
2238 hr = p_TV->GetAvailableModes( &l_modes );
2239 if( SUCCEEDED(hr) && (l_modes & i_amtuner_mode) )
2241 p_TV->put_Mode( (AMTunerModeType)i_amtuner_mode );
2244 if( i_input == 1 ) p_TV->put_InputType( 0, TunerInputCable );
2245 else if( i_input == 2 ) p_TV->put_InputType( 0, TunerInputAntenna );
2247 p_TV->put_CountryCode( i_country );
2248 p_TV->put_Channel( i_channel, AMTUNER_SUBCHAN_NO_TUNE,
2249 AMTUNER_SUBCHAN_NO_TUNE );
2250 p_TV->Release();
2253 } // namespace