Revert "DShow: fix RGB24 Colouring" (fix #21005)
[vlc.git] / modules / access / dshow / dshow.cpp
blob68a379f1cf675cf0216786ab32114495082398bd
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 BGR format */
707 fmt.video.i_bmask = 0x00ff0000;
708 fmt.video.i_gmask = 0x0000ff00;
709 fmt.video.i_rmask = 0x000000ff;
712 if( p_stream->header.video.AvgTimePerFrame )
714 fmt.video.i_frame_rate = 10000000;
715 fmt.video.i_frame_rate_base =
716 p_stream->header.video.AvgTimePerFrame;
719 else if( p_stream->mt.majortype == MEDIATYPE_Audio )
721 es_format_Init( &fmt, AUDIO_ES, p_stream->i_fourcc );
723 fmt.audio.i_channels = p_stream->header.audio.nChannels;
724 fmt.audio.i_rate = p_stream->header.audio.nSamplesPerSec;
725 fmt.audio.i_bitspersample = p_stream->header.audio.wBitsPerSample;
726 fmt.audio.i_blockalign = fmt.audio.i_channels *
727 fmt.audio.i_bitspersample / 8;
728 fmt.i_bitrate = fmt.audio.i_channels * fmt.audio.i_rate *
729 fmt.audio.i_bitspersample;
732 p_stream->p_es = es_out_Add( p_demux->out, &fmt );
735 p_sys->i_start = vlc_tick_now();
736 return VLC_SUCCESS;
739 /*****************************************************************************
740 * AccessOpen: open direct show device as an access module
741 *****************************************************************************/
742 static int AccessOpen( vlc_object_t *p_this )
744 stream_t *p_access = (stream_t*)p_this;
745 access_sys_t *p_sys;
747 p_access->p_sys = p_sys = (access_sys_t*)calloc( 1, sizeof( access_sys_t ) );
748 if( !p_sys )
749 return VLC_ENOMEM;
751 ComContext ctx( COINIT_MULTITHREADED );
753 if( vlc_mta_acquire( p_this ) == false )
755 msg_Err( p_this, "Failed to acquire MTA" );
756 return VLC_EGENERIC;
759 if( CommonOpen( p_this, p_sys, false ) != VLC_SUCCESS )
761 CommonClose( p_this, p_sys );
762 return VLC_EGENERIC;
765 /* Setup Access */
766 p_access->pf_read = NULL;
767 p_access->pf_block = ReadCompressed;
768 p_access->pf_control = AccessControl;
769 p_access->pf_seek = NULL;
770 p_access->p_sys = p_sys;
772 /* Everything is ready. Let's rock baby */
773 msg_Dbg( p_this, "Playing...");
774 if( FAILED( p_sys->p_control->Run() ) )
776 msg_Err( p_this, "Failed to run graph. Capture device may be in use." );
777 CommonClose( p_this, p_sys );
778 return VLC_EGENERIC;
781 return VLC_SUCCESS;
784 /*****************************************************************************
785 * CommonClose: close device
786 *****************************************************************************/
787 static void CommonClose( vlc_object_t *p_this, access_sys_t *p_sys )
789 msg_Dbg( p_this, "releasing DirectShow");
791 DeleteDirectShowGraph( p_this, p_sys );
793 vlc_delete_all( p_sys->pp_streams );
795 vlc_mutex_destroy( &p_sys->lock );
796 vlc_cond_destroy( &p_sys->wait );
798 vlc_mta_release( p_this );
800 free( p_sys );
803 /*****************************************************************************
804 * AccessClose: close device
805 *****************************************************************************/
806 static void AccessClose( vlc_object_t *p_this )
808 stream_t *p_access = (stream_t *)p_this;
809 access_sys_t *p_sys = (access_sys_t *)p_access->p_sys;
811 ComContext ctx( COINIT_MULTITHREADED );
813 /* Stop capturing stuff */
814 p_sys->p_control->Stop();
816 CommonClose( p_this, p_sys );
819 /*****************************************************************************
820 * DemuxClose: close device
821 *****************************************************************************/
822 static void DemuxClose( vlc_object_t *p_this )
824 demux_t *p_demux = (demux_t *)p_this;
825 access_sys_t *p_sys = (access_sys_t *)p_demux->p_sys;
827 ComContext ctx( COINIT_MULTITHREADED );
829 /* Stop capturing stuff */
830 p_sys->p_control->Stop();
832 CommonClose( p_this, p_sys );
835 /****************************************************************************
836 * ConnectFilters
837 ****************************************************************************/
838 static bool ConnectFilters( vlc_object_t *p_this, access_sys_t *p_sys,
839 IBaseFilter *p_filter,
840 CaptureFilter *p_capture_filter )
842 ComPtr<CapturePin> p_input_pin = p_capture_filter->CustomGetPin();
844 AM_MEDIA_TYPE mediaType = p_input_pin->CustomGetMediaType();
846 if( p_sys->p_capture_graph_builder2 )
848 if( FAILED(p_sys->p_capture_graph_builder2->
849 RenderStream( &PIN_CATEGORY_CAPTURE, &mediaType.majortype,
850 p_filter, 0, (IBaseFilter *)p_capture_filter )) )
852 return false;
855 // Sort out all the possible video inputs
856 // The class needs to be given the capture filters ANALOGVIDEO input pin
857 ComPtr<IEnumPins> pins;
858 if( ( mediaType.majortype == MEDIATYPE_Video ||
859 mediaType.majortype == MEDIATYPE_Stream ) &&
860 SUCCEEDED(p_filter->EnumPins(pins.GetAddressOf())) )
862 ComPtr<IPin> pP;
863 ULONG n;
864 PIN_INFO pinInfo;
865 BOOL Found = FALSE;
866 GUID guid;
867 DWORD dw;
869 while( !Found && ( S_OK == pins->Next(1, pP.ReleaseAndGetAddressOf(), &n) ) )
871 if( S_OK == pP->QueryPinInfo(&pinInfo) )
873 ComPtr<IKsPropertySet> pKs;
874 // is this pin an ANALOGVIDEOIN input pin?
875 if( pinInfo.dir == PINDIR_INPUT &&
876 pP->QueryInterface( IID_IKsPropertySet,
877 (void**)pKs.GetAddressOf() ) == S_OK )
879 if( pKs->Get( AMPROPSETID_Pin,
880 AMPROPERTY_PIN_CATEGORY, NULL, 0,
881 &guid, sizeof(GUID), &dw ) == S_OK )
883 if( guid == PIN_CATEGORY_ANALOGVIDEOIN )
885 // recursively search crossbar routes
886 FindCrossbarRoutes( p_this, p_sys, pP.Get(), 0 );
887 // found it
888 Found = TRUE;
892 pinInfo.pFilter->Release();
895 msg_Dbg( p_this, "ConnectFilters: graph_builder2 available.") ;
896 if ( !Found )
897 msg_Warn( p_this, "ConnectFilters: No crossBar routes found (incompatible pin types)" ) ;
899 return true;
901 else
903 ComPtr<IEnumPins> p_enumpins;
904 ComPtr<IPin> p_pin;
906 if( S_OK != p_filter->EnumPins( p_enumpins.GetAddressOf() ) ) return false;
908 while( S_OK == p_enumpins->Next( 1, p_pin.ReleaseAndGetAddressOf(), NULL ) )
910 PIN_DIRECTION pin_dir;
911 p_pin->QueryDirection( &pin_dir );
913 if( pin_dir == PINDIR_OUTPUT &&
914 p_sys->p_graph->ConnectDirect( p_pin.Get(), p_input_pin.Get(),
915 0 ) == S_OK )
917 return true;
920 return false;
925 * get fourcc priority from arbritary preference, the higher the better
927 static int GetFourCCPriority( int i_fourcc )
929 switch( i_fourcc )
931 case VLC_CODEC_I420:
932 case VLC_CODEC_FL32:
933 return 9;
934 case VLC_CODEC_YV12:
935 case VLC_FOURCC('a','r','a','w'):
936 return 8;
937 case VLC_CODEC_RGB24:
938 return 7;
939 case VLC_CODEC_YUYV:
940 case VLC_CODEC_RGB32:
941 case VLC_CODEC_RGBA:
942 return 6;
945 return 0;
948 #define MAX_MEDIA_TYPES 32
950 static int OpenDevice( vlc_object_t *p_this, access_sys_t *p_sys,
951 std::string devicename, bool b_audio )
953 ComPtr<IBaseFilter> p_device_filter;
955 /* See if device is already opened */
956 std::vector<dshow_stream_t*>::iterator it = p_sys->pp_streams.begin();
957 std::vector<dshow_stream_t*>::iterator end = p_sys->pp_streams.end();
958 for ( ; it != end; ++it )
960 if( devicename.size() &&
961 (*it)->devicename == devicename )
963 /* Already opened */
964 wchar_t *pwsz_devicename = ToWide( devicename.c_str() );
966 if( likely( pwsz_devicename ) )
967 p_sys->p_graph->FindFilterByName( pwsz_devicename, p_device_filter.GetAddressOf() );
969 free( pwsz_devicename );
971 if( !p_device_filter )
973 msg_Err( p_this, "Device '%s' already opened, but couldn't be retrieved", devicename.c_str() );
974 return VLC_EGENERIC;
977 break;
981 if( !p_device_filter )
983 std::list<std::string> list_devices;
985 /* Enumerate devices and display their names */
986 FindCaptureDevice( p_this, NULL, &list_devices, b_audio );
987 if( list_devices.empty() )
988 return VLC_EGENERIC;
990 std::list<std::string>::iterator iter;
991 for( iter = list_devices.begin(); iter != list_devices.end(); ++iter )
992 msg_Dbg( p_this, "found device: %s", iter->c_str() );
994 /* If no device name was specified, pick the 1st one */
995 if( devicename.size() == 0 )
997 /* When none selected */
998 devicename = *list_devices.begin();
999 msg_Dbg( p_this, "asking for default device: %s", devicename.c_str() ) ;
1001 else
1002 msg_Dbg( p_this, "asking for device: %s", devicename.c_str() ) ;
1004 // Use the system device enumerator and class enumerator to find
1005 // a capture/preview device, such as a desktop USB video camera.
1006 p_device_filter = FindCaptureDevice( p_this, &devicename, NULL, b_audio );
1008 if( p_device_filter )
1009 msg_Dbg( p_this, "using device: %s", devicename.c_str() );
1010 else
1012 msg_Err( p_this, "can't use device: %s, unsupported device type",
1013 devicename.c_str() );
1014 vlc_dialog_display_error( p_this, _("Capture failed"),
1015 _("The device you selected cannot be used, because its "
1016 "type is not supported.") );
1017 return VLC_EGENERIC;
1020 /* Add the device filter to the graph (seems necessary with VfW before
1021 * accessing pin attributes). */
1023 HRESULT hr = E_FAIL;
1024 wchar_t *pwsz_devicename = ToWide( devicename.c_str() );
1026 if( likely( pwsz_devicename ) )
1027 hr = p_sys->p_graph->AddFilter( p_device_filter.Get(), pwsz_devicename );
1029 free( pwsz_devicename );
1031 if( FAILED( hr ) )
1033 msg_Err( p_this, "Error adding device '%s' to the graph", devicename.c_str() );
1034 return VLC_EGENERIC;
1038 // Retreive acceptable media types supported by device
1039 AM_MEDIA_TYPE media_types[MAX_MEDIA_TYPES];
1040 size_t media_count =
1041 EnumDeviceCaps( p_this, p_device_filter.Get(), b_audio ? 0 : p_sys->i_chroma,
1042 p_sys->i_width, p_sys->i_height,
1043 b_audio ? var_CreateGetInteger( p_this, "dshow-audio-channels" ) : 0,
1044 b_audio ? var_CreateGetInteger( p_this, "dshow-audio-samplerate" ) : 0,
1045 b_audio ? var_CreateGetInteger( p_this, "dshow-audio-bitspersample" ) : 0,
1046 media_types, MAX_MEDIA_TYPES, b_audio );
1048 AM_MEDIA_TYPE *mt = NULL;
1050 if( media_count > 0 )
1052 mt = (AM_MEDIA_TYPE *)CoTaskMemAlloc(sizeof(AM_MEDIA_TYPE) * media_count);
1054 // Order and copy returned media types according to arbitrary
1055 // fourcc priority
1056 for( size_t c = 0; c < media_count; c++ )
1058 int slot_priority =
1059 GetFourCCPriority(GetFourCCFromMediaType(media_types[c]));
1060 size_t slot_copy = c;
1061 for( size_t d = c+1; d < media_count; d++ )
1063 int priority =
1064 GetFourCCPriority(GetFourCCFromMediaType(media_types[d]));
1065 if( priority > slot_priority )
1067 slot_priority = priority;
1068 slot_copy = d;
1071 if( slot_copy != c )
1073 mt[c] = media_types[slot_copy];
1074 media_types[slot_copy] = media_types[c];
1076 else
1078 mt[c] = media_types[c];
1082 else {
1083 /* capture device */
1084 msg_Err( p_this, "capture device '%s' does not support required parameters !", devicename.c_str() );
1085 vlc_dialog_display_error( p_this, _("Capture failed"),
1086 _("The capture device \"%s\" does not support the "
1087 "required parameters."), devicename.c_str() );
1088 return VLC_EGENERIC;
1091 /* Create and add our capture filter */
1092 ComPtr<CaptureFilter> p_capture_filter(
1093 new CaptureFilter( p_this, p_sys, mt, media_count ) );
1094 p_sys->p_graph->AddFilter( p_capture_filter.Get(), 0 );
1096 /* Attempt to connect one of this device's capture output pins */
1097 msg_Dbg( p_this, "connecting filters" );
1098 if( ConnectFilters( p_this, p_sys, p_device_filter.Get(), p_capture_filter.Get() ) )
1100 /* Success */
1101 msg_Dbg( p_this, "filters connected successfully !" );
1103 dshow_stream_t dshow_stream;
1104 dshow_stream.devicename = devicename;
1105 dshow_stream.b_pts = false;
1106 dshow_stream.p_es = 0;
1107 dshow_stream.mt =
1108 p_capture_filter->CustomGetPin()->CustomGetMediaType();
1110 /* Show Device properties. Done here so the VLC stream is setup with
1111 * the proper parameters. */
1112 if( var_GetBool( p_this, "dshow-config" ) )
1114 ShowDeviceProperties( p_this, p_sys->p_capture_graph_builder2.Get(),
1115 p_device_filter.Get(), b_audio );
1118 ConfigTuner( p_this, p_sys->p_capture_graph_builder2.Get(),
1119 p_device_filter.Get() );
1121 if( var_GetBool( p_this, "dshow-tuner" ) &&
1122 dshow_stream.mt.majortype != MEDIATYPE_Stream )
1124 /* FIXME: we do MEDIATYPE_Stream later so we don't do it twice. */
1125 ShowTunerProperties( p_this, p_sys->p_capture_graph_builder2.Get(),
1126 p_device_filter.Get(), b_audio );
1129 dshow_stream.mt =
1130 p_capture_filter->CustomGetPin()->CustomGetMediaType();
1132 dshow_stream.i_fourcc = GetFourCCFromMediaType( dshow_stream.mt );
1133 if( dshow_stream.i_fourcc )
1135 if( dshow_stream.mt.majortype == MEDIATYPE_Video )
1137 dshow_stream.header.video =
1138 *(VIDEOINFOHEADER *)dshow_stream.mt.pbFormat;
1139 msg_Dbg( p_this, "MEDIATYPE_Video" );
1140 msg_Dbg( p_this, "selected video pin accepts format: %4.4s",
1141 (char *)&dshow_stream.i_fourcc);
1143 else if( dshow_stream.mt.majortype == MEDIATYPE_Audio )
1145 dshow_stream.header.audio =
1146 *(WAVEFORMATEX *)dshow_stream.mt.pbFormat;
1147 msg_Dbg( p_this, "MEDIATYPE_Audio" );
1148 msg_Dbg( p_this, "selected audio pin accepts format: %4.4s",
1149 (char *)&dshow_stream.i_fourcc);
1151 else if( dshow_stream.mt.majortype == MEDIATYPE_Stream )
1153 msg_Dbg( p_this, "MEDIATYPE_Stream" );
1154 msg_Dbg( p_this, "selected stream pin accepts format: %4.4s",
1155 (char *)&dshow_stream.i_fourcc);
1157 else
1159 msg_Dbg( p_this, "unknown stream majortype" );
1160 goto fail;
1163 /* Add directshow elementary stream to our list */
1164 dshow_stream.p_device_filter = p_device_filter;
1165 dshow_stream.p_capture_filter = p_capture_filter;
1167 p_sys->pp_streams.push_back( new dshow_stream_t(dshow_stream) );
1169 return VLC_SUCCESS;
1173 fail:
1174 /* Remove filters from graph */
1175 msg_Dbg( p_this, "OpenDevice: Removing filters" ) ;
1176 p_sys->p_graph->RemoveFilter( p_device_filter.Get() );
1177 p_sys->p_graph->RemoveFilter( p_capture_filter.Get() );
1179 return VLC_EGENERIC;
1182 /* FindCaptureDevices:: This Function had two purposes :
1183 Returns the list of capture devices when p_listdevices != NULL
1184 Creates an IBaseFilter when p_devicename corresponds to an existing devname
1185 These actions *may* be requested whith a single call.
1187 static ComPtr<IBaseFilter>
1188 FindCaptureDevice( vlc_object_t *p_this, std::string *p_devicename,
1189 std::list<std::string> *p_listdevices, bool b_audio )
1191 ComPtr<IBaseFilter> p_base_filter;
1192 ComPtr<IMoniker> p_moniker;
1193 ULONG i_fetched;
1194 HRESULT hr;
1195 std::list<std::string> devicelist;
1197 /* Create the system device enumerator */
1198 ComPtr<ICreateDevEnum> p_dev_enum;
1200 hr = CoCreateInstance( CLSID_SystemDeviceEnum, NULL, CLSCTX_INPROC,
1201 IID_ICreateDevEnum, (void**)p_dev_enum.GetAddressOf() );
1202 if( FAILED(hr) )
1204 msg_Err( p_this, "failed to create the device enumerator (0x%lx)", hr);
1205 return p_base_filter;
1208 /* Create an enumerator for the video capture devices */
1209 ComPtr<IEnumMoniker> p_class_enum;
1210 if( !b_audio )
1211 hr = p_dev_enum->CreateClassEnumerator( CLSID_VideoInputDeviceCategory,
1212 p_class_enum.GetAddressOf(), 0 );
1213 else
1214 hr = p_dev_enum->CreateClassEnumerator( CLSID_AudioInputDeviceCategory,
1215 p_class_enum.GetAddressOf(), 0 );
1216 if( FAILED(hr) )
1218 msg_Err( p_this, "failed to create the class enumerator (0x%lx)", hr );
1219 return p_base_filter;
1222 /* If there are no enumerators for the requested type, then
1223 * CreateClassEnumerator will succeed, but p_class_enum will be NULL */
1224 if( p_class_enum == NULL )
1226 msg_Err( p_this, "no %s capture device was detected", ( b_audio ? "audio" : "video" ) );
1227 return p_base_filter;
1230 /* Enumerate the devices */
1232 /* Note that if the Next() call succeeds but there are no monikers,
1233 * it will return S_FALSE (which is not a failure). Therefore, we check
1234 * that the return code is S_OK instead of using SUCCEEDED() macro. */
1236 while( p_class_enum->Next( 1, p_moniker.ReleaseAndGetAddressOf(), &i_fetched ) == S_OK )
1238 /* Getting the property page to get the device name */
1239 ComPtr<IPropertyBag> p_bag;
1240 hr = p_moniker->BindToStorage( 0, 0, IID_IPropertyBag,
1241 (void**)p_bag.GetAddressOf() );
1242 if( SUCCEEDED(hr) )
1244 VARIANT var;
1245 var.vt = VT_BSTR;
1246 hr = p_bag->Read( L"FriendlyName", &var, NULL );
1247 if( SUCCEEDED(hr) )
1249 char *p_buf = FromWide( var.bstrVal );
1250 std::string devname(p_buf);
1251 free( p_buf) ;
1253 int dup = 0;
1254 /* find out if this name is already used by a previously found device */
1255 std::list<std::string>::const_iterator iter = devicelist.begin();
1256 std::list<std::string>::const_iterator end = devicelist.end();
1257 std::string ordevname = devname ;
1258 while ( iter != end )
1260 if( 0 == (*iter).compare( devname ) )
1261 { /* devname is on the list. Try another name with sequence
1262 number apended and then rescan until a unique entry is found*/
1263 char seq[16];
1264 snprintf(seq, 16, " #%d", ++dup);
1265 devname = ordevname + seq;
1266 iter = devicelist.begin();
1268 else
1269 ++iter;
1271 devicelist.push_back( devname );
1273 if( p_devicename && *p_devicename == devname )
1275 msg_Dbg( p_this, "asked for %s, binding to %s", p_devicename->c_str() , devname.c_str() ) ;
1276 /* NULL possibly means we don't need BindMoniker BindCtx ?? */
1277 hr = p_moniker->BindToObject( NULL, 0, IID_IBaseFilter,
1278 (void**)p_base_filter.GetAddressOf() );
1279 if( FAILED(hr) )
1281 msg_Err( p_this, "couldn't bind moniker to filter "
1282 "object (0x%lx)", hr );
1283 return NULL;
1285 return p_base_filter;
1291 if( p_listdevices ) {
1292 devicelist.sort();
1293 *p_listdevices = devicelist;
1295 return p_base_filter;
1298 static size_t EnumDeviceCaps( vlc_object_t *p_this, IBaseFilter *p_filter,
1299 int i_fourcc, int i_width, int i_height,
1300 int i_channels, int i_samplespersec,
1301 int i_bitspersample, AM_MEDIA_TYPE *mt,
1302 size_t mt_max, bool b_audio )
1304 ComPtr<IEnumPins> p_enumpins;
1305 ComPtr<IPin> p_output_pin;
1306 ComPtr<IEnumMediaTypes> p_enummt;
1307 size_t mt_count = 0;
1309 LONGLONG i_AvgTimePerFrame = 0;
1310 float r_fps = var_GetFloat( p_this, "dshow-fps" );
1311 if( r_fps )
1312 i_AvgTimePerFrame = 10000000000LL/(LONGLONG)(r_fps*1000.0f);
1314 if( FAILED(p_filter->EnumPins( p_enumpins.GetAddressOf() )) )
1316 msg_Dbg( p_this, "EnumDeviceCaps failed: no pin enumeration !");
1317 return 0;
1320 while( S_OK == p_enumpins->Next( 1, p_output_pin.ReleaseAndGetAddressOf(), NULL ) )
1322 PIN_INFO info;
1324 if( S_OK == p_output_pin->QueryPinInfo( &info ) )
1326 msg_Dbg( p_this, "EnumDeviceCaps: %s pin: %S",
1327 info.dir == PINDIR_INPUT ? "input" : "output",
1328 info.achName );
1329 if( info.pFilter ) info.pFilter->Release();
1333 p_enumpins->Reset();
1335 while( !mt_count && p_enumpins->Next( 1, p_output_pin.ReleaseAndGetAddressOf(), NULL ) == S_OK )
1337 PIN_INFO info;
1339 if( S_OK == p_output_pin->QueryPinInfo( &info ) )
1341 if( info.pFilter ) info.pFilter->Release();
1342 if( info.dir == PINDIR_INPUT )
1343 continue;
1344 msg_Dbg( p_this, "EnumDeviceCaps: trying pin %S", info.achName );
1347 AM_MEDIA_TYPE *p_mt;
1350 ** Configure pin with a default compatible media if possible
1353 ComPtr<IAMStreamConfig> pSC;
1354 if( SUCCEEDED(p_output_pin->QueryInterface( IID_IAMStreamConfig,
1355 (void**)pSC.GetAddressOf() )) )
1357 int piCount, piSize;
1358 if( SUCCEEDED(pSC->GetNumberOfCapabilities(&piCount, &piSize)) )
1360 BYTE *pSCC= (BYTE *)CoTaskMemAlloc(piSize);
1361 if( NULL != pSCC )
1363 int i_priority = ES_PRIORITY_NOT_DEFAULTABLE;
1364 for( int i=0; i<piCount; ++i )
1366 if( SUCCEEDED(pSC->GetStreamCaps(i, &p_mt, pSCC)) )
1368 int i_current_fourcc = GetFourCCFromMediaType( *p_mt );
1369 int i_current_priority = GetFourCCPriority(i_current_fourcc);
1371 if( (i_fourcc && (i_current_fourcc != i_fourcc))
1372 || (i_priority > i_current_priority) )
1374 // unwanted chroma, try next media type
1375 FreeMediaType( *p_mt );
1376 CoTaskMemFree( (PVOID)p_mt );
1377 continue;
1380 if( !b_audio && MEDIATYPE_Video == p_mt->majortype
1381 && FORMAT_VideoInfo == p_mt->formattype )
1383 VIDEO_STREAM_CONFIG_CAPS *pVSCC = reinterpret_cast<VIDEO_STREAM_CONFIG_CAPS*>(pSCC);
1384 VIDEOINFOHEADER *pVih = reinterpret_cast<VIDEOINFOHEADER*>(p_mt->pbFormat);
1386 if( i_AvgTimePerFrame )
1388 if( pVSCC->MinFrameInterval > i_AvgTimePerFrame
1389 || i_AvgTimePerFrame > pVSCC->MaxFrameInterval )
1391 // required frame rate not compatible, try next media type
1392 FreeMediaType( *p_mt );
1393 CoTaskMemFree( (PVOID)p_mt );
1394 continue;
1396 pVih->AvgTimePerFrame = i_AvgTimePerFrame;
1399 if( i_width )
1401 if(( !pVSCC->OutputGranularityX
1402 && i_width != pVSCC->MinOutputSize.cx
1403 && i_width != pVSCC->MaxOutputSize.cx)
1405 ( pVSCC->OutputGranularityX
1406 && ((i_width % pVSCC->OutputGranularityX)
1407 || pVSCC->MinOutputSize.cx > i_width
1408 || i_width > pVSCC->MaxOutputSize.cx )))
1410 // required width not compatible, try next media type
1411 FreeMediaType( *p_mt );
1412 CoTaskMemFree( (PVOID)p_mt );
1413 continue;
1415 pVih->bmiHeader.biWidth = i_width;
1418 if( i_height )
1420 if(( !pVSCC->OutputGranularityY
1421 && i_height != pVSCC->MinOutputSize.cy
1422 && i_height != pVSCC->MaxOutputSize.cy)
1424 ( pVSCC->OutputGranularityY
1425 && ((i_height % pVSCC->OutputGranularityY)
1426 || pVSCC->MinOutputSize.cy > i_height
1427 || i_height > pVSCC->MaxOutputSize.cy )))
1429 // required height not compatible, try next media type
1430 FreeMediaType( *p_mt );
1431 CoTaskMemFree( (PVOID)p_mt );
1432 continue;
1434 pVih->bmiHeader.biHeight = i_height;
1437 // Set the sample size and image size.
1438 // (Round the image width up to a DWORD boundary.)
1439 p_mt->lSampleSize = pVih->bmiHeader.biSizeImage =
1440 ((pVih->bmiHeader.biWidth + 3) & ~3) *
1441 pVih->bmiHeader.biHeight * (pVih->bmiHeader.biBitCount>>3);
1443 // no cropping, use full video input buffer
1444 memset(&(pVih->rcSource), 0, sizeof(RECT));
1445 memset(&(pVih->rcTarget), 0, sizeof(RECT));
1447 // select this format as default
1448 if( SUCCEEDED( pSC->SetFormat(p_mt) ) )
1450 i_priority = i_current_priority;
1451 if( i_fourcc )
1452 // no need to check any more media types
1453 i = piCount;
1456 else if( b_audio && p_mt->majortype == MEDIATYPE_Audio
1457 && p_mt->formattype == FORMAT_WaveFormatEx )
1459 AUDIO_STREAM_CONFIG_CAPS *pASCC = reinterpret_cast<AUDIO_STREAM_CONFIG_CAPS*>(pSCC);
1460 WAVEFORMATEX *pWfx = reinterpret_cast<WAVEFORMATEX*>(p_mt->pbFormat);
1462 if( i_current_fourcc && (WAVE_FORMAT_PCM == pWfx->wFormatTag) )
1464 int val = i_channels;
1465 if( ! val )
1466 val = 2;
1468 if( ( !pASCC->ChannelsGranularity
1469 && (unsigned int)val != pASCC->MinimumChannels
1470 && (unsigned int)val != pASCC->MaximumChannels)
1472 ( pASCC->ChannelsGranularity
1473 && ((val % pASCC->ChannelsGranularity)
1474 || (unsigned int)val < pASCC->MinimumChannels
1475 || (unsigned int)val > pASCC->MaximumChannels)))
1477 // required number channels not available, try next media type
1478 FreeMediaType( *p_mt );
1479 CoTaskMemFree( (PVOID)p_mt );
1480 continue;
1482 pWfx->nChannels = val;
1484 val = i_samplespersec;
1485 if( ! val )
1486 val = 44100;
1488 if( ( !pASCC->SampleFrequencyGranularity
1489 && (unsigned int)val != pASCC->MinimumSampleFrequency
1490 && (unsigned int)val != pASCC->MaximumSampleFrequency)
1492 ( pASCC->SampleFrequencyGranularity
1493 && ((val % pASCC->SampleFrequencyGranularity)
1494 || (unsigned int)val < pASCC->MinimumSampleFrequency
1495 || (unsigned int)val > pASCC->MaximumSampleFrequency )))
1497 // required sampling rate not available, try next media type
1498 FreeMediaType( *p_mt );
1499 CoTaskMemFree( (PVOID)p_mt );
1500 continue;
1502 pWfx->nSamplesPerSec = val;
1504 val = i_bitspersample;
1505 if( ! val )
1507 if( VLC_CODEC_FL32 == i_current_fourcc )
1508 val = 32;
1509 else
1510 val = 16;
1513 if( ( !pASCC->BitsPerSampleGranularity
1514 && (unsigned int)val != pASCC->MinimumBitsPerSample
1515 && (unsigned int)val != pASCC->MaximumBitsPerSample )
1517 ( pASCC->BitsPerSampleGranularity
1518 && ((val % pASCC->BitsPerSampleGranularity)
1519 || (unsigned int)val < pASCC->MinimumBitsPerSample
1520 || (unsigned int)val > pASCC->MaximumBitsPerSample )))
1522 // required sample size not available, try next media type
1523 FreeMediaType( *p_mt );
1524 CoTaskMemFree( (PVOID)p_mt );
1525 continue;
1528 pWfx->wBitsPerSample = val;
1529 pWfx->nBlockAlign = (pWfx->wBitsPerSample * pWfx->nChannels)/8;
1530 pWfx->nAvgBytesPerSec = pWfx->nSamplesPerSec * pWfx->nBlockAlign;
1532 // select this format as default
1533 if( SUCCEEDED( pSC->SetFormat(p_mt) ) )
1535 i_priority = i_current_priority;
1539 FreeMediaType( *p_mt );
1540 CoTaskMemFree( (PVOID)p_mt );
1543 CoTaskMemFree( (LPVOID)pSCC );
1544 if( i_priority >= ES_PRIORITY_SELECTABLE_MIN )
1545 msg_Dbg( p_this, "EnumDeviceCaps: input pin default format configured");
1551 ** Probe pin for available medias (may be a previously configured one)
1554 if( FAILED( p_output_pin->EnumMediaTypes( p_enummt.ReleaseAndGetAddressOf() ) ) )
1556 continue;
1559 while( p_enummt->Next( 1, &p_mt, NULL ) == S_OK )
1561 int i_current_fourcc = GetFourCCFromMediaType( *p_mt );
1562 if( !b_audio && i_current_fourcc && p_mt->majortype == MEDIATYPE_Video
1563 && p_mt->formattype == FORMAT_VideoInfo )
1565 int i_current_width = ((VIDEOINFOHEADER *)p_mt->pbFormat)->bmiHeader.biWidth;
1566 int i_current_height = ((VIDEOINFOHEADER *)p_mt->pbFormat)->bmiHeader.biHeight;
1567 LONGLONG i_current_atpf = ((VIDEOINFOHEADER *)p_mt->pbFormat)->AvgTimePerFrame;
1569 if( i_current_height < 0 )
1570 i_current_height = -i_current_height;
1572 msg_Dbg( p_this, "EnumDeviceCaps: input pin "
1573 "accepts chroma: %4.4s, width:%i, height:%i, fps:%f",
1574 (char *)&i_current_fourcc, i_current_width,
1575 i_current_height, (10000000.0f/((float)i_current_atpf)) );
1577 if( ( !i_fourcc || i_fourcc == i_current_fourcc ) &&
1578 ( !i_width || i_width == i_current_width ) &&
1579 ( !i_height || i_height == i_current_height ) &&
1580 ( !i_AvgTimePerFrame || i_AvgTimePerFrame == i_current_atpf ) &&
1581 mt_count < mt_max )
1583 /* Pick match */
1584 mt[mt_count++] = *p_mt;
1586 else FreeMediaType( *p_mt );
1588 else if( b_audio && i_current_fourcc && p_mt->majortype == MEDIATYPE_Audio
1589 && p_mt->formattype == FORMAT_WaveFormatEx)
1591 int i_current_channels =
1592 ((WAVEFORMATEX *)p_mt->pbFormat)->nChannels;
1593 int i_current_samplespersec =
1594 ((WAVEFORMATEX *)p_mt->pbFormat)->nSamplesPerSec;
1595 int i_current_bitspersample =
1596 ((WAVEFORMATEX *)p_mt->pbFormat)->wBitsPerSample;
1598 msg_Dbg( p_this, "EnumDeviceCaps: input pin "
1599 "accepts format: %4.4s, channels:%i, "
1600 "samples/sec:%i bits/sample:%i",
1601 (char *)&i_current_fourcc, i_current_channels,
1602 i_current_samplespersec, i_current_bitspersample);
1604 if( (!i_channels || i_channels == i_current_channels) &&
1605 (!i_samplespersec ||
1606 i_samplespersec == i_current_samplespersec) &&
1607 (!i_bitspersample ||
1608 i_bitspersample == i_current_bitspersample) &&
1609 mt_count < mt_max )
1611 /* Pick match */
1612 mt[mt_count++] = *p_mt;
1614 /* Setup a few properties like the audio latency */
1615 ComPtr<IAMBufferNegotiation> p_ambuf;
1616 if( SUCCEEDED( p_output_pin->QueryInterface(
1617 IID_IAMBufferNegotiation, (void **)p_ambuf.GetAddressOf() ) ) )
1619 ALLOCATOR_PROPERTIES AllocProp;
1620 AllocProp.cbAlign = -1;
1622 /* 100 ms of latency */
1623 AllocProp.cbBuffer = i_current_channels *
1624 i_current_samplespersec *
1625 i_current_bitspersample / 8 / 10;
1627 AllocProp.cbPrefix = -1;
1628 AllocProp.cBuffers = -1;
1629 p_ambuf->SuggestAllocatorProperties( &AllocProp );
1632 else FreeMediaType( *p_mt );
1634 else if( i_current_fourcc && p_mt->majortype == MEDIATYPE_Stream )
1636 msg_Dbg( p_this, "EnumDeviceCaps: input pin "
1637 "accepts stream format: %4.4s",
1638 (char *)&i_current_fourcc );
1640 if( ( !i_fourcc || i_fourcc == i_current_fourcc ) &&
1641 mt_count < mt_max )
1643 /* Pick match */
1644 mt[mt_count++] = *p_mt;
1645 i_fourcc = i_current_fourcc;
1647 else FreeMediaType( *p_mt );
1649 else
1651 const char * psz_type = "unknown";
1652 if( p_mt->majortype == MEDIATYPE_Video ) psz_type = "video";
1653 if( p_mt->majortype == MEDIATYPE_Audio ) psz_type = "audio";
1654 if( p_mt->majortype == MEDIATYPE_Stream ) psz_type = "stream";
1655 msg_Dbg( p_this, "EnumDeviceCaps: input pin media: unsupported format "
1656 "(%s %4.4s)", psz_type, (char *)&p_mt->subtype );
1658 FreeMediaType( *p_mt );
1660 CoTaskMemFree( (PVOID)p_mt );
1663 if( !mt_count && p_enummt->Reset() == S_OK )
1665 // VLC did not find any supported MEDIATYPE for this output pin.
1666 // However the graph builder might insert converter filters in
1667 // the graph if we use a different codec in VLC filter input pin.
1668 // however, in order to avoid nasty surprises, make use of this
1669 // facility only for known unsupported codecs.
1671 while( !mt_count && p_enummt->Next( 1, &p_mt, NULL ) == S_OK )
1673 // the first four bytes of subtype GUID contains the codec FOURCC
1674 const char *pfcc = (char *)&p_mt->subtype;
1675 int i_current_fourcc = VLC_FOURCC(pfcc[0], pfcc[1], pfcc[2], pfcc[3]);
1676 if( VLC_FOURCC('H','C','W','2') == i_current_fourcc
1677 && p_mt->majortype == MEDIATYPE_Video && !b_audio )
1679 // output format for 'Hauppauge WinTV PVR PCI II Capture'
1680 // try I420 as an input format
1681 i_current_fourcc = VLC_CODEC_I420;
1682 if( !i_fourcc || i_fourcc == i_current_fourcc )
1684 // return alternative media type
1685 AM_MEDIA_TYPE mtr;
1686 VIDEOINFOHEADER vh;
1688 mtr.majortype = MEDIATYPE_Video;
1689 mtr.subtype = MEDIASUBTYPE_I420;
1690 mtr.bFixedSizeSamples = TRUE;
1691 mtr.bTemporalCompression = FALSE;
1692 mtr.pUnk = NULL;
1693 mtr.formattype = FORMAT_VideoInfo;
1694 mtr.cbFormat = sizeof(vh);
1695 mtr.pbFormat = (BYTE *)&vh;
1697 memset(&vh, 0, sizeof(vh));
1699 vh.bmiHeader.biSize = sizeof(vh.bmiHeader);
1700 vh.bmiHeader.biWidth = i_width > 0 ? i_width :
1701 ((VIDEOINFOHEADER *)p_mt->pbFormat)->bmiHeader.biWidth;
1702 vh.bmiHeader.biHeight = i_height > 0 ? i_height :
1703 ((VIDEOINFOHEADER *)p_mt->pbFormat)->bmiHeader.biHeight;
1704 vh.bmiHeader.biPlanes = 3;
1705 vh.bmiHeader.biBitCount = 12;
1706 vh.bmiHeader.biCompression = VLC_CODEC_I420;
1707 vh.bmiHeader.biSizeImage = vh.bmiHeader.biWidth * 12 *
1708 vh.bmiHeader.biHeight / 8;
1709 mtr.lSampleSize = vh.bmiHeader.biSizeImage;
1711 msg_Dbg( p_this, "EnumDeviceCaps: input pin media: using 'I420' in place of unsupported format 'HCW2'");
1713 if( SUCCEEDED(CopyMediaType(mt+mt_count, &mtr)) )
1714 ++mt_count;
1717 FreeMediaType( *p_mt );
1722 return mt_count;
1725 /*****************************************************************************
1726 * ReadCompressed: reads compressed (MPEG/DV) data from the device.
1727 *****************************************************************************/
1728 static block_t *ReadCompressed( stream_t *p_access, bool *eof )
1730 ComContext ctx( COINIT_MULTITHREADED );
1732 access_sys_t *p_sys = (access_sys_t *)p_access->p_sys;
1733 /* There must be only 1 elementary stream to produce a valid stream
1734 * of MPEG or DV data */
1735 dshow_stream_t *p_stream = p_sys->pp_streams[0];
1736 VLCMediaSample sample;
1738 /* Read 1 DV/MPEG frame (they contain the video and audio data) */
1740 /* Get new sample/frame from the elementary stream (blocking). */
1741 vlc_mutex_lock( &p_sys->lock );
1743 if( p_stream->p_capture_filter->CustomGetPin()->CustomGetSample(&sample) != S_OK )
1744 { /* No data available. Wait until some data has arrived */
1745 vlc_cond_wait( &p_sys->wait, &p_sys->lock );
1746 vlc_mutex_unlock( &p_sys->lock );
1747 return NULL;
1749 vlc_mutex_unlock( &p_sys->lock );
1752 * We got our sample
1754 block_t *p_block = NULL;
1755 uint8_t *p_data;
1756 int i_data_size = sample.p_sample->GetActualDataLength();
1757 if( i_data_size == 0 )
1758 goto out;
1760 p_block = block_Alloc( i_data_size );
1761 if( unlikely(p_block == NULL) )
1762 goto out;
1764 sample.p_sample->GetPointer( &p_data );
1765 memcpy( p_block->p_buffer, p_data, i_data_size );
1766 /* The caller got what he wanted */
1767 out:
1768 (void) eof;
1769 return p_block;
1772 /****************************************************************************
1773 * Demux:
1774 ****************************************************************************/
1775 static int Demux( demux_t *p_demux )
1777 ComContext ctx( COINIT_MULTITHREADED );
1779 access_sys_t *p_sys = (access_sys_t *)p_demux->p_sys;
1780 int i_found_samples;
1782 i_found_samples = 0;
1783 vlc_mutex_lock( &p_sys->lock );
1785 while ( !i_found_samples )
1787 /* Try to grab samples from all streams */
1788 std::vector<dshow_stream_t*>::iterator it = p_sys->pp_streams.begin();
1789 std::vector<dshow_stream_t*>::iterator end = p_sys->pp_streams.end();
1790 for ( ; it != end; ++it )
1792 dshow_stream_t *p_stream = *it;
1793 if( p_stream->p_capture_filter &&
1794 p_stream->p_capture_filter->CustomGetPin()
1795 ->CustomGetSamples( p_stream->samples_queue ) == S_OK )
1797 i_found_samples = 1;
1801 if ( !i_found_samples)
1803 /* Didn't find any audio nor video sample, just wait till the
1804 * dshow thread pushes some samples */
1805 vlc_cond_wait( &p_sys->wait, &p_sys->lock );
1806 /* Some DShow thread pushed data, or the OS broke the wait all
1807 * by itself. In all cases, it's *strongly* advised to test the
1808 * condition again, so let the loop do the test again */
1812 vlc_mutex_unlock( &p_sys->lock );
1814 std::vector<dshow_stream_t*>::iterator it = p_sys->pp_streams.begin();
1815 std::vector<dshow_stream_t*>::iterator end = p_sys->pp_streams.end();
1816 for ( ; it != end; ++it )
1818 int i_samples;
1819 dshow_stream_t *p_stream = *it;
1821 i_samples = p_stream->samples_queue.size();
1822 while ( i_samples > 0 )
1824 int i_data_size;
1825 uint8_t *p_data;
1826 block_t *p_block;
1827 VLCMediaSample sample;
1829 sample = p_stream->samples_queue.front();
1830 p_stream->samples_queue.pop_front();
1832 i_data_size = sample.p_sample->GetActualDataLength();
1833 sample.p_sample->GetPointer( &p_data );
1835 REFERENCE_TIME i_pts, i_end_date;
1836 HRESULT hr = sample.p_sample->GetTime( &i_pts, &i_end_date );
1837 if( hr != S_OK && hr != VFW_S_NO_STOP_TIME )
1839 if( p_stream->mt.majortype == MEDIATYPE_Video || !p_stream->b_pts )
1841 /* Use our data timestamp */
1842 i_pts = MSFTIME_FROM_VLC_TICK(sample.i_timestamp);
1843 p_stream->b_pts = true;
1845 else
1846 i_pts = LONG_MIN;
1849 if( i_pts != LONG_MIN ) {
1850 i_pts += 5;
1852 #if 0
1853 msg_Dbg( p_demux, "Read() stream: %i, size: %i, PTS: %" PRId64,
1854 i_stream, i_data_size, VLC_TICK_FROM_MSFTIME(i_pts) );
1855 #endif
1857 p_block = block_Alloc( i_data_size );
1858 memcpy( p_block->p_buffer, p_data, i_data_size );
1859 p_block->i_pts = p_block->i_dts = i_pts == LONG_MIN ?
1860 VLC_TICK_INVALID : (VLC_TICK_FROM_MSFTIME(i_pts) + VLC_TICK_0);
1862 if( p_block->i_pts != VLC_TICK_INVALID )
1863 es_out_SetPCR( p_demux->out, p_block->i_pts );
1864 es_out_Send( p_demux->out, p_stream->p_es, p_block );
1866 i_samples--;
1870 return 1;
1873 /*****************************************************************************
1874 * AccessControl:
1875 *****************************************************************************/
1876 static int AccessControl( stream_t *p_access, int i_query, va_list args )
1878 access_sys_t *sys = (access_sys_t *)p_access->p_sys;
1879 bool *pb_bool;
1881 switch( i_query )
1883 case STREAM_CAN_SEEK:
1884 case STREAM_CAN_FASTSEEK:
1885 case STREAM_CAN_PAUSE:
1886 case STREAM_CAN_CONTROL_PACE:
1887 pb_bool = va_arg( args, bool * );
1888 *pb_bool = false;
1889 break;
1891 case STREAM_GET_PTS_DELAY:
1892 *va_arg( args, vlc_tick_t * ) =
1893 VLC_TICK_FROM_MS( var_InheritInteger( p_access, "live-caching" ) );
1894 break;
1896 case STREAM_GET_CONTENT_TYPE:
1898 dshow_stream_t *p_stream = sys->pp_streams[0];
1899 char **type = va_arg( args, char ** );
1901 /* Check if we need to force demuxers */
1902 if( p_stream->i_fourcc == VLC_CODEC_DV )
1903 *type = strdup( "video/dv" );
1904 else if( p_stream->i_fourcc == VLC_CODEC_MPGV )
1905 *type = strdup( "video/MP2P" );
1906 else
1907 return VLC_EGENERIC;
1908 break;
1911 default:
1912 return VLC_EGENERIC;
1915 return VLC_SUCCESS;
1918 /****************************************************************************
1919 * DemuxControl:
1920 ****************************************************************************/
1921 static int DemuxControl( demux_t *p_demux, int i_query, va_list args )
1923 bool *pb;
1924 int64_t *pi64;
1926 access_sys_t *p_sys = ( access_sys_t * ) p_demux->p_sys;
1928 switch( i_query )
1930 /* Special for access_demux */
1931 case DEMUX_CAN_PAUSE:
1932 case DEMUX_CAN_SEEK:
1933 case DEMUX_SET_PAUSE_STATE:
1934 case DEMUX_CAN_CONTROL_PACE:
1935 pb = va_arg( args, bool * );
1936 *pb = false;
1937 return VLC_SUCCESS;
1939 case DEMUX_GET_PTS_DELAY:
1940 *va_arg( args, vlc_tick_t * ) =
1941 VLC_TICK_FROM_MS( var_InheritInteger( p_demux, "live-caching" ) );
1942 return VLC_SUCCESS;
1944 case DEMUX_GET_TIME:
1945 pi64 = va_arg( args, int64_t * );
1946 *pi64 = vlc_tick_now() - p_sys->i_start;
1947 return VLC_SUCCESS;
1949 /* TODO implement others */
1950 default:
1951 return VLC_EGENERIC;
1954 return VLC_EGENERIC;
1957 static int AppendAudioEnabledVDevs( vlc_object_t *p_this, std::list<std::string> &audio_list,
1958 std::list<std::string> &video_list )
1960 ComPtr<IFilterGraph> p_graph;
1961 ComPtr<IGraphBuilder> p_gbuilder;
1962 ComPtr<ICaptureGraphBuilder2> p_cgbuilder;
1964 if( FAILED( CoCreateInstance( CLSID_FilterGraph, NULL, CLSCTX_INPROC_SERVER, IID_IFilterGraph,
1965 ( void ** ) p_graph.GetAddressOf() ) ) )
1966 return VLC_EGENERIC;
1968 if( FAILED( p_graph->QueryInterface( IID_IGraphBuilder, ( void ** ) p_gbuilder.GetAddressOf() ) ) )
1969 return VLC_EGENERIC;
1971 if( FAILED( CoCreateInstance( CLSID_CaptureGraphBuilder2, NULL, CLSCTX_INPROC_SERVER,
1972 IID_ICaptureGraphBuilder2, ( void ** ) p_cgbuilder.GetAddressOf() ) ) )
1973 return VLC_EGENERIC;
1975 if( FAILED( p_cgbuilder->SetFiltergraph( p_gbuilder.Get() ) ) )
1976 return VLC_EGENERIC;
1978 for( std::list<std::string>::iterator iter = video_list.begin();
1979 iter != video_list.end();
1980 ++iter )
1982 ComPtr<IBaseFilter> p_device;
1983 ComPtr<IPin> p_pin;
1985 p_device = FindCaptureDevice( p_this, &( *iter ), NULL, false );
1986 if( !p_device ) continue;
1988 if( FAILED( p_gbuilder->AddFilter( p_device.Get(), NULL ) ) )
1989 continue;
1991 if( SUCCEEDED( p_cgbuilder->FindPin( p_device.Get(), PINDIR_OUTPUT, NULL, &MEDIATYPE_Audio,
1992 true, 0, p_pin.GetAddressOf() ) ) )
1993 audio_list.push_back( *iter );
1995 p_gbuilder->RemoveFilter( p_device.Get() );
1998 return VLC_SUCCESS;
2001 /*****************************************************************************
2002 * config variable callback
2003 *****************************************************************************/
2004 static int FindDevices( const char *psz_name, char ***vp, char ***tp )
2006 /* Find list of devices */
2007 std::list<std::string> list_devices;
2010 bool b_audio = !strcmp( psz_name, "dshow-adev" );
2012 // Use STA as this most likely comes from a Qt thread, which is
2013 // initialized as STA.
2014 ComContext ctx( COINIT_APARTMENTTHREADED );
2016 FindCaptureDevice( NULL, NULL, &list_devices, b_audio );
2018 if( b_audio )
2020 std::list<std::string> list_vdevs;
2021 FindCaptureDevice( NULL, NULL, &list_vdevs, false );
2022 if( !list_vdevs.empty() )
2023 AppendAudioEnabledVDevs( NULL, list_devices, list_vdevs );
2026 catch (const std::runtime_error& ex)
2028 msg_Err( (vlc_object_t *)NULL, "Failed fetch devices: %s", ex.what() );
2031 unsigned count = 2 + list_devices.size(), i = 2;
2032 char **values = (char **)xmalloc( count * sizeof(*values) );
2033 char **texts = (char **)xmalloc( count * sizeof(*texts) );
2035 values[0] = strdup( "" );
2036 texts[0] = strdup( _("Default") );
2037 values[1] = strdup( "none" );
2038 texts[1] = strdup( _("None") );
2040 for( std::list<std::string>::iterator iter = list_devices.begin();
2041 iter != list_devices.end();
2042 ++iter )
2044 assert( i < count );
2045 values[i] = strdup( iter->c_str() );
2046 texts[i] = strdup( iter->c_str() );
2047 i++;
2050 *vp = values;
2051 *tp = texts;
2052 return count;
2055 /*****************************************************************************
2056 * Properties
2057 *****************************************************************************/
2059 static void ShowPropertyPage( IUnknown *obj )
2061 ComPtr<ISpecifyPropertyPages> p_spec;
2062 CAUUID cauuid;
2064 HRESULT hr = obj->QueryInterface( IID_ISpecifyPropertyPages,
2065 (void **)p_spec.GetAddressOf() );
2066 if( FAILED(hr) ) return;
2068 if( SUCCEEDED(p_spec->GetPages( &cauuid )) )
2070 if( cauuid.cElems > 0 )
2072 HWND hwnd_desktop = ::GetDesktopWindow();
2074 OleCreatePropertyFrame( hwnd_desktop, 30, 30, NULL, 1, &obj,
2075 cauuid.cElems, cauuid.pElems, 0, 0, NULL );
2077 CoTaskMemFree( cauuid.pElems );
2082 static void ShowDeviceProperties( vlc_object_t *p_this,
2083 ICaptureGraphBuilder2 *p_graph,
2084 IBaseFilter *p_device_filter,
2085 bool b_audio )
2087 HRESULT hr;
2088 msg_Dbg( p_this, "configuring Device Properties" );
2091 * Video or audio capture filter page
2093 ShowPropertyPage( p_device_filter );
2096 * Audio capture pin
2098 if( p_graph && b_audio )
2100 ComPtr<IAMStreamConfig> p_SC;
2102 msg_Dbg( p_this, "showing WDM Audio Configuration Pages" );
2104 hr = p_graph->FindInterface( &PIN_CATEGORY_CAPTURE,
2105 &MEDIATYPE_Audio, p_device_filter,
2106 IID_IAMStreamConfig, (void **)p_SC.GetAddressOf() );
2107 if( SUCCEEDED(hr) )
2109 ShowPropertyPage(p_SC.Get());
2113 * TV Audio filter
2115 ComPtr<IAMTVAudio> p_TVA;
2116 HRESULT hr = p_graph->FindInterface( &PIN_CATEGORY_CAPTURE,
2117 &MEDIATYPE_Audio, p_device_filter,
2118 IID_IAMTVAudio, (void **)p_TVA.GetAddressOf() );
2119 if( SUCCEEDED(hr) )
2121 ShowPropertyPage(p_TVA.Get());
2126 * Video capture pin
2128 if( p_graph && !b_audio )
2130 ComPtr<IAMStreamConfig> p_SC;
2132 msg_Dbg( p_this, "showing WDM Video Configuration Pages" );
2134 hr = p_graph->FindInterface( &PIN_CATEGORY_CAPTURE,
2135 &MEDIATYPE_Interleaved, p_device_filter,
2136 IID_IAMStreamConfig, (void **)p_SC.GetAddressOf() );
2137 if( FAILED(hr) )
2139 hr = p_graph->FindInterface( &PIN_CATEGORY_CAPTURE,
2140 &MEDIATYPE_Video, p_device_filter,
2141 IID_IAMStreamConfig, (void **)p_SC.GetAddressOf() );
2144 if( FAILED(hr) )
2146 hr = p_graph->FindInterface( &PIN_CATEGORY_CAPTURE,
2147 &MEDIATYPE_Stream, p_device_filter,
2148 IID_IAMStreamConfig, (void **)p_SC.GetAddressOf() );
2151 if( SUCCEEDED(hr) )
2153 ShowPropertyPage(p_SC.Get());
2158 static void ShowTunerProperties( vlc_object_t *p_this,
2159 ICaptureGraphBuilder2 *p_graph,
2160 IBaseFilter *p_device_filter,
2161 bool b_audio )
2163 HRESULT hr;
2164 msg_Dbg( p_this, "configuring Tuner Properties" );
2166 if( !p_graph || b_audio ) return;
2168 ComPtr<IAMTVTuner> p_TV;
2169 hr = p_graph->FindInterface( &PIN_CATEGORY_CAPTURE,
2170 &MEDIATYPE_Interleaved, p_device_filter,
2171 IID_IAMTVTuner, (void **)p_TV.GetAddressOf() );
2172 if( FAILED(hr) )
2174 hr = p_graph->FindInterface( &PIN_CATEGORY_CAPTURE,
2175 &MEDIATYPE_Video, p_device_filter,
2176 IID_IAMTVTuner, (void **)p_TV.GetAddressOf() );
2179 if( FAILED(hr) )
2181 hr = p_graph->FindInterface( &PIN_CATEGORY_CAPTURE,
2182 &MEDIATYPE_Stream, p_device_filter,
2183 IID_IAMTVTuner, (void **)p_TV.GetAddressOf() );
2186 if( SUCCEEDED(hr) )
2188 ShowPropertyPage(p_TV.Get());
2192 static void ConfigTuner( vlc_object_t *p_this, ICaptureGraphBuilder2 *p_graph,
2193 IBaseFilter *p_device_filter )
2195 int i_channel, i_country, i_input, i_amtuner_mode;
2196 long l_modes = 0;
2197 unsigned i_frequency;
2198 ComPtr<IAMTVTuner> p_TV;
2199 HRESULT hr;
2201 if( !p_graph ) return;
2203 i_channel = var_GetInteger( p_this, "dshow-tuner-channel" );
2204 i_country = var_GetInteger( p_this, "dshow-tuner-country" );
2205 i_input = var_GetInteger( p_this, "dshow-tuner-input" );
2206 i_amtuner_mode = var_GetInteger( p_this, "dshow-amtuner-mode" );
2208 if( !i_channel && !i_country && !i_input ) return; /* Nothing to do */
2210 msg_Dbg( p_this, "tuner config: channel %i, country %i, input type %i",
2211 i_channel, i_country, i_input );
2213 hr = p_graph->FindInterface( &PIN_CATEGORY_CAPTURE, &MEDIATYPE_Interleaved,
2214 p_device_filter, IID_IAMTVTuner,
2215 (void **)p_TV.GetAddressOf() );
2216 if( FAILED(hr) )
2218 hr = p_graph->FindInterface( &PIN_CATEGORY_CAPTURE, &MEDIATYPE_Video,
2219 p_device_filter, IID_IAMTVTuner,
2220 (void **)p_TV.GetAddressOf() );
2223 if( FAILED(hr) )
2225 hr = p_graph->FindInterface( &PIN_CATEGORY_CAPTURE, &MEDIATYPE_Stream,
2226 p_device_filter, IID_IAMTVTuner,
2227 (void **)p_TV.GetAddressOf() );
2230 if( FAILED(hr) )
2232 msg_Dbg( p_this, "couldn't find tuner interface" );
2233 return;
2236 hr = p_TV->GetAvailableModes( &l_modes );
2237 if( SUCCEEDED(hr) && (l_modes & i_amtuner_mode) )
2239 p_TV->put_Mode( (AMTunerModeType)i_amtuner_mode );
2242 if( i_input == 1 ) p_TV->put_InputType( 0, TunerInputCable );
2243 else if( i_input == 2 ) p_TV->put_InputType( 0, TunerInputAntenna );
2245 p_TV->put_CountryCode( i_country );
2246 p_TV->put_Channel( i_channel, AMTUNER_SUBCHAN_NO_TUNE,
2247 AMTUNER_SUBCHAN_NO_TUNE );
2248 p_TV->Release();
2251 } // namespace