Revert "Add frequency and video standard options in dshow"
[vlc.git] / modules / access / dshow / dshow.cpp
blobc698ac4db8c413dbc3ab3659a75e008d6c042876
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 #define VLC_MODULE_LICENSE VLC_LICENSE_GPL_2_PLUS
40 #include <vlc_common.h>
41 #include <vlc_plugin.h>
42 #include <vlc_access.h>
43 #include <vlc_demux.h>
45 #include <vlc_dialog.h> /* vlc_dialog_display_error */
46 #include <vlc_charset.h> /* FromWide */
48 #include <initguid.h>
49 #include "vlc_dshow.h"
51 #include "access.h"
52 #include "filter.h"
54 #include "../src/win32/mta_holder.h"
56 namespace dshow {
58 /*****************************************************************************
59 * Access: local prototypes
60 *****************************************************************************/
61 static block_t *ReadCompressed( stream_t *, bool * );
62 static int AccessControl ( stream_t *, int, va_list );
64 static int Demux ( demux_t * );
65 static int DemuxControl( demux_t *, int, va_list );
67 static int OpenDevice( vlc_object_t *, access_sys_t *, std::string, bool );
68 static ComPtr<IBaseFilter> FindCaptureDevice( vlc_object_t *, std::string *,
69 std::list<std::string> *, bool );
70 static size_t EnumDeviceCaps( vlc_object_t *, IBaseFilter *,
71 int, int, int, int, int, int,
72 AM_MEDIA_TYPE *mt, size_t, bool );
73 static bool ConnectFilters( vlc_object_t *, access_sys_t *,
74 IBaseFilter *, CaptureFilter * );
75 static int FindDevices( const char *, char ***, char *** );
77 static void ShowPropertyPage( IUnknown * );
78 static void ShowDeviceProperties( vlc_object_t *, ICaptureGraphBuilder2 *,
79 IBaseFilter *, bool );
80 static void ShowTunerProperties( vlc_object_t *, ICaptureGraphBuilder2 *,
81 IBaseFilter *, bool );
82 static void ConfigTuner( vlc_object_t *, ICaptureGraphBuilder2 *,
83 IBaseFilter * );
85 /*****************************************************************************
86 * Module descriptor
87 *****************************************************************************/
88 static const int pi_tuner_input[] = { 0, 1, 2 };
89 static const char *const ppsz_tuner_input_text[] =
90 {N_("Default"), N_("Cable"), N_("Antenna")};
92 static const int pi_amtuner_mode[] = { AMTUNER_MODE_DEFAULT,
93 AMTUNER_MODE_TV,
94 AMTUNER_MODE_FM_RADIO,
95 AMTUNER_MODE_AM_RADIO,
96 AMTUNER_MODE_DSS };
97 static const char *const ppsz_amtuner_mode_text[] = { N_("Default"),
98 N_("TV"),
99 N_("FM radio"),
100 N_("AM radio"),
101 N_("DSS") };
103 #define VDEV_TEXT N_("Video device name")
104 #define VDEV_LONGTEXT N_( \
105 "Name of the video device that will be used by the " \
106 "DirectShow plugin. If you don't specify anything, the default device " \
107 "will be used.")
108 #define ADEV_TEXT N_("Audio device name")
109 #define ADEV_LONGTEXT N_( \
110 "Name of the audio device that will be used by the " \
111 "DirectShow plugin. If you don't specify anything, the default device " \
112 "will be used.")
113 #define SIZE_TEXT N_("Video size")
114 #define SIZE_LONGTEXT N_( \
115 "Size of the video that will be displayed by the " \
116 "DirectShow plugin. If you don't specify anything the default size for " \
117 "your device will be used. You can specify a standard size (cif, d1, ...) or <width>x<height>.")
118 #define ASPECT_TEXT N_("Picture aspect-ratio n:m")
119 #define ASPECT_LONGTEXT N_("Define input picture aspect-ratio to use. Default is 4:3" )
120 #define CHROMA_TEXT N_("Video input chroma format")
121 #define CHROMA_LONGTEXT N_( \
122 "Force the DirectShow video input to use a specific chroma format " \
123 "(eg. I420 (default), RV24, etc.)")
124 #define FPS_TEXT N_("Video input frame rate")
125 #define FPS_LONGTEXT N_( \
126 "Force the DirectShow video input to use a specific frame rate " \
127 "(eg. 0 means default, 25, 29.97, 50, 59.94, etc.)")
128 #define CONFIG_TEXT N_("Device properties")
129 #define CONFIG_LONGTEXT N_( \
130 "Show the properties dialog of the selected device before starting the " \
131 "stream.")
132 #define TUNER_TEXT N_("Tuner properties")
133 #define TUNER_LONGTEXT N_( \
134 "Show the tuner properties [channel selection] page." )
135 #define CHANNEL_TEXT N_("Tuner TV Channel")
136 #define CHANNEL_LONGTEXT N_( \
137 "Set the TV channel the tuner will set to " \
138 "(0 means default)." )
139 #define COUNTRY_TEXT N_("Tuner country code")
140 #define COUNTRY_LONGTEXT N_( \
141 "Set the tuner country code that establishes the current " \
142 "channel-to-frequency mapping (0 means default)." )
143 #define TUNER_INPUT_TEXT N_("Tuner input type")
144 #define TUNER_INPUT_LONGTEXT N_( \
145 "Select the tuner input type (Cable/Antenna)." )
146 #define VIDEO_IN_TEXT N_("Video input pin")
147 #define VIDEO_IN_LONGTEXT N_( \
148 "Select the video input source, such as composite, s-video, " \
149 "or tuner. Since these settings are hardware-specific, you should find good " \
150 "settings in the \"Device config\" area, and use those numbers here. -1 " \
151 "means that settings will not be changed.")
152 #define AUDIO_IN_TEXT N_("Audio input pin")
153 #define AUDIO_IN_LONGTEXT N_( \
154 "Select the audio input source. See the \"video input\" option." )
155 #define VIDEO_OUT_TEXT N_("Video output pin")
156 #define VIDEO_OUT_LONGTEXT N_( \
157 "Select the video output type. See the \"video input\" option." )
158 #define AUDIO_OUT_TEXT N_("Audio output pin")
159 #define AUDIO_OUT_LONGTEXT N_( \
160 "Select the audio output type. See the \"video input\" option." )
162 #define AMTUNER_MODE_TEXT N_("AM Tuner mode")
163 #define AMTUNER_MODE_LONGTEXT N_( \
164 "AM Tuner mode. Can be one of Default (0), TV (1), " \
165 "AM Radio (2), FM Radio (3) or DSS (4).")
167 #define AUDIO_CHANNELS_TEXT N_("Number of audio channels")
168 #define AUDIO_CHANNELS_LONGTEXT N_( \
169 "Select audio input format with the given number of audio channels (if non 0)" )
171 #define AUDIO_SAMPLERATE_TEXT N_("Audio sample rate")
172 #define AUDIO_SAMPLERATE_LONGTEXT N_( \
173 "Select audio input format with the given sample rate (if non 0)" )
175 #define AUDIO_BITSPERSAMPLE_TEXT N_("Audio bits per sample")
176 #define AUDIO_BITSPERSAMPLE_LONGTEXT N_( \
177 "Select audio input format with the given bits/sample (if non 0)" )
179 static int CommonOpen ( vlc_object_t *, access_sys_t *, bool );
180 static void CommonClose( vlc_object_t *, access_sys_t * );
182 static int AccessOpen ( vlc_object_t * );
183 static void AccessClose( vlc_object_t * );
185 static int DemuxOpen ( vlc_object_t * );
186 static void DemuxClose ( vlc_object_t * );
188 } // namespace
190 using namespace dshow;
192 vlc_module_begin ()
193 set_shortname( N_("DirectShow") )
194 set_description( N_("DirectShow input") )
195 set_category( CAT_INPUT )
196 set_subcategory( SUBCAT_INPUT_ACCESS )
197 add_string( "dshow-vdev", NULL, VDEV_TEXT, VDEV_LONGTEXT, false)
198 change_string_cb( FindDevices )
200 add_string( "dshow-adev", NULL, ADEV_TEXT, ADEV_LONGTEXT, false)
201 change_string_cb( FindDevices )
203 add_string( "dshow-size", NULL, SIZE_TEXT, SIZE_LONGTEXT, false)
204 change_safe()
206 add_string( "dshow-aspect-ratio", "4:3", ASPECT_TEXT, ASPECT_LONGTEXT, false)
207 change_safe()
209 add_string( "dshow-chroma", NULL, CHROMA_TEXT, CHROMA_LONGTEXT, true )
210 change_safe()
212 add_float( "dshow-fps", 0.0f, FPS_TEXT, FPS_LONGTEXT, true )
213 change_safe()
215 add_bool( "dshow-config", false, CONFIG_TEXT, CONFIG_LONGTEXT, true )
217 add_bool( "dshow-tuner", false, TUNER_TEXT, TUNER_LONGTEXT, true )
219 add_integer( "dshow-tuner-channel", 0, CHANNEL_TEXT, CHANNEL_LONGTEXT,
220 true )
221 change_safe()
223 add_integer( "dshow-tuner-country", 0, COUNTRY_TEXT, COUNTRY_LONGTEXT,
224 true )
226 add_integer( "dshow-tuner-input", 0, TUNER_INPUT_TEXT,
227 TUNER_INPUT_LONGTEXT, true )
228 change_integer_list( pi_tuner_input, ppsz_tuner_input_text )
229 change_safe()
231 add_integer( "dshow-video-input", -1, VIDEO_IN_TEXT,
232 VIDEO_IN_LONGTEXT, true )
233 change_safe()
235 add_integer( "dshow-video-output", -1, VIDEO_OUT_TEXT,
236 VIDEO_OUT_LONGTEXT, true )
238 add_integer( "dshow-audio-input", -1, AUDIO_IN_TEXT,
239 AUDIO_IN_LONGTEXT, true )
240 change_safe()
242 add_integer( "dshow-audio-output", -1, AUDIO_OUT_TEXT,
243 AUDIO_OUT_LONGTEXT, true )
245 add_integer( "dshow-amtuner-mode", AMTUNER_MODE_TV,
246 AMTUNER_MODE_TEXT, AMTUNER_MODE_LONGTEXT, false)
247 change_integer_list( pi_amtuner_mode, ppsz_amtuner_mode_text )
248 change_safe()
250 add_integer( "dshow-audio-channels", 0, AUDIO_CHANNELS_TEXT,
251 AUDIO_CHANNELS_LONGTEXT, true )
252 add_integer( "dshow-audio-samplerate", 0, AUDIO_SAMPLERATE_TEXT,
253 AUDIO_SAMPLERATE_LONGTEXT, true )
254 add_integer( "dshow-audio-bitspersample", 0, AUDIO_BITSPERSAMPLE_TEXT,
255 AUDIO_BITSPERSAMPLE_LONGTEXT, true )
257 add_shortcut( "dshow" )
258 set_capability( "access", 1 )
259 set_callbacks( DemuxOpen, DemuxClose )
261 add_submodule ()
262 set_description( N_("DirectShow input") )
263 add_shortcut( "dshow" )
264 set_capability( "access", 0 )
265 set_callbacks( AccessOpen, AccessClose )
267 vlc_module_end ()
269 namespace dshow {
271 struct ComContext
273 ComContext( int mode )
275 if( FAILED( CoInitializeEx( NULL, mode ) ) )
276 throw std::runtime_error( "CoInitializeEx failed" );
278 ~ComContext()
280 CoUninitialize();
284 /*****************************************************************************
285 * DirectShow elementary stream descriptor
286 *****************************************************************************/
287 struct dshow_stream_t
289 std::string devicename;
290 ComPtr<IBaseFilter> p_device_filter;
291 ComPtr<CaptureFilter> p_capture_filter;
292 AM_MEDIA_TYPE mt;
294 union
296 VIDEOINFOHEADER video;
297 WAVEFORMATEX audio;
299 } header;
301 int i_fourcc;
302 es_out_id_t *p_es;
304 bool b_pts;
306 std::deque<VLCMediaSample> samples_queue;
309 /*****************************************************************************
310 * DirectShow utility functions
311 *****************************************************************************/
312 static void CreateDirectShowGraph( access_sys_t *p_sys )
314 p_sys->i_crossbar_route_depth = 0;
316 /* Create directshow filter graph */
317 if( SUCCEEDED( CoCreateInstance( CLSID_FilterGraph, 0, CLSCTX_INPROC,
318 (REFIID)IID_IFilterGraph, (void**)p_sys->p_graph.GetAddressOf() ) ) )
320 /* Create directshow capture graph builder if available */
321 if( SUCCEEDED( CoCreateInstance( CLSID_CaptureGraphBuilder2, 0,
322 CLSCTX_INPROC, (REFIID)IID_ICaptureGraphBuilder2,
323 (void**)p_sys->p_capture_graph_builder2.GetAddressOf() ) ) )
325 p_sys->p_capture_graph_builder2->
326 SetFiltergraph((IGraphBuilder *)p_sys->p_graph.Get() );
329 p_sys->p_graph->QueryInterface( IID_IMediaControl,
330 (void**)p_sys->p_control.GetAddressOf() );
334 static void DeleteDirectShowGraph( vlc_object_t *p_this, access_sys_t *p_sys )
336 DeleteCrossbarRoutes( p_sys );
338 /* Remove filters from graph */
339 msg_Dbg( p_this, "DeleteDirectShowGraph: Removing filters" );
340 std::vector<dshow_stream_t*>::iterator it = p_sys->pp_streams.begin();
341 std::vector<dshow_stream_t*>::iterator end = p_sys->pp_streams.end();
342 for( ; it != end; ++it )
344 /* RemoveFilter does an undocumented Release()
345 * but does not set item to NULL */
346 msg_Dbg( p_this, "DeleteDirectShowGraph: Removing capture filter" );
347 p_sys->p_graph->RemoveFilter( (*it)->p_capture_filter.Get() );
348 (*it)->p_capture_filter.Reset();
350 msg_Dbg( p_this, "DeleteDirectShowGraph: Removing device filter" );
351 p_sys->p_graph->RemoveFilter( (*it)->p_device_filter.Get() );
352 (*it)->p_device_filter.Reset();
355 /* Release directshow objects */
356 p_sys->p_control.Reset();
357 p_sys->p_capture_graph_builder2.Reset();
358 p_sys->p_graph.Reset();
361 /*****************************************************************************
362 * CommonOpen: open direct show device
363 *****************************************************************************/
364 static int CommonOpen( vlc_object_t *p_this, access_sys_t *p_sys,
365 bool b_access_demux )
367 char *psz_val;
369 /* Get/parse options and open device(s) */
370 std::string vdevname, adevname;
371 int i_width = 0, i_height = 0;
372 vlc_fourcc_t i_chroma = 0;
373 bool b_use_audio = true;
374 bool b_use_video = true;
376 var_Create( p_this, "dshow-config", VLC_VAR_BOOL | VLC_VAR_DOINHERIT );
377 var_Create( p_this, "dshow-tuner", VLC_VAR_BOOL | VLC_VAR_DOINHERIT );
378 psz_val = var_CreateGetString( p_this, "dshow-vdev" );
379 if( psz_val )
381 msg_Dbg( p_this, "dshow-vdev: %s", psz_val ) ;
382 /* skip none device */
383 if ( strncasecmp( psz_val, "none", 4 ) != 0 )
384 vdevname = std::string( psz_val );
385 else
386 b_use_video = false ;
388 free( psz_val );
390 psz_val = var_CreateGetString( p_this, "dshow-adev" );
391 if( psz_val )
393 msg_Dbg( p_this, "dshow-adev: %s", psz_val ) ;
394 /* skip none device */
395 if ( strncasecmp( psz_val, "none", 4 ) != 0 )
396 adevname = std::string( psz_val );
397 else
398 b_use_audio = false ;
400 free( psz_val );
402 /* DShow Size */
403 static struct {
404 const char *psz_size;
405 int i_width;
406 int i_height;
407 } size_table[] =
408 { { "subqcif", 128, 96 },
409 { "qsif", 160, 120 },
410 { "qcif", 176, 144 },
411 { "sif", 320, 240 },
412 { "cif", 352, 288 },
413 { "d1", 640, 480 },
414 { 0, 0, 0 },
417 psz_val = var_CreateGetString( p_this, "dshow-size" );
418 if( !EMPTY_STR(psz_val) )
420 int i;
421 for( i = 0; size_table[i].psz_size; i++ )
423 if( !strcmp( psz_val, size_table[i].psz_size ) )
425 i_width = size_table[i].i_width;
426 i_height = size_table[i].i_height;
427 break;
430 if( !size_table[i].psz_size ) /* Try to parse "WidthxHeight" */
432 char *psz_parser;
433 i_width = strtol( psz_val, &psz_parser, 0 );
434 if( *psz_parser == 'x' || *psz_parser == 'X')
436 i_height = strtol( psz_parser + 1, &psz_parser, 0 );
438 msg_Dbg( p_this, "width x height %dx%d", i_width, i_height );
441 free( psz_val );
443 /* Chroma */
444 psz_val = var_CreateGetString( p_this, "dshow-chroma" );
445 i_chroma = vlc_fourcc_GetCodecFromString( VIDEO_ES, psz_val );
446 free( psz_val );
448 var_Create( p_this, "dshow-fps", VLC_VAR_FLOAT | VLC_VAR_DOINHERIT );
449 var_Create( p_this, "dshow-tuner-channel",
450 VLC_VAR_INTEGER | VLC_VAR_DOINHERIT );
451 var_Create( p_this, "dshow-tuner-country",
452 VLC_VAR_INTEGER | VLC_VAR_DOINHERIT );
453 var_Create( p_this, "dshow-tuner-input",
454 VLC_VAR_INTEGER | VLC_VAR_DOINHERIT );
456 var_Create( p_this, "dshow-amtuner-mode",
457 VLC_VAR_INTEGER | VLC_VAR_DOINHERIT );
459 var_Create( p_this, "dshow-video-input", VLC_VAR_INTEGER | VLC_VAR_DOINHERIT );
460 var_Create( p_this, "dshow-audio-input", VLC_VAR_INTEGER | VLC_VAR_DOINHERIT );
461 var_Create( p_this, "dshow-video-output", VLC_VAR_INTEGER | VLC_VAR_DOINHERIT );
462 var_Create( p_this, "dshow-audio-output", VLC_VAR_INTEGER | VLC_VAR_DOINHERIT );
465 /* Initialize some data */
466 p_sys->i_width = i_width;
467 p_sys->i_height = i_height;
468 p_sys->i_chroma = i_chroma;
470 /* Build directshow graph */
471 CreateDirectShowGraph( p_sys );
473 vlc_mutex_init( &p_sys->lock );
474 vlc_cond_init( &p_sys->wait );
476 if( !b_use_video && !b_use_audio )
478 vlc_dialog_display_error( p_this, _("Capture failed"),
479 _("No video or audio device selected.") );
480 return VLC_EGENERIC ;
483 if( !b_use_video )
484 msg_Dbg( p_this, "skipping video device" ) ;
485 bool b_err_video = false ;
487 if( b_use_video && OpenDevice( p_this, p_sys, vdevname, 0 ) != VLC_SUCCESS )
489 msg_Err( p_this, "can't open video device");
490 b_err_video = true ;
493 if ( b_use_video && !b_err_video )
495 /* Check if we can handle the demuxing ourselves or need to spawn
496 * a demuxer module */
497 dshow_stream_t *p_stream = *(p_sys->pp_streams.rbegin());
499 if( p_stream->mt.majortype == MEDIATYPE_Video )
501 if( /* Raw DV stream */
502 p_stream->i_fourcc == VLC_CODEC_DV ||
503 /* Raw MPEG video stream */
504 p_stream->i_fourcc == VLC_CODEC_MPGV )
506 b_use_audio = false;
508 if( b_access_demux )
510 /* Let the access (only) take care of that */
511 return VLC_EGENERIC;
516 if( p_stream->mt.majortype == MEDIATYPE_Stream )
518 b_use_audio = false;
520 if( b_access_demux )
522 /* Let the access (only) take care of that */
523 return VLC_EGENERIC;
526 if( var_GetBool( p_this, "dshow-tuner" ) )
528 /* FIXME: we do MEDIATYPE_Stream here so we don't do
529 * it twice. */
530 ShowTunerProperties( p_this, p_sys->p_capture_graph_builder2.Get(),
531 p_stream->p_device_filter.Get(), 0 );
536 if( !b_use_audio )
537 msg_Dbg( p_this, "skipping audio device") ;
539 bool b_err_audio = false ;
541 if( b_use_audio && OpenDevice( p_this, p_sys, adevname, 1 ) != VLC_SUCCESS )
543 msg_Err( p_this, "can't open audio device");
544 b_err_audio = true ;
547 if( ( b_use_video && b_err_video && b_use_audio && b_err_audio ) ||
548 ( !b_use_video && b_use_audio && b_err_audio ) ||
549 ( b_use_video && !b_use_audio && b_err_video ) )
551 msg_Err( p_this, "FATAL: could not open ANY device" ) ;
552 vlc_dialog_display_error( p_this, _("Capture failed"),
553 _("VLC cannot open ANY capture device. "
554 "Check the error log for details.") );
555 return VLC_EGENERIC ;
558 for( int i = p_sys->i_crossbar_route_depth-1; i >= 0 ; --i )
560 int i_val = var_GetInteger( p_this, "dshow-video-input" );
561 if( i_val >= 0 )
562 p_sys->crossbar_routes[i].VideoInputIndex = i_val;
563 i_val = var_GetInteger( p_this, "dshow-video-output" );
564 if( i_val >= 0 )
565 p_sys->crossbar_routes[i].VideoOutputIndex = i_val;
566 i_val = var_GetInteger( p_this, "dshow-audio-input" );
567 if( i_val >= 0 )
568 p_sys->crossbar_routes[i].AudioInputIndex = i_val;
569 i_val = var_GetInteger( p_this, "dshow-audio-output" );
570 if( i_val >= 0 )
571 p_sys->crossbar_routes[i].AudioOutputIndex = i_val;
573 IAMCrossbar *pXbar = p_sys->crossbar_routes[i].pXbar.Get();
574 LONG VideoInputIndex = p_sys->crossbar_routes[i].VideoInputIndex;
575 LONG VideoOutputIndex = p_sys->crossbar_routes[i].VideoOutputIndex;
576 LONG AudioInputIndex = p_sys->crossbar_routes[i].AudioInputIndex;
577 LONG AudioOutputIndex = p_sys->crossbar_routes[i].AudioOutputIndex;
579 if( SUCCEEDED(pXbar->Route(VideoOutputIndex, VideoInputIndex)) )
581 msg_Dbg( p_this, "crossbar at depth %d, routed video "
582 "output %ld to video input %ld", i, VideoOutputIndex,
583 VideoInputIndex );
585 if( AudioOutputIndex != -1 && AudioInputIndex != -1 )
587 if( SUCCEEDED( pXbar->Route(AudioOutputIndex,
588 AudioInputIndex)) )
590 msg_Dbg(p_this, "crossbar at depth %d, routed audio "
591 "output %ld to audio input %ld", i,
592 AudioOutputIndex, AudioInputIndex );
596 else
597 msg_Err( p_this, "crossbar at depth %d could not route video "
598 "output %ld to input %ld", i, VideoOutputIndex, VideoInputIndex );
602 ** Show properties pages from other filters in graph
604 if( var_GetBool( p_this, "dshow-config" ) )
606 for( int i = p_sys->i_crossbar_route_depth-1; i >= 0 ; --i )
608 IAMCrossbar *pXbar = p_sys->crossbar_routes[i].pXbar.Get();
609 ComPtr<IBaseFilter> p_XF;
611 if( SUCCEEDED( pXbar->QueryInterface( IID_IBaseFilter,
612 (void**)p_XF.ReleaseAndGetAddressOf() ) ) )
614 ShowPropertyPage( p_XF.Get() );
619 /* Initialize some data */
620 p_sys->i_current_stream = 0;
622 if( p_sys->pp_streams.empty() ) return VLC_EGENERIC;
624 return VLC_SUCCESS;
627 /*****************************************************************************
628 * DemuxOpen: open direct show device as an access_demux module
629 *****************************************************************************/
630 static int DemuxOpen( vlc_object_t *p_this )
632 demux_t *p_demux = (demux_t *)p_this;
633 access_sys_t *p_sys;
635 if (p_demux->out == NULL)
636 return VLC_EGENERIC;
638 p_sys = (access_sys_t*)calloc( 1, sizeof( access_sys_t ) );
639 if( !p_sys )
640 return VLC_ENOMEM;
641 p_demux->p_sys = (demux_sys_t *)p_sys;
643 ComContext ctx( COINIT_MULTITHREADED );
645 if( vlc_mta_acquire( p_this ) == false )
647 msg_Err( p_this, "Failed to acquire MTA" );
648 return VLC_EGENERIC;
651 if( CommonOpen( p_this, p_sys, true ) != VLC_SUCCESS )
653 CommonClose( p_this, p_sys );
654 return VLC_EGENERIC;
657 /* Everything is ready. Let's rock baby */
658 msg_Dbg( p_this, "Playing...");
659 if( FAILED( p_sys->p_control->Run() ) )
661 msg_Err( p_this, "Failed to run graph. Capture device may be in use." );
662 CommonClose( p_this, p_sys );
663 return VLC_EGENERIC;
666 p_demux->pf_demux = Demux;
667 p_demux->pf_control = DemuxControl;
669 std::vector<dshow_stream_t*>::iterator it = p_sys->pp_streams.begin();
670 std::vector<dshow_stream_t*>::iterator end = p_sys->pp_streams.end();
671 for ( ; it != end; ++it )
673 dshow_stream_t *p_stream = *it;
674 es_format_t fmt;
676 if( p_stream->mt.majortype == MEDIATYPE_Video )
678 char *psz_aspect = var_CreateGetString( p_this, "dshow-aspect-ratio" );
679 char *psz_delim = !EMPTY_STR( psz_aspect ) ? strchr( psz_aspect, ':' ) : NULL;
681 es_format_Init( &fmt, VIDEO_ES, p_stream->i_fourcc );
683 fmt.video.i_width = p_stream->header.video.bmiHeader.biWidth;
684 fmt.video.i_height = p_stream->header.video.bmiHeader.biHeight;
686 if( psz_delim )
688 fmt.video.i_sar_num = atoi( psz_aspect ) * fmt.video.i_height;
689 fmt.video.i_sar_den = atoi( psz_delim + 1 ) * fmt.video.i_width;
691 else
693 fmt.video.i_sar_num = 4 * fmt.video.i_height;
694 fmt.video.i_sar_den = 3 * fmt.video.i_width;
696 free( psz_aspect );
698 if( !p_stream->header.video.bmiHeader.biCompression )
700 /* RGB DIB are coded from bottom to top */
701 fmt.video.orientation = ORIENT_BOTTOM_LEFT;
704 /* Setup rgb mask for RGB formats */
705 if( p_stream->i_fourcc == VLC_CODEC_RGB24 )
707 /* This is in RGB format
708 http://msdn.microsoft.com/en-us/library/dd407253%28VS.85%29.aspx?ppud=4
710 fmt.video.i_rmask = 0x00ff0000;
711 fmt.video.i_gmask = 0x0000ff00;
712 fmt.video.i_bmask = 0x000000ff;
715 if( p_stream->header.video.AvgTimePerFrame )
717 fmt.video.i_frame_rate = 10000000;
718 fmt.video.i_frame_rate_base =
719 p_stream->header.video.AvgTimePerFrame;
722 else if( p_stream->mt.majortype == MEDIATYPE_Audio )
724 es_format_Init( &fmt, AUDIO_ES, p_stream->i_fourcc );
726 fmt.audio.i_channels = p_stream->header.audio.nChannels;
727 fmt.audio.i_rate = p_stream->header.audio.nSamplesPerSec;
728 fmt.audio.i_bitspersample = p_stream->header.audio.wBitsPerSample;
729 fmt.audio.i_blockalign = fmt.audio.i_channels *
730 fmt.audio.i_bitspersample / 8;
731 fmt.i_bitrate = fmt.audio.i_channels * fmt.audio.i_rate *
732 fmt.audio.i_bitspersample;
735 p_stream->p_es = es_out_Add( p_demux->out, &fmt );
738 p_sys->i_start = vlc_tick_now();
739 return VLC_SUCCESS;
742 /*****************************************************************************
743 * AccessOpen: open direct show device as an access module
744 *****************************************************************************/
745 static int AccessOpen( vlc_object_t *p_this )
747 stream_t *p_access = (stream_t*)p_this;
748 access_sys_t *p_sys;
750 p_access->p_sys = p_sys = (access_sys_t*)calloc( 1, sizeof( access_sys_t ) );
751 if( !p_sys )
752 return VLC_ENOMEM;
754 ComContext ctx( COINIT_MULTITHREADED );
756 if( vlc_mta_acquire( p_this ) == false )
758 msg_Err( p_this, "Failed to acquire MTA" );
759 return VLC_EGENERIC;
762 if( CommonOpen( p_this, p_sys, false ) != VLC_SUCCESS )
764 CommonClose( p_this, p_sys );
765 return VLC_EGENERIC;
768 /* Setup Access */
769 p_access->pf_read = NULL;
770 p_access->pf_block = ReadCompressed;
771 p_access->pf_control = AccessControl;
772 p_access->pf_seek = NULL;
773 p_access->p_sys = p_sys;
775 /* Everything is ready. Let's rock baby */
776 msg_Dbg( p_this, "Playing...");
777 if( FAILED( p_sys->p_control->Run() ) )
779 msg_Err( p_this, "Failed to run graph. Capture device may be in use." );
780 CommonClose( p_this, p_sys );
781 return VLC_EGENERIC;
784 return VLC_SUCCESS;
787 /*****************************************************************************
788 * CommonClose: close device
789 *****************************************************************************/
790 static void CommonClose( vlc_object_t *p_this, access_sys_t *p_sys )
792 msg_Dbg( p_this, "releasing DirectShow");
794 DeleteDirectShowGraph( p_this, p_sys );
796 vlc_delete_all( p_sys->pp_streams );
798 vlc_mutex_destroy( &p_sys->lock );
799 vlc_cond_destroy( &p_sys->wait );
801 vlc_mta_release( p_this );
803 free( p_sys );
806 /*****************************************************************************
807 * AccessClose: close device
808 *****************************************************************************/
809 static void AccessClose( vlc_object_t *p_this )
811 stream_t *p_access = (stream_t *)p_this;
812 access_sys_t *p_sys = (access_sys_t *)p_access->p_sys;
814 ComContext ctx( COINIT_MULTITHREADED );
816 /* Stop capturing stuff */
817 p_sys->p_control->Stop();
819 CommonClose( p_this, p_sys );
822 /*****************************************************************************
823 * DemuxClose: close device
824 *****************************************************************************/
825 static void DemuxClose( vlc_object_t *p_this )
827 demux_t *p_demux = (demux_t *)p_this;
828 access_sys_t *p_sys = (access_sys_t *)p_demux->p_sys;
830 ComContext ctx( COINIT_MULTITHREADED );
832 /* Stop capturing stuff */
833 p_sys->p_control->Stop();
835 CommonClose( p_this, p_sys );
838 /****************************************************************************
839 * ConnectFilters
840 ****************************************************************************/
841 static bool ConnectFilters( vlc_object_t *p_this, access_sys_t *p_sys,
842 IBaseFilter *p_filter,
843 CaptureFilter *p_capture_filter )
845 ComPtr<CapturePin> p_input_pin = p_capture_filter->CustomGetPin();
847 AM_MEDIA_TYPE mediaType = p_input_pin->CustomGetMediaType();
849 if( p_sys->p_capture_graph_builder2 )
851 if( FAILED(p_sys->p_capture_graph_builder2->
852 RenderStream( &PIN_CATEGORY_CAPTURE, &mediaType.majortype,
853 p_filter, 0, (IBaseFilter *)p_capture_filter )) )
855 return false;
858 // Sort out all the possible video inputs
859 // The class needs to be given the capture filters ANALOGVIDEO input pin
860 ComPtr<IEnumPins> pins;
861 if( ( mediaType.majortype == MEDIATYPE_Video ||
862 mediaType.majortype == MEDIATYPE_Stream ) &&
863 SUCCEEDED(p_filter->EnumPins(pins.GetAddressOf())) )
865 ComPtr<IPin> pP;
866 ULONG n;
867 PIN_INFO pinInfo;
868 BOOL Found = FALSE;
869 GUID guid;
870 DWORD dw;
872 while( !Found && ( S_OK == pins->Next(1, pP.ReleaseAndGetAddressOf(), &n) ) )
874 if( S_OK == pP->QueryPinInfo(&pinInfo) )
876 ComPtr<IKsPropertySet> pKs;
877 // is this pin an ANALOGVIDEOIN input pin?
878 if( pinInfo.dir == PINDIR_INPUT &&
879 pP->QueryInterface( IID_IKsPropertySet,
880 (void**)pKs.GetAddressOf() ) == S_OK )
882 if( pKs->Get( AMPROPSETID_Pin,
883 AMPROPERTY_PIN_CATEGORY, NULL, 0,
884 &guid, sizeof(GUID), &dw ) == S_OK )
886 if( guid == PIN_CATEGORY_ANALOGVIDEOIN )
888 // recursively search crossbar routes
889 FindCrossbarRoutes( p_this, p_sys, pP.Get(), 0 );
890 // found it
891 Found = TRUE;
895 pinInfo.pFilter->Release();
898 msg_Dbg( p_this, "ConnectFilters: graph_builder2 available.") ;
899 if ( !Found )
900 msg_Warn( p_this, "ConnectFilters: No crossBar routes found (incompatible pin types)" ) ;
902 return true;
904 else
906 ComPtr<IEnumPins> p_enumpins;
907 ComPtr<IPin> p_pin;
909 if( S_OK != p_filter->EnumPins( p_enumpins.GetAddressOf() ) ) return false;
911 while( S_OK == p_enumpins->Next( 1, p_pin.ReleaseAndGetAddressOf(), NULL ) )
913 PIN_DIRECTION pin_dir;
914 p_pin->QueryDirection( &pin_dir );
916 if( pin_dir == PINDIR_OUTPUT &&
917 p_sys->p_graph->ConnectDirect( p_pin.Get(), p_input_pin.Get(),
918 0 ) == S_OK )
920 return true;
923 return false;
928 * get fourcc priority from arbritary preference, the higher the better
930 static int GetFourCCPriority( int i_fourcc )
932 switch( i_fourcc )
934 case VLC_CODEC_I420:
935 case VLC_CODEC_FL32:
936 return 9;
937 case VLC_CODEC_YV12:
938 case VLC_FOURCC('a','r','a','w'):
939 return 8;
940 case VLC_CODEC_RGB24:
941 return 7;
942 case VLC_CODEC_YUYV:
943 case VLC_CODEC_RGB32:
944 case VLC_CODEC_RGBA:
945 return 6;
948 return 0;
951 #define MAX_MEDIA_TYPES 32
953 static int OpenDevice( vlc_object_t *p_this, access_sys_t *p_sys,
954 std::string devicename, bool b_audio )
956 ComPtr<IBaseFilter> p_device_filter;
958 /* See if device is already opened */
959 std::vector<dshow_stream_t*>::iterator it = p_sys->pp_streams.begin();
960 std::vector<dshow_stream_t*>::iterator end = p_sys->pp_streams.end();
961 for ( ; it != end; ++it )
963 if( devicename.size() &&
964 (*it)->devicename == devicename )
966 /* Already opened */
967 wchar_t *pwsz_devicename = ToWide( devicename.c_str() );
969 if( likely( pwsz_devicename ) )
970 p_sys->p_graph->FindFilterByName( pwsz_devicename, p_device_filter.GetAddressOf() );
972 free( pwsz_devicename );
974 if( !p_device_filter )
976 msg_Err( p_this, "Device '%s' already opened, but couldn't be retrieved", devicename.c_str() );
977 return VLC_EGENERIC;
980 break;
984 if( !p_device_filter )
986 std::list<std::string> list_devices;
988 /* Enumerate devices and display their names */
989 FindCaptureDevice( p_this, NULL, &list_devices, b_audio );
990 if( list_devices.empty() )
991 return VLC_EGENERIC;
993 std::list<std::string>::iterator iter;
994 for( iter = list_devices.begin(); iter != list_devices.end(); ++iter )
995 msg_Dbg( p_this, "found device: %s", iter->c_str() );
997 /* If no device name was specified, pick the 1st one */
998 if( devicename.size() == 0 )
1000 /* When none selected */
1001 devicename = *list_devices.begin();
1002 msg_Dbg( p_this, "asking for default device: %s", devicename.c_str() ) ;
1004 else
1005 msg_Dbg( p_this, "asking for device: %s", devicename.c_str() ) ;
1007 // Use the system device enumerator and class enumerator to find
1008 // a capture/preview device, such as a desktop USB video camera.
1009 p_device_filter = FindCaptureDevice( p_this, &devicename, NULL, b_audio );
1011 if( p_device_filter )
1012 msg_Dbg( p_this, "using device: %s", devicename.c_str() );
1013 else
1015 msg_Err( p_this, "can't use device: %s, unsupported device type",
1016 devicename.c_str() );
1017 vlc_dialog_display_error( p_this, _("Capture failed"),
1018 _("The device you selected cannot be used, because its "
1019 "type is not supported.") );
1020 return VLC_EGENERIC;
1023 /* Add the device filter to the graph (seems necessary with VfW before
1024 * accessing pin attributes). */
1026 HRESULT hr = E_FAIL;
1027 wchar_t *pwsz_devicename = ToWide( devicename.c_str() );
1029 if( likely( pwsz_devicename ) )
1030 hr = p_sys->p_graph->AddFilter( p_device_filter.Get(), pwsz_devicename );
1032 free( pwsz_devicename );
1034 if( FAILED( hr ) )
1036 msg_Err( p_this, "Error adding device '%s' to the graph", devicename.c_str() );
1037 return VLC_EGENERIC;
1041 // Retreive acceptable media types supported by device
1042 AM_MEDIA_TYPE media_types[MAX_MEDIA_TYPES];
1043 size_t media_count =
1044 EnumDeviceCaps( p_this, p_device_filter.Get(), b_audio ? 0 : p_sys->i_chroma,
1045 p_sys->i_width, p_sys->i_height,
1046 b_audio ? var_CreateGetInteger( p_this, "dshow-audio-channels" ) : 0,
1047 b_audio ? var_CreateGetInteger( p_this, "dshow-audio-samplerate" ) : 0,
1048 b_audio ? var_CreateGetInteger( p_this, "dshow-audio-bitspersample" ) : 0,
1049 media_types, MAX_MEDIA_TYPES, b_audio );
1051 AM_MEDIA_TYPE *mt = NULL;
1053 if( media_count > 0 )
1055 mt = (AM_MEDIA_TYPE *)CoTaskMemAlloc(sizeof(AM_MEDIA_TYPE) * media_count);
1057 // Order and copy returned media types according to arbitrary
1058 // fourcc priority
1059 for( size_t c = 0; c < media_count; c++ )
1061 int slot_priority =
1062 GetFourCCPriority(GetFourCCFromMediaType(media_types[c]));
1063 size_t slot_copy = c;
1064 for( size_t d = c+1; d < media_count; d++ )
1066 int priority =
1067 GetFourCCPriority(GetFourCCFromMediaType(media_types[d]));
1068 if( priority > slot_priority )
1070 slot_priority = priority;
1071 slot_copy = d;
1074 if( slot_copy != c )
1076 mt[c] = media_types[slot_copy];
1077 media_types[slot_copy] = media_types[c];
1079 else
1081 mt[c] = media_types[c];
1085 else {
1086 /* capture device */
1087 msg_Err( p_this, "capture device '%s' does not support required parameters !", devicename.c_str() );
1088 vlc_dialog_display_error( p_this, _("Capture failed"),
1089 _("The capture device \"%s\" does not support the "
1090 "required parameters."), devicename.c_str() );
1091 return VLC_EGENERIC;
1094 /* Create and add our capture filter */
1095 ComPtr<CaptureFilter> p_capture_filter(
1096 new CaptureFilter( p_this, p_sys, mt, media_count ) );
1097 p_sys->p_graph->AddFilter( p_capture_filter.Get(), 0 );
1099 /* Attempt to connect one of this device's capture output pins */
1100 msg_Dbg( p_this, "connecting filters" );
1101 if( ConnectFilters( p_this, p_sys, p_device_filter.Get(), p_capture_filter.Get() ) )
1103 /* Success */
1104 msg_Dbg( p_this, "filters connected successfully !" );
1106 dshow_stream_t dshow_stream;
1107 dshow_stream.devicename = devicename;
1108 dshow_stream.b_pts = false;
1109 dshow_stream.p_es = 0;
1110 dshow_stream.mt =
1111 p_capture_filter->CustomGetPin()->CustomGetMediaType();
1113 /* Show Device properties. Done here so the VLC stream is setup with
1114 * the proper parameters. */
1115 if( var_GetBool( p_this, "dshow-config" ) )
1117 ShowDeviceProperties( p_this, p_sys->p_capture_graph_builder2.Get(),
1118 p_device_filter.Get(), b_audio );
1121 ConfigTuner( p_this, p_sys->p_capture_graph_builder2.Get(),
1122 p_device_filter.Get() );
1124 if( var_GetBool( p_this, "dshow-tuner" ) &&
1125 dshow_stream.mt.majortype != MEDIATYPE_Stream )
1127 /* FIXME: we do MEDIATYPE_Stream later so we don't do it twice. */
1128 ShowTunerProperties( p_this, p_sys->p_capture_graph_builder2.Get(),
1129 p_device_filter.Get(), b_audio );
1132 dshow_stream.mt =
1133 p_capture_filter->CustomGetPin()->CustomGetMediaType();
1135 dshow_stream.i_fourcc = GetFourCCFromMediaType( dshow_stream.mt );
1136 if( dshow_stream.i_fourcc )
1138 if( dshow_stream.mt.majortype == MEDIATYPE_Video )
1140 dshow_stream.header.video =
1141 *(VIDEOINFOHEADER *)dshow_stream.mt.pbFormat;
1142 msg_Dbg( p_this, "MEDIATYPE_Video" );
1143 msg_Dbg( p_this, "selected video pin accepts format: %4.4s",
1144 (char *)&dshow_stream.i_fourcc);
1146 else if( dshow_stream.mt.majortype == MEDIATYPE_Audio )
1148 dshow_stream.header.audio =
1149 *(WAVEFORMATEX *)dshow_stream.mt.pbFormat;
1150 msg_Dbg( p_this, "MEDIATYPE_Audio" );
1151 msg_Dbg( p_this, "selected audio pin accepts format: %4.4s",
1152 (char *)&dshow_stream.i_fourcc);
1154 else if( dshow_stream.mt.majortype == MEDIATYPE_Stream )
1156 msg_Dbg( p_this, "MEDIATYPE_Stream" );
1157 msg_Dbg( p_this, "selected stream pin accepts format: %4.4s",
1158 (char *)&dshow_stream.i_fourcc);
1160 else
1162 msg_Dbg( p_this, "unknown stream majortype" );
1163 goto fail;
1166 /* Add directshow elementary stream to our list */
1167 dshow_stream.p_device_filter = p_device_filter;
1168 dshow_stream.p_capture_filter = p_capture_filter;
1170 p_sys->pp_streams.push_back( new dshow_stream_t(dshow_stream) );
1172 return VLC_SUCCESS;
1176 fail:
1177 /* Remove filters from graph */
1178 msg_Dbg( p_this, "OpenDevice: Removing filters" ) ;
1179 p_sys->p_graph->RemoveFilter( p_device_filter.Get() );
1180 p_sys->p_graph->RemoveFilter( p_capture_filter.Get() );
1182 return VLC_EGENERIC;
1185 /* FindCaptureDevices:: This Function had two purposes :
1186 Returns the list of capture devices when p_listdevices != NULL
1187 Creates an IBaseFilter when p_devicename corresponds to an existing devname
1188 These actions *may* be requested whith a single call.
1190 static ComPtr<IBaseFilter>
1191 FindCaptureDevice( vlc_object_t *p_this, std::string *p_devicename,
1192 std::list<std::string> *p_listdevices, bool b_audio )
1194 ComPtr<IBaseFilter> p_base_filter;
1195 ComPtr<IMoniker> p_moniker;
1196 ULONG i_fetched;
1197 HRESULT hr;
1198 std::list<std::string> devicelist;
1200 /* Create the system device enumerator */
1201 ComPtr<ICreateDevEnum> p_dev_enum;
1203 hr = CoCreateInstance( CLSID_SystemDeviceEnum, NULL, CLSCTX_INPROC,
1204 IID_ICreateDevEnum, (void**)p_dev_enum.GetAddressOf() );
1205 if( FAILED(hr) )
1207 msg_Err( p_this, "failed to create the device enumerator (0x%lx)", hr);
1208 return p_base_filter;
1211 /* Create an enumerator for the video capture devices */
1212 ComPtr<IEnumMoniker> p_class_enum;
1213 if( !b_audio )
1214 hr = p_dev_enum->CreateClassEnumerator( CLSID_VideoInputDeviceCategory,
1215 p_class_enum.GetAddressOf(), 0 );
1216 else
1217 hr = p_dev_enum->CreateClassEnumerator( CLSID_AudioInputDeviceCategory,
1218 p_class_enum.GetAddressOf(), 0 );
1219 if( FAILED(hr) )
1221 msg_Err( p_this, "failed to create the class enumerator (0x%lx)", hr );
1222 return p_base_filter;
1225 /* If there are no enumerators for the requested type, then
1226 * CreateClassEnumerator will succeed, but p_class_enum will be NULL */
1227 if( p_class_enum == NULL )
1229 msg_Err( p_this, "no %s capture device was detected", ( b_audio ? "audio" : "video" ) );
1230 return p_base_filter;
1233 /* Enumerate the devices */
1235 /* Note that if the Next() call succeeds but there are no monikers,
1236 * it will return S_FALSE (which is not a failure). Therefore, we check
1237 * that the return code is S_OK instead of using SUCCEEDED() macro. */
1239 while( p_class_enum->Next( 1, p_moniker.ReleaseAndGetAddressOf(), &i_fetched ) == S_OK )
1241 /* Getting the property page to get the device name */
1242 ComPtr<IPropertyBag> p_bag;
1243 hr = p_moniker->BindToStorage( 0, 0, IID_IPropertyBag,
1244 (void**)p_bag.GetAddressOf() );
1245 if( SUCCEEDED(hr) )
1247 VARIANT var;
1248 var.vt = VT_BSTR;
1249 hr = p_bag->Read( L"FriendlyName", &var, NULL );
1250 if( SUCCEEDED(hr) )
1252 char *p_buf = FromWide( var.bstrVal );
1253 std::string devname(p_buf);
1254 free( p_buf) ;
1256 int dup = 0;
1257 /* find out if this name is already used by a previously found device */
1258 std::list<std::string>::const_iterator iter = devicelist.begin();
1259 std::list<std::string>::const_iterator end = devicelist.end();
1260 std::string ordevname = devname ;
1261 while ( iter != end )
1263 if( 0 == (*iter).compare( devname ) )
1264 { /* devname is on the list. Try another name with sequence
1265 number apended and then rescan until a unique entry is found*/
1266 char seq[16];
1267 snprintf(seq, 16, " #%d", ++dup);
1268 devname = ordevname + seq;
1269 iter = devicelist.begin();
1271 else
1272 ++iter;
1274 devicelist.push_back( devname );
1276 if( p_devicename && *p_devicename == devname )
1278 msg_Dbg( p_this, "asked for %s, binding to %s", p_devicename->c_str() , devname.c_str() ) ;
1279 /* NULL possibly means we don't need BindMoniker BindCtx ?? */
1280 hr = p_moniker->BindToObject( NULL, 0, IID_IBaseFilter,
1281 (void**)p_base_filter.GetAddressOf() );
1282 if( FAILED(hr) )
1284 msg_Err( p_this, "couldn't bind moniker to filter "
1285 "object (0x%lx)", hr );
1286 return NULL;
1288 return p_base_filter;
1294 if( p_listdevices ) {
1295 devicelist.sort();
1296 *p_listdevices = devicelist;
1298 return p_base_filter;
1301 static size_t EnumDeviceCaps( vlc_object_t *p_this, IBaseFilter *p_filter,
1302 int i_fourcc, int i_width, int i_height,
1303 int i_channels, int i_samplespersec,
1304 int i_bitspersample, AM_MEDIA_TYPE *mt,
1305 size_t mt_max, bool b_audio )
1307 ComPtr<IEnumPins> p_enumpins;
1308 ComPtr<IPin> p_output_pin;
1309 ComPtr<IEnumMediaTypes> p_enummt;
1310 size_t mt_count = 0;
1312 LONGLONG i_AvgTimePerFrame = 0;
1313 float r_fps = var_GetFloat( p_this, "dshow-fps" );
1314 if( r_fps )
1315 i_AvgTimePerFrame = 10000000000LL/(LONGLONG)(r_fps*1000.0f);
1317 if( FAILED(p_filter->EnumPins( p_enumpins.GetAddressOf() )) )
1319 msg_Dbg( p_this, "EnumDeviceCaps failed: no pin enumeration !");
1320 return 0;
1323 while( S_OK == p_enumpins->Next( 1, p_output_pin.ReleaseAndGetAddressOf(), NULL ) )
1325 PIN_INFO info;
1327 if( S_OK == p_output_pin->QueryPinInfo( &info ) )
1329 msg_Dbg( p_this, "EnumDeviceCaps: %s pin: %S",
1330 info.dir == PINDIR_INPUT ? "input" : "output",
1331 info.achName );
1332 if( info.pFilter ) info.pFilter->Release();
1336 p_enumpins->Reset();
1338 while( !mt_count && p_enumpins->Next( 1, p_output_pin.ReleaseAndGetAddressOf(), NULL ) == S_OK )
1340 PIN_INFO info;
1342 if( S_OK == p_output_pin->QueryPinInfo( &info ) )
1344 if( info.pFilter ) info.pFilter->Release();
1345 if( info.dir == PINDIR_INPUT )
1346 continue;
1347 msg_Dbg( p_this, "EnumDeviceCaps: trying pin %S", info.achName );
1350 AM_MEDIA_TYPE *p_mt;
1353 ** Configure pin with a default compatible media if possible
1356 ComPtr<IAMStreamConfig> pSC;
1357 if( SUCCEEDED(p_output_pin->QueryInterface( IID_IAMStreamConfig,
1358 (void**)pSC.GetAddressOf() )) )
1360 int piCount, piSize;
1361 if( SUCCEEDED(pSC->GetNumberOfCapabilities(&piCount, &piSize)) )
1363 BYTE *pSCC= (BYTE *)CoTaskMemAlloc(piSize);
1364 if( NULL != pSCC )
1366 int i_priority = ES_PRIORITY_NOT_DEFAULTABLE;
1367 for( int i=0; i<piCount; ++i )
1369 if( SUCCEEDED(pSC->GetStreamCaps(i, &p_mt, pSCC)) )
1371 int i_current_fourcc = GetFourCCFromMediaType( *p_mt );
1372 int i_current_priority = GetFourCCPriority(i_current_fourcc);
1374 if( (i_fourcc && (i_current_fourcc != i_fourcc))
1375 || (i_priority > i_current_priority) )
1377 // unwanted chroma, try next media type
1378 FreeMediaType( *p_mt );
1379 CoTaskMemFree( (PVOID)p_mt );
1380 continue;
1383 if( !b_audio && MEDIATYPE_Video == p_mt->majortype
1384 && FORMAT_VideoInfo == p_mt->formattype )
1386 VIDEO_STREAM_CONFIG_CAPS *pVSCC = reinterpret_cast<VIDEO_STREAM_CONFIG_CAPS*>(pSCC);
1387 VIDEOINFOHEADER *pVih = reinterpret_cast<VIDEOINFOHEADER*>(p_mt->pbFormat);
1389 if( i_AvgTimePerFrame )
1391 if( pVSCC->MinFrameInterval > i_AvgTimePerFrame
1392 || i_AvgTimePerFrame > pVSCC->MaxFrameInterval )
1394 // required frame rate not compatible, try next media type
1395 FreeMediaType( *p_mt );
1396 CoTaskMemFree( (PVOID)p_mt );
1397 continue;
1399 pVih->AvgTimePerFrame = i_AvgTimePerFrame;
1402 if( i_width )
1404 if(( !pVSCC->OutputGranularityX
1405 && i_width != pVSCC->MinOutputSize.cx
1406 && i_width != pVSCC->MaxOutputSize.cx)
1408 ( pVSCC->OutputGranularityX
1409 && ((i_width % pVSCC->OutputGranularityX)
1410 || pVSCC->MinOutputSize.cx > i_width
1411 || i_width > pVSCC->MaxOutputSize.cx )))
1413 // required width not compatible, try next media type
1414 FreeMediaType( *p_mt );
1415 CoTaskMemFree( (PVOID)p_mt );
1416 continue;
1418 pVih->bmiHeader.biWidth = i_width;
1421 if( i_height )
1423 if(( !pVSCC->OutputGranularityY
1424 && i_height != pVSCC->MinOutputSize.cy
1425 && i_height != pVSCC->MaxOutputSize.cy)
1427 ( pVSCC->OutputGranularityY
1428 && ((i_height % pVSCC->OutputGranularityY)
1429 || pVSCC->MinOutputSize.cy > i_height
1430 || i_height > pVSCC->MaxOutputSize.cy )))
1432 // required height not compatible, try next media type
1433 FreeMediaType( *p_mt );
1434 CoTaskMemFree( (PVOID)p_mt );
1435 continue;
1437 pVih->bmiHeader.biHeight = i_height;
1440 // Set the sample size and image size.
1441 // (Round the image width up to a DWORD boundary.)
1442 p_mt->lSampleSize = pVih->bmiHeader.biSizeImage =
1443 ((pVih->bmiHeader.biWidth + 3) & ~3) *
1444 pVih->bmiHeader.biHeight * (pVih->bmiHeader.biBitCount>>3);
1446 // no cropping, use full video input buffer
1447 memset(&(pVih->rcSource), 0, sizeof(RECT));
1448 memset(&(pVih->rcTarget), 0, sizeof(RECT));
1450 // select this format as default
1451 if( SUCCEEDED( pSC->SetFormat(p_mt) ) )
1453 i_priority = i_current_priority;
1454 if( i_fourcc )
1455 // no need to check any more media types
1456 i = piCount;
1459 else if( b_audio && p_mt->majortype == MEDIATYPE_Audio
1460 && p_mt->formattype == FORMAT_WaveFormatEx )
1462 AUDIO_STREAM_CONFIG_CAPS *pASCC = reinterpret_cast<AUDIO_STREAM_CONFIG_CAPS*>(pSCC);
1463 WAVEFORMATEX *pWfx = reinterpret_cast<WAVEFORMATEX*>(p_mt->pbFormat);
1465 if( i_current_fourcc && (WAVE_FORMAT_PCM == pWfx->wFormatTag) )
1467 int val = i_channels;
1468 if( ! val )
1469 val = 2;
1471 if( ( !pASCC->ChannelsGranularity
1472 && (unsigned int)val != pASCC->MinimumChannels
1473 && (unsigned int)val != pASCC->MaximumChannels)
1475 ( pASCC->ChannelsGranularity
1476 && ((val % pASCC->ChannelsGranularity)
1477 || (unsigned int)val < pASCC->MinimumChannels
1478 || (unsigned int)val > pASCC->MaximumChannels)))
1480 // required number channels not available, try next media type
1481 FreeMediaType( *p_mt );
1482 CoTaskMemFree( (PVOID)p_mt );
1483 continue;
1485 pWfx->nChannels = val;
1487 val = i_samplespersec;
1488 if( ! val )
1489 val = 44100;
1491 if( ( !pASCC->SampleFrequencyGranularity
1492 && (unsigned int)val != pASCC->MinimumSampleFrequency
1493 && (unsigned int)val != pASCC->MaximumSampleFrequency)
1495 ( pASCC->SampleFrequencyGranularity
1496 && ((val % pASCC->SampleFrequencyGranularity)
1497 || (unsigned int)val < pASCC->MinimumSampleFrequency
1498 || (unsigned int)val > pASCC->MaximumSampleFrequency )))
1500 // required sampling rate not available, try next media type
1501 FreeMediaType( *p_mt );
1502 CoTaskMemFree( (PVOID)p_mt );
1503 continue;
1505 pWfx->nSamplesPerSec = val;
1507 val = i_bitspersample;
1508 if( ! val )
1510 if( VLC_CODEC_FL32 == i_current_fourcc )
1511 val = 32;
1512 else
1513 val = 16;
1516 if( ( !pASCC->BitsPerSampleGranularity
1517 && (unsigned int)val != pASCC->MinimumBitsPerSample
1518 && (unsigned int)val != pASCC->MaximumBitsPerSample )
1520 ( pASCC->BitsPerSampleGranularity
1521 && ((val % pASCC->BitsPerSampleGranularity)
1522 || (unsigned int)val < pASCC->MinimumBitsPerSample
1523 || (unsigned int)val > pASCC->MaximumBitsPerSample )))
1525 // required sample size not available, try next media type
1526 FreeMediaType( *p_mt );
1527 CoTaskMemFree( (PVOID)p_mt );
1528 continue;
1531 pWfx->wBitsPerSample = val;
1532 pWfx->nBlockAlign = (pWfx->wBitsPerSample * pWfx->nChannels)/8;
1533 pWfx->nAvgBytesPerSec = pWfx->nSamplesPerSec * pWfx->nBlockAlign;
1535 // select this format as default
1536 if( SUCCEEDED( pSC->SetFormat(p_mt) ) )
1538 i_priority = i_current_priority;
1542 FreeMediaType( *p_mt );
1543 CoTaskMemFree( (PVOID)p_mt );
1546 CoTaskMemFree( (LPVOID)pSCC );
1547 if( i_priority >= ES_PRIORITY_SELECTABLE_MIN )
1548 msg_Dbg( p_this, "EnumDeviceCaps: input pin default format configured");
1554 ** Probe pin for available medias (may be a previously configured one)
1557 if( FAILED( p_output_pin->EnumMediaTypes( p_enummt.ReleaseAndGetAddressOf() ) ) )
1559 continue;
1562 while( p_enummt->Next( 1, &p_mt, NULL ) == S_OK )
1564 int i_current_fourcc = GetFourCCFromMediaType( *p_mt );
1565 if( !b_audio && i_current_fourcc && p_mt->majortype == MEDIATYPE_Video
1566 && p_mt->formattype == FORMAT_VideoInfo )
1568 int i_current_width = ((VIDEOINFOHEADER *)p_mt->pbFormat)->bmiHeader.biWidth;
1569 int i_current_height = ((VIDEOINFOHEADER *)p_mt->pbFormat)->bmiHeader.biHeight;
1570 LONGLONG i_current_atpf = ((VIDEOINFOHEADER *)p_mt->pbFormat)->AvgTimePerFrame;
1572 if( i_current_height < 0 )
1573 i_current_height = -i_current_height;
1575 msg_Dbg( p_this, "EnumDeviceCaps: input pin "
1576 "accepts chroma: %4.4s, width:%i, height:%i, fps:%f",
1577 (char *)&i_current_fourcc, i_current_width,
1578 i_current_height, (10000000.0f/((float)i_current_atpf)) );
1580 if( ( !i_fourcc || i_fourcc == i_current_fourcc ) &&
1581 ( !i_width || i_width == i_current_width ) &&
1582 ( !i_height || i_height == i_current_height ) &&
1583 ( !i_AvgTimePerFrame || i_AvgTimePerFrame == i_current_atpf ) &&
1584 mt_count < mt_max )
1586 /* Pick match */
1587 mt[mt_count++] = *p_mt;
1589 else FreeMediaType( *p_mt );
1591 else if( b_audio && i_current_fourcc && p_mt->majortype == MEDIATYPE_Audio
1592 && p_mt->formattype == FORMAT_WaveFormatEx)
1594 int i_current_channels =
1595 ((WAVEFORMATEX *)p_mt->pbFormat)->nChannels;
1596 int i_current_samplespersec =
1597 ((WAVEFORMATEX *)p_mt->pbFormat)->nSamplesPerSec;
1598 int i_current_bitspersample =
1599 ((WAVEFORMATEX *)p_mt->pbFormat)->wBitsPerSample;
1601 msg_Dbg( p_this, "EnumDeviceCaps: input pin "
1602 "accepts format: %4.4s, channels:%i, "
1603 "samples/sec:%i bits/sample:%i",
1604 (char *)&i_current_fourcc, i_current_channels,
1605 i_current_samplespersec, i_current_bitspersample);
1607 if( (!i_channels || i_channels == i_current_channels) &&
1608 (!i_samplespersec ||
1609 i_samplespersec == i_current_samplespersec) &&
1610 (!i_bitspersample ||
1611 i_bitspersample == i_current_bitspersample) &&
1612 mt_count < mt_max )
1614 /* Pick match */
1615 mt[mt_count++] = *p_mt;
1617 /* Setup a few properties like the audio latency */
1618 ComPtr<IAMBufferNegotiation> p_ambuf;
1619 if( SUCCEEDED( p_output_pin->QueryInterface(
1620 IID_IAMBufferNegotiation, (void **)p_ambuf.GetAddressOf() ) ) )
1622 ALLOCATOR_PROPERTIES AllocProp;
1623 AllocProp.cbAlign = -1;
1625 /* 100 ms of latency */
1626 AllocProp.cbBuffer = i_current_channels *
1627 i_current_samplespersec *
1628 i_current_bitspersample / 8 / 10;
1630 AllocProp.cbPrefix = -1;
1631 AllocProp.cBuffers = -1;
1632 p_ambuf->SuggestAllocatorProperties( &AllocProp );
1635 else FreeMediaType( *p_mt );
1637 else if( i_current_fourcc && p_mt->majortype == MEDIATYPE_Stream )
1639 msg_Dbg( p_this, "EnumDeviceCaps: input pin "
1640 "accepts stream format: %4.4s",
1641 (char *)&i_current_fourcc );
1643 if( ( !i_fourcc || i_fourcc == i_current_fourcc ) &&
1644 mt_count < mt_max )
1646 /* Pick match */
1647 mt[mt_count++] = *p_mt;
1648 i_fourcc = i_current_fourcc;
1650 else FreeMediaType( *p_mt );
1652 else
1654 const char * psz_type = "unknown";
1655 if( p_mt->majortype == MEDIATYPE_Video ) psz_type = "video";
1656 if( p_mt->majortype == MEDIATYPE_Audio ) psz_type = "audio";
1657 if( p_mt->majortype == MEDIATYPE_Stream ) psz_type = "stream";
1658 msg_Dbg( p_this, "EnumDeviceCaps: input pin media: unsupported format "
1659 "(%s %4.4s)", psz_type, (char *)&p_mt->subtype );
1661 FreeMediaType( *p_mt );
1663 CoTaskMemFree( (PVOID)p_mt );
1666 if( !mt_count && p_enummt->Reset() == S_OK )
1668 // VLC did not find any supported MEDIATYPE for this output pin.
1669 // However the graph builder might insert converter filters in
1670 // the graph if we use a different codec in VLC filter input pin.
1671 // however, in order to avoid nasty surprises, make use of this
1672 // facility only for known unsupported codecs.
1674 while( !mt_count && p_enummt->Next( 1, &p_mt, NULL ) == S_OK )
1676 // the first four bytes of subtype GUID contains the codec FOURCC
1677 const char *pfcc = (char *)&p_mt->subtype;
1678 int i_current_fourcc = VLC_FOURCC(pfcc[0], pfcc[1], pfcc[2], pfcc[3]);
1679 if( VLC_FOURCC('H','C','W','2') == i_current_fourcc
1680 && p_mt->majortype == MEDIATYPE_Video && !b_audio )
1682 // output format for 'Hauppauge WinTV PVR PCI II Capture'
1683 // try I420 as an input format
1684 i_current_fourcc = VLC_CODEC_I420;
1685 if( !i_fourcc || i_fourcc == i_current_fourcc )
1687 // return alternative media type
1688 AM_MEDIA_TYPE mtr;
1689 VIDEOINFOHEADER vh;
1691 mtr.majortype = MEDIATYPE_Video;
1692 mtr.subtype = MEDIASUBTYPE_I420;
1693 mtr.bFixedSizeSamples = TRUE;
1694 mtr.bTemporalCompression = FALSE;
1695 mtr.pUnk = NULL;
1696 mtr.formattype = FORMAT_VideoInfo;
1697 mtr.cbFormat = sizeof(vh);
1698 mtr.pbFormat = (BYTE *)&vh;
1700 memset(&vh, 0, sizeof(vh));
1702 vh.bmiHeader.biSize = sizeof(vh.bmiHeader);
1703 vh.bmiHeader.biWidth = i_width > 0 ? i_width :
1704 ((VIDEOINFOHEADER *)p_mt->pbFormat)->bmiHeader.biWidth;
1705 vh.bmiHeader.biHeight = i_height > 0 ? i_height :
1706 ((VIDEOINFOHEADER *)p_mt->pbFormat)->bmiHeader.biHeight;
1707 vh.bmiHeader.biPlanes = 3;
1708 vh.bmiHeader.biBitCount = 12;
1709 vh.bmiHeader.biCompression = VLC_CODEC_I420;
1710 vh.bmiHeader.biSizeImage = vh.bmiHeader.biWidth * 12 *
1711 vh.bmiHeader.biHeight / 8;
1712 mtr.lSampleSize = vh.bmiHeader.biSizeImage;
1714 msg_Dbg( p_this, "EnumDeviceCaps: input pin media: using 'I420' in place of unsupported format 'HCW2'");
1716 if( SUCCEEDED(CopyMediaType(mt+mt_count, &mtr)) )
1717 ++mt_count;
1720 FreeMediaType( *p_mt );
1725 return mt_count;
1728 /*****************************************************************************
1729 * ReadCompressed: reads compressed (MPEG/DV) data from the device.
1730 *****************************************************************************/
1731 static block_t *ReadCompressed( stream_t *p_access, bool *eof )
1733 ComContext ctx( COINIT_MULTITHREADED );
1735 access_sys_t *p_sys = (access_sys_t *)p_access->p_sys;
1736 /* There must be only 1 elementary stream to produce a valid stream
1737 * of MPEG or DV data */
1738 dshow_stream_t *p_stream = p_sys->pp_streams[0];
1739 VLCMediaSample sample;
1741 /* Read 1 DV/MPEG frame (they contain the video and audio data) */
1743 /* Get new sample/frame from the elementary stream (blocking). */
1744 vlc_mutex_lock( &p_sys->lock );
1746 if( p_stream->p_capture_filter->CustomGetPin()->CustomGetSample(&sample) != S_OK )
1747 { /* No data available. Wait until some data has arrived */
1748 vlc_cond_wait( &p_sys->wait, &p_sys->lock );
1749 vlc_mutex_unlock( &p_sys->lock );
1750 return NULL;
1752 vlc_mutex_unlock( &p_sys->lock );
1755 * We got our sample
1757 block_t *p_block = NULL;
1758 uint8_t *p_data;
1759 int i_data_size = sample.p_sample->GetActualDataLength();
1760 if( i_data_size == 0 )
1761 goto out;
1763 p_block = block_Alloc( i_data_size );
1764 if( unlikely(p_block == NULL) )
1765 goto out;
1767 sample.p_sample->GetPointer( &p_data );
1768 memcpy( p_block->p_buffer, p_data, i_data_size );
1769 /* The caller got what he wanted */
1770 out:
1771 (void) eof;
1772 return p_block;
1775 /****************************************************************************
1776 * Demux:
1777 ****************************************************************************/
1778 static int Demux( demux_t *p_demux )
1780 ComContext ctx( COINIT_MULTITHREADED );
1782 access_sys_t *p_sys = (access_sys_t *)p_demux->p_sys;
1783 int i_found_samples;
1785 i_found_samples = 0;
1786 vlc_mutex_lock( &p_sys->lock );
1788 while ( !i_found_samples )
1790 /* Try to grab samples from all streams */
1791 std::vector<dshow_stream_t*>::iterator it = p_sys->pp_streams.begin();
1792 std::vector<dshow_stream_t*>::iterator end = p_sys->pp_streams.end();
1793 for ( ; it != end; ++it )
1795 dshow_stream_t *p_stream = *it;
1796 if( p_stream->p_capture_filter &&
1797 p_stream->p_capture_filter->CustomGetPin()
1798 ->CustomGetSamples( p_stream->samples_queue ) == S_OK )
1800 i_found_samples = 1;
1804 if ( !i_found_samples)
1806 /* Didn't find any audio nor video sample, just wait till the
1807 * dshow thread pushes some samples */
1808 vlc_cond_wait( &p_sys->wait, &p_sys->lock );
1809 /* Some DShow thread pushed data, or the OS broke the wait all
1810 * by itself. In all cases, it's *strongly* advised to test the
1811 * condition again, so let the loop do the test again */
1815 vlc_mutex_unlock( &p_sys->lock );
1817 std::vector<dshow_stream_t*>::iterator it = p_sys->pp_streams.begin();
1818 std::vector<dshow_stream_t*>::iterator end = p_sys->pp_streams.end();
1819 for ( ; it != end; ++it )
1821 int i_samples;
1822 dshow_stream_t *p_stream = *it;
1824 i_samples = p_stream->samples_queue.size();
1825 while ( i_samples > 0 )
1827 int i_data_size;
1828 uint8_t *p_data;
1829 block_t *p_block;
1830 VLCMediaSample sample;
1832 sample = p_stream->samples_queue.front();
1833 p_stream->samples_queue.pop_front();
1835 i_data_size = sample.p_sample->GetActualDataLength();
1836 sample.p_sample->GetPointer( &p_data );
1838 REFERENCE_TIME i_pts, i_end_date;
1839 HRESULT hr = sample.p_sample->GetTime( &i_pts, &i_end_date );
1840 if( hr != S_OK && hr != VFW_S_NO_STOP_TIME )
1842 if( p_stream->mt.majortype == MEDIATYPE_Video || !p_stream->b_pts )
1844 /* Use our data timestamp */
1845 i_pts = MSFTIME_FROM_VLC_TICK(sample.i_timestamp);
1846 p_stream->b_pts = true;
1848 else
1849 i_pts = LONG_MIN;
1852 if( i_pts != LONG_MIN ) {
1853 i_pts += 5;
1855 #if 0
1856 msg_Dbg( p_demux, "Read() stream: %i, size: %i, PTS: %" PRId64,
1857 i_stream, i_data_size, VLC_TICK_FROM_MSFTIME(i_pts) );
1858 #endif
1860 p_block = block_Alloc( i_data_size );
1861 memcpy( p_block->p_buffer, p_data, i_data_size );
1862 p_block->i_pts = p_block->i_dts = i_pts == LONG_MIN ?
1863 VLC_TICK_INVALID : (VLC_TICK_FROM_MSFTIME(i_pts) + VLC_TICK_0);
1865 if( p_block->i_pts != VLC_TICK_INVALID )
1866 es_out_SetPCR( p_demux->out, p_block->i_pts );
1867 es_out_Send( p_demux->out, p_stream->p_es, p_block );
1869 i_samples--;
1873 return 1;
1876 /*****************************************************************************
1877 * AccessControl:
1878 *****************************************************************************/
1879 static int AccessControl( stream_t *p_access, int i_query, va_list args )
1881 access_sys_t *sys = (access_sys_t *)p_access->p_sys;
1882 bool *pb_bool;
1884 switch( i_query )
1886 case STREAM_CAN_SEEK:
1887 case STREAM_CAN_FASTSEEK:
1888 case STREAM_CAN_PAUSE:
1889 case STREAM_CAN_CONTROL_PACE:
1890 pb_bool = va_arg( args, bool * );
1891 *pb_bool = false;
1892 break;
1894 case STREAM_GET_PTS_DELAY:
1895 *va_arg( args, vlc_tick_t * ) =
1896 VLC_TICK_FROM_MS( var_InheritInteger( p_access, "live-caching" ) );
1897 break;
1899 case STREAM_GET_CONTENT_TYPE:
1901 dshow_stream_t *p_stream = sys->pp_streams[0];
1902 char **type = va_arg( args, char ** );
1904 /* Check if we need to force demuxers */
1905 if( p_stream->i_fourcc == VLC_CODEC_DV )
1906 *type = strdup( "video/dv" );
1907 else if( p_stream->i_fourcc == VLC_CODEC_MPGV )
1908 *type = strdup( "video/MP2P" );
1909 else
1910 return VLC_EGENERIC;
1911 break;
1914 default:
1915 return VLC_EGENERIC;
1918 return VLC_SUCCESS;
1921 /****************************************************************************
1922 * DemuxControl:
1923 ****************************************************************************/
1924 static int DemuxControl( demux_t *p_demux, int i_query, va_list args )
1926 bool *pb;
1927 int64_t *pi64;
1929 access_sys_t *p_sys = ( access_sys_t * ) p_demux->p_sys;
1931 switch( i_query )
1933 /* Special for access_demux */
1934 case DEMUX_CAN_PAUSE:
1935 case DEMUX_CAN_SEEK:
1936 case DEMUX_SET_PAUSE_STATE:
1937 case DEMUX_CAN_CONTROL_PACE:
1938 pb = va_arg( args, bool * );
1939 *pb = false;
1940 return VLC_SUCCESS;
1942 case DEMUX_GET_PTS_DELAY:
1943 *va_arg( args, vlc_tick_t * ) =
1944 VLC_TICK_FROM_MS( var_InheritInteger( p_demux, "live-caching" ) );
1945 return VLC_SUCCESS;
1947 case DEMUX_GET_TIME:
1948 pi64 = va_arg( args, int64_t * );
1949 *pi64 = vlc_tick_now() - p_sys->i_start;
1950 return VLC_SUCCESS;
1952 /* TODO implement others */
1953 default:
1954 return VLC_EGENERIC;
1957 return VLC_EGENERIC;
1960 static int AppendAudioEnabledVDevs( vlc_object_t *p_this, std::list<std::string> &audio_list,
1961 std::list<std::string> &video_list )
1963 ComPtr<IFilterGraph> p_graph;
1964 ComPtr<IGraphBuilder> p_gbuilder;
1965 ComPtr<ICaptureGraphBuilder2> p_cgbuilder;
1967 if( FAILED( CoCreateInstance( CLSID_FilterGraph, NULL, CLSCTX_INPROC_SERVER, IID_IFilterGraph,
1968 ( void ** ) p_graph.GetAddressOf() ) ) )
1969 return VLC_EGENERIC;
1971 if( FAILED( p_graph->QueryInterface( IID_IGraphBuilder, ( void ** ) p_gbuilder.GetAddressOf() ) ) )
1972 return VLC_EGENERIC;
1974 if( FAILED( CoCreateInstance( CLSID_CaptureGraphBuilder2, NULL, CLSCTX_INPROC_SERVER,
1975 IID_ICaptureGraphBuilder2, ( void ** ) p_cgbuilder.GetAddressOf() ) ) )
1976 return VLC_EGENERIC;
1978 if( FAILED( p_cgbuilder->SetFiltergraph( p_gbuilder.Get() ) ) )
1979 return VLC_EGENERIC;
1981 for( std::list<std::string>::iterator iter = video_list.begin();
1982 iter != video_list.end();
1983 ++iter )
1985 ComPtr<IBaseFilter> p_device;
1986 ComPtr<IPin> p_pin;
1988 p_device = FindCaptureDevice( p_this, &( *iter ), NULL, false );
1989 if( !p_device ) continue;
1991 if( FAILED( p_gbuilder->AddFilter( p_device.Get(), NULL ) ) )
1992 continue;
1994 if( SUCCEEDED( p_cgbuilder->FindPin( p_device.Get(), PINDIR_OUTPUT, NULL, &MEDIATYPE_Audio,
1995 true, 0, p_pin.GetAddressOf() ) ) )
1996 audio_list.push_back( *iter );
1998 p_gbuilder->RemoveFilter( p_device.Get() );
2001 return VLC_SUCCESS;
2004 /*****************************************************************************
2005 * config variable callback
2006 *****************************************************************************/
2007 static int FindDevices( const char *psz_name, char ***vp, char ***tp )
2009 /* Find list of devices */
2010 std::list<std::string> list_devices;
2013 bool b_audio = !strcmp( psz_name, "dshow-adev" );
2015 // Use STA as this most likely comes from a Qt thread, which is
2016 // initialized as STA.
2017 ComContext ctx( COINIT_APARTMENTTHREADED );
2019 FindCaptureDevice( NULL, NULL, &list_devices, b_audio );
2021 if( b_audio )
2023 std::list<std::string> list_vdevs;
2024 FindCaptureDevice( NULL, NULL, &list_vdevs, false );
2025 if( !list_vdevs.empty() )
2026 AppendAudioEnabledVDevs( NULL, list_devices, list_vdevs );
2029 catch (const std::runtime_error& ex)
2031 msg_Err( (vlc_object_t *)NULL, "Failed fetch devices: %s", ex.what() );
2034 unsigned count = 2 + list_devices.size(), i = 2;
2035 char **values = (char **)xmalloc( count * sizeof(*values) );
2036 char **texts = (char **)xmalloc( count * sizeof(*texts) );
2038 values[0] = strdup( "" );
2039 texts[0] = strdup( _("Default") );
2040 values[1] = strdup( "none" );
2041 texts[1] = strdup( _("None") );
2043 for( std::list<std::string>::iterator iter = list_devices.begin();
2044 iter != list_devices.end();
2045 ++iter )
2047 assert( i < count );
2048 values[i] = strdup( iter->c_str() );
2049 texts[i] = strdup( iter->c_str() );
2050 i++;
2053 *vp = values;
2054 *tp = texts;
2055 return count;
2058 /*****************************************************************************
2059 * Properties
2060 *****************************************************************************/
2062 static void ShowPropertyPage( IUnknown *obj )
2064 ComPtr<ISpecifyPropertyPages> p_spec;
2065 CAUUID cauuid;
2067 HRESULT hr = obj->QueryInterface( IID_ISpecifyPropertyPages,
2068 (void **)p_spec.GetAddressOf() );
2069 if( FAILED(hr) ) return;
2071 if( SUCCEEDED(p_spec->GetPages( &cauuid )) )
2073 if( cauuid.cElems > 0 )
2075 HWND hwnd_desktop = ::GetDesktopWindow();
2077 OleCreatePropertyFrame( hwnd_desktop, 30, 30, NULL, 1, &obj,
2078 cauuid.cElems, cauuid.pElems, 0, 0, NULL );
2080 CoTaskMemFree( cauuid.pElems );
2085 static void ShowDeviceProperties( vlc_object_t *p_this,
2086 ICaptureGraphBuilder2 *p_graph,
2087 IBaseFilter *p_device_filter,
2088 bool b_audio )
2090 HRESULT hr;
2091 msg_Dbg( p_this, "configuring Device Properties" );
2094 * Video or audio capture filter page
2096 ShowPropertyPage( p_device_filter );
2099 * Audio capture pin
2101 if( p_graph && b_audio )
2103 ComPtr<IAMStreamConfig> p_SC;
2105 msg_Dbg( p_this, "showing WDM Audio Configuration Pages" );
2107 hr = p_graph->FindInterface( &PIN_CATEGORY_CAPTURE,
2108 &MEDIATYPE_Audio, p_device_filter,
2109 IID_IAMStreamConfig, (void **)p_SC.GetAddressOf() );
2110 if( SUCCEEDED(hr) )
2112 ShowPropertyPage(p_SC.Get());
2116 * TV Audio filter
2118 ComPtr<IAMTVAudio> p_TVA;
2119 HRESULT hr = p_graph->FindInterface( &PIN_CATEGORY_CAPTURE,
2120 &MEDIATYPE_Audio, p_device_filter,
2121 IID_IAMTVAudio, (void **)p_TVA.GetAddressOf() );
2122 if( SUCCEEDED(hr) )
2124 ShowPropertyPage(p_TVA.Get());
2129 * Video capture pin
2131 if( p_graph && !b_audio )
2133 ComPtr<IAMStreamConfig> p_SC;
2135 msg_Dbg( p_this, "showing WDM Video Configuration Pages" );
2137 hr = p_graph->FindInterface( &PIN_CATEGORY_CAPTURE,
2138 &MEDIATYPE_Interleaved, p_device_filter,
2139 IID_IAMStreamConfig, (void **)p_SC.GetAddressOf() );
2140 if( FAILED(hr) )
2142 hr = p_graph->FindInterface( &PIN_CATEGORY_CAPTURE,
2143 &MEDIATYPE_Video, p_device_filter,
2144 IID_IAMStreamConfig, (void **)p_SC.GetAddressOf() );
2147 if( FAILED(hr) )
2149 hr = p_graph->FindInterface( &PIN_CATEGORY_CAPTURE,
2150 &MEDIATYPE_Stream, p_device_filter,
2151 IID_IAMStreamConfig, (void **)p_SC.GetAddressOf() );
2154 if( SUCCEEDED(hr) )
2156 ShowPropertyPage(p_SC.Get());
2161 static void ShowTunerProperties( vlc_object_t *p_this,
2162 ICaptureGraphBuilder2 *p_graph,
2163 IBaseFilter *p_device_filter,
2164 bool b_audio )
2166 HRESULT hr;
2167 msg_Dbg( p_this, "configuring Tuner Properties" );
2169 if( !p_graph || b_audio ) return;
2171 ComPtr<IAMTVTuner> p_TV;
2172 hr = p_graph->FindInterface( &PIN_CATEGORY_CAPTURE,
2173 &MEDIATYPE_Interleaved, p_device_filter,
2174 IID_IAMTVTuner, (void **)p_TV.GetAddressOf() );
2175 if( FAILED(hr) )
2177 hr = p_graph->FindInterface( &PIN_CATEGORY_CAPTURE,
2178 &MEDIATYPE_Video, p_device_filter,
2179 IID_IAMTVTuner, (void **)p_TV.GetAddressOf() );
2182 if( FAILED(hr) )
2184 hr = p_graph->FindInterface( &PIN_CATEGORY_CAPTURE,
2185 &MEDIATYPE_Stream, p_device_filter,
2186 IID_IAMTVTuner, (void **)p_TV.GetAddressOf() );
2189 if( SUCCEEDED(hr) )
2191 ShowPropertyPage(p_TV.Get());
2195 static void ConfigTuner( vlc_object_t *p_this, ICaptureGraphBuilder2 *p_graph,
2196 IBaseFilter *p_device_filter )
2198 int i_channel, i_country, i_input, i_amtuner_mode;
2199 long l_modes = 0;
2200 unsigned i_frequency;
2201 ComPtr<IAMTVTuner> p_TV;
2202 HRESULT hr;
2204 if( !p_graph ) return;
2206 i_channel = var_GetInteger( p_this, "dshow-tuner-channel" );
2207 i_country = var_GetInteger( p_this, "dshow-tuner-country" );
2208 i_input = var_GetInteger( p_this, "dshow-tuner-input" );
2209 i_amtuner_mode = var_GetInteger( p_this, "dshow-amtuner-mode" );
2211 if( !i_channel && !i_country && !i_input ) return; /* Nothing to do */
2213 msg_Dbg( p_this, "tuner config: channel %i, country %i, input type %i",
2214 i_channel, i_country, i_input );
2216 hr = p_graph->FindInterface( &PIN_CATEGORY_CAPTURE, &MEDIATYPE_Interleaved,
2217 p_device_filter, IID_IAMTVTuner,
2218 (void **)p_TV.GetAddressOf() );
2219 if( FAILED(hr) )
2221 hr = p_graph->FindInterface( &PIN_CATEGORY_CAPTURE, &MEDIATYPE_Video,
2222 p_device_filter, IID_IAMTVTuner,
2223 (void **)p_TV.GetAddressOf() );
2226 if( FAILED(hr) )
2228 hr = p_graph->FindInterface( &PIN_CATEGORY_CAPTURE, &MEDIATYPE_Stream,
2229 p_device_filter, IID_IAMTVTuner,
2230 (void **)p_TV.GetAddressOf() );
2233 if( FAILED(hr) )
2235 msg_Dbg( p_this, "couldn't find tuner interface" );
2236 return;
2239 hr = p_TV->GetAvailableModes( &l_modes );
2240 if( SUCCEEDED(hr) && (l_modes & i_amtuner_mode) )
2242 p_TV->put_Mode( (AMTunerModeType)i_amtuner_mode );
2245 if( i_input == 1 ) p_TV->put_InputType( 0, TunerInputCable );
2246 else if( i_input == 2 ) p_TV->put_InputType( 0, TunerInputAntenna );
2248 p_TV->put_CountryCode( i_country );
2249 p_TV->put_Channel( i_channel, AMTUNER_SUBCHAN_NO_TUNE,
2250 AMTUNER_SUBCHAN_NO_TUNE );
2251 p_TV->Release();
2254 } // namespace