1 /*****************************************************************************
2 * dshow.cpp : DirectShow access module for vlc
3 *****************************************************************************
4 * Copyright (C) 2002, 2003 the VideoLAN team
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 /*****************************************************************************
27 *****************************************************************************/
33 #define __STDC_FORMAT_MACROS 1
36 #include <vlc_common.h>
37 #include <vlc_plugin.h>
38 #include <vlc_input.h>
39 #include <vlc_access.h>
40 #include <vlc_demux.h>
42 #include <vlc_interface.h>
47 /*****************************************************************************
48 * Access: local prototypes
49 *****************************************************************************/
50 static block_t *ReadCompressed( access_t * );
51 static int AccessControl ( access_t *, int, va_list );
53 static int Demux ( demux_t * );
54 static int DemuxControl( demux_t *, int, va_list );
56 static int OpenDevice( vlc_object_t *, access_sys_t *, string, bool );
57 static IBaseFilter *FindCaptureDevice( vlc_object_t *, string *,
58 list<string> *, bool );
59 static size_t EnumDeviceCaps( vlc_object_t *, IBaseFilter *,
60 int, int, int, int, int, int,
61 AM_MEDIA_TYPE *mt, size_t );
62 static bool ConnectFilters( vlc_object_t *, access_sys_t *,
63 IBaseFilter *, CaptureFilter * );
64 static int FindDevicesCallback( vlc_object_t *, char const *,
65 vlc_value_t, vlc_value_t, void * );
66 static int ConfigDevicesCallback( vlc_object_t *, char const *,
67 vlc_value_t, vlc_value_t, void * );
69 static void ShowPropertyPage( IUnknown * );
70 static void ShowDeviceProperties( vlc_object_t *, ICaptureGraphBuilder2 *,
71 IBaseFilter *, bool );
72 static void ShowTunerProperties( vlc_object_t *, ICaptureGraphBuilder2 *,
73 IBaseFilter *, bool );
74 static void ConfigTuner( vlc_object_t *, ICaptureGraphBuilder2 *,
77 /*****************************************************************************
79 *****************************************************************************/
80 static const char *const ppsz_vdev[] = { "", "none" };
81 static const char *const ppsz_vdev_text[] = { N_("Default"), N_("None") };
82 static const char *const ppsz_adev[] = { "", "none" };
83 static const char *const ppsz_adev_text[] = { N_("Default"), N_("None") };
84 static const int pi_tuner_input[] = { 0, 1, 2 };
85 static const char *const ppsz_tuner_input_text[] =
86 {N_("Default"), N_("Cable"), N_("Antenna")};
87 static const int pi_amtuner_mode[] = { AMTUNER_MODE_DEFAULT,
89 AMTUNER_MODE_FM_RADIO,
90 AMTUNER_MODE_AM_RADIO,
92 static const char *const ppsz_amtuner_mode_text[] = { N_("Default"),
98 #define CACHING_TEXT N_("Caching value in ms")
99 #define CACHING_LONGTEXT N_( \
100 "Caching value for DirectShow streams. " \
101 "This value should be set in millisecondss." )
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 " \
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 " \
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 CHROMA_TEXT N_("Video input chroma format")
118 #define CHROMA_LONGTEXT N_( \
119 "Force the DirectShow video input to use a specific chroma format " \
120 "(eg. I420 (default), RV24, etc.)")
121 #define FPS_TEXT N_("Video input frame rate")
122 #define FPS_LONGTEXT N_( \
123 "Force the DirectShow video input to use a specific frame rate" \
124 "(eg. 0 means default, 25, 29.97, 50, 59.94, etc.)")
125 #define CONFIG_TEXT N_("Device properties")
126 #define CONFIG_LONGTEXT N_( \
127 "Show the properties dialog of the selected device before starting the " \
129 #define TUNER_TEXT N_("Tuner properties")
130 #define TUNER_LONGTEXT N_( \
131 "Show the tuner properties [channel selection] page." )
132 #define CHANNEL_TEXT N_("Tuner TV Channel")
133 #define CHANNEL_LONGTEXT N_( \
134 "Set the TV channel the tuner will set to " \
135 "(0 means default)." )
136 #define COUNTRY_TEXT N_("Tuner country code")
137 #define COUNTRY_LONGTEXT N_( \
138 "Set the tuner country code that establishes the current " \
139 "channel-to-frequency mapping (0 means default)." )
140 #define TUNER_INPUT_TEXT N_("Tuner input type")
141 #define TUNER_INPUT_LONGTEXT N_( \
142 "Select the tuner input type (Cable/Antenna)." )
143 #define VIDEO_IN_TEXT N_("Video input pin")
144 #define VIDEO_IN_LONGTEXT N_( \
145 "Select the video input source, such as composite, s-video, " \
146 "or tuner. Since these settings are hardware-specific, you should find good " \
147 "settings in the \"Device config\" area, and use those numbers here. -1 " \
148 "means that settings will not be changed.")
149 #define AUDIO_IN_TEXT N_("Audio input pin")
150 #define AUDIO_IN_LONGTEXT N_( \
151 "Select the audio input source. See the \"video input\" option." )
152 #define VIDEO_OUT_TEXT N_("Video output pin")
153 #define VIDEO_OUT_LONGTEXT N_( \
154 "Select the video output type. See the \"video input\" option." )
155 #define AUDIO_OUT_TEXT N_("Audio output pin")
156 #define AUDIO_OUT_LONGTEXT N_( \
157 "Select the audio output type. See the \"video input\" option." )
159 #define AMTUNER_MODE_TEXT N_("AM Tuner mode")
160 #define AMTUNER_MODE_LONGTEXT N_( \
161 "AM Tuner mode. Can be one of Default (0), TV (1)," \
162 "AM Radio (2), FM Radio (3) or DSS (4).")
164 #define AUDIO_CHANNELS_TEXT N_("Number of audio channels")
165 #define AUDIO_CHANNELS_LONGTEXT N_( \
166 "Select audio input format with the given number of audio channels (if non 0)" )
168 #define AUDIO_SAMPLERATE_TEXT N_("Audio sample rate")
169 #define AUDIO_SAMPLERATE_LONGTEXT N_( \
170 "Select audio input format with the given sample rate (if non 0)" )
172 #define AUDIO_BITSPERSAMPLE_TEXT N_("Audio bits per sample")
173 #define AUDIO_BITSPERSAMPLE_LONGTEXT N_( \
174 "Select audio input format with the given bits/sample (if non 0)" )
176 static int CommonOpen ( vlc_object_t *, access_sys_t *, bool );
177 static void CommonClose( vlc_object_t *, access_sys_t * );
179 static int AccessOpen ( vlc_object_t * );
180 static void AccessClose( vlc_object_t * );
182 static int DemuxOpen ( vlc_object_t * );
183 static void DemuxClose ( vlc_object_t * );
186 set_shortname( N_("DirectShow") );
187 set_description( N_("DirectShow input") );
188 set_category( CAT_INPUT );
189 set_subcategory( SUBCAT_INPUT_ACCESS );
190 add_integer( "dshow-caching", (mtime_t)(0.2*CLOCK_FREQ) / 1000, NULL,
191 CACHING_TEXT, CACHING_LONGTEXT, true );
193 add_string( "dshow-vdev", NULL, NULL, VDEV_TEXT, VDEV_LONGTEXT, false);
194 change_string_list( ppsz_vdev, ppsz_vdev_text, FindDevicesCallback );
195 change_action_add( FindDevicesCallback, N_("Refresh list") );
196 change_action_add( ConfigDevicesCallback, N_("Configure") );
198 add_string( "dshow-adev", NULL, NULL, ADEV_TEXT, ADEV_LONGTEXT, false);
199 change_string_list( ppsz_adev, ppsz_adev_text, FindDevicesCallback );
200 change_action_add( FindDevicesCallback, N_("Refresh list") );
201 change_action_add( ConfigDevicesCallback, N_("Configure") );
203 add_string( "dshow-size", NULL, NULL, SIZE_TEXT, SIZE_LONGTEXT, false);
205 add_string( "dshow-chroma", NULL, NULL, CHROMA_TEXT, CHROMA_LONGTEXT,
208 add_float( "dshow-fps", 0.0f, NULL, FPS_TEXT, FPS_LONGTEXT,
211 add_bool( "dshow-config", false, NULL, CONFIG_TEXT, CONFIG_LONGTEXT,
214 add_bool( "dshow-tuner", false, NULL, TUNER_TEXT, TUNER_LONGTEXT,
217 add_integer( "dshow-tuner-channel", 0, NULL, CHANNEL_TEXT,
218 CHANNEL_LONGTEXT, true );
220 add_integer( "dshow-tuner-country", 0, NULL, COUNTRY_TEXT,
221 COUNTRY_LONGTEXT, true );
223 add_integer( "dshow-tuner-input", 0, NULL, TUNER_INPUT_TEXT,
224 TUNER_INPUT_LONGTEXT, true );
225 change_integer_list( pi_tuner_input, ppsz_tuner_input_text, NULL );
227 add_integer( "dshow-video-input", -1, NULL, VIDEO_IN_TEXT,
228 VIDEO_IN_LONGTEXT, true );
230 add_integer( "dshow-audio-input", -1, NULL, AUDIO_IN_TEXT,
231 AUDIO_IN_LONGTEXT, true );
233 add_integer( "dshow-video-output", -1, NULL, VIDEO_OUT_TEXT,
234 VIDEO_OUT_LONGTEXT, true );
236 add_integer( "dshow-audio-output", -1, NULL, AUDIO_OUT_TEXT,
237 AUDIO_OUT_LONGTEXT, true );
239 add_integer( "dshow-amtuner-mode", AMTUNER_MODE_TV, NULL,
240 AMTUNER_MODE_TEXT, AMTUNER_MODE_LONGTEXT, false);
241 change_integer_list( pi_amtuner_mode, ppsz_amtuner_mode_text, NULL );
243 add_integer( "dshow-audio-channels", 0, NULL, AUDIO_CHANNELS_TEXT,
244 AUDIO_CHANNELS_LONGTEXT, true );
245 add_integer( "dshow-audio-samplerate", 0, NULL, AUDIO_SAMPLERATE_TEXT,
246 AUDIO_SAMPLERATE_LONGTEXT, true );
247 add_integer( "dshow-audio-bitspersample", 0, NULL, AUDIO_BITSPERSAMPLE_TEXT,
248 AUDIO_BITSPERSAMPLE_LONGTEXT, true );
250 add_shortcut( "dshow" );
251 set_capability( "access_demux", 0 );
252 set_callbacks( DemuxOpen, DemuxClose );
255 set_description( N_("DirectShow input") );
256 set_capability( "access", 0 );
257 set_callbacks( AccessOpen, AccessClose );
261 /*****************************************************************************
262 * DirectShow elementary stream descriptor
263 *****************************************************************************/
264 typedef struct dshow_stream_t
267 IBaseFilter *p_device_filter;
268 CaptureFilter *p_capture_filter;
273 VIDEOINFOHEADER video;
284 /*****************************************************************************
285 * DirectShow utility functions
286 *****************************************************************************/
287 static void CreateDirectShowGraph( access_sys_t *p_sys )
289 p_sys->i_crossbar_route_depth = 0;
291 /* Create directshow filter graph */
292 if( SUCCEEDED( CoCreateInstance( CLSID_FilterGraph, 0, CLSCTX_INPROC,
293 (REFIID)IID_IFilterGraph, (void **)&p_sys->p_graph) ) )
295 /* Create directshow capture graph builder if available */
296 if( SUCCEEDED( CoCreateInstance( CLSID_CaptureGraphBuilder2, 0,
297 CLSCTX_INPROC, (REFIID)IID_ICaptureGraphBuilder2,
298 (void **)&p_sys->p_capture_graph_builder2 ) ) )
300 p_sys->p_capture_graph_builder2->
301 SetFiltergraph((IGraphBuilder *)p_sys->p_graph);
304 p_sys->p_graph->QueryInterface( IID_IMediaControl,
305 (void **)&p_sys->p_control );
309 static void DeleteDirectShowGraph( access_sys_t *p_sys )
311 DeleteCrossbarRoutes( p_sys );
313 /* Remove filters from graph */
314 for( int i = 0; i < p_sys->i_streams; i++ )
316 p_sys->p_graph->RemoveFilter( p_sys->pp_streams[i]->p_capture_filter );
317 p_sys->p_graph->RemoveFilter( p_sys->pp_streams[i]->p_device_filter );
318 p_sys->pp_streams[i]->p_capture_filter->Release();
319 p_sys->pp_streams[i]->p_device_filter->Release();
322 /* Release directshow objects */
323 if( p_sys->p_control )
325 p_sys->p_control->Release();
326 p_sys->p_control = NULL;
328 if( p_sys->p_capture_graph_builder2 )
330 p_sys->p_capture_graph_builder2->Release();
331 p_sys->p_capture_graph_builder2 = NULL;
336 p_sys->p_graph->Release();
337 p_sys->p_graph = NULL;
341 /*****************************************************************************
342 * CommonOpen: open direct show device
343 *****************************************************************************/
344 static int CommonOpen( vlc_object_t *p_this, access_sys_t *p_sys,
345 bool b_access_demux )
350 /* Get/parse options and open device(s) */
351 string vdevname, adevname;
352 int i_width = 0, i_height = 0, i_chroma = 0;
355 var_Create( p_this, "dshow-config", VLC_VAR_BOOL | VLC_VAR_DOINHERIT );
356 var_Create( p_this, "dshow-tuner", VLC_VAR_BOOL | VLC_VAR_DOINHERIT );
357 var_Create( p_this, "dshow-vdev", VLC_VAR_STRING | VLC_VAR_DOINHERIT );
358 var_Get( p_this, "dshow-vdev", &val );
359 if( val.psz_string ) vdevname = string( val.psz_string );
360 free( val.psz_string );
362 var_Create( p_this, "dshow-adev", VLC_VAR_STRING | VLC_VAR_DOINHERIT );
363 var_Get( p_this, "dshow-adev", &val );
364 if( val.psz_string ) adevname = string( val.psz_string );
365 free( val.psz_string );
367 static struct {char *psz_size; int i_width; int i_height;} size_table[] =
368 { { "subqcif", 128, 96 }, { "qsif", 160, 120 }, { "qcif", 176, 144 },
369 { "sif", 320, 240 }, { "cif", 352, 288 }, { "d1", 640, 480 },
373 var_Create( p_this, "dshow-size", VLC_VAR_STRING | VLC_VAR_DOINHERIT );
374 var_Get( p_this, "dshow-size", &val );
375 if( val.psz_string && *val.psz_string )
377 for( i = 0; size_table[i].psz_size; i++ )
379 if( !strcmp( val.psz_string, size_table[i].psz_size ) )
381 i_width = size_table[i].i_width;
382 i_height = size_table[i].i_height;
386 if( !size_table[i].psz_size ) /* Try to parse "WidthxHeight" */
389 i_width = strtol( val.psz_string, &psz_parser, 0 );
390 if( *psz_parser == 'x' || *psz_parser == 'X')
392 i_height = strtol( psz_parser + 1, &psz_parser, 0 );
394 msg_Dbg( p_this, "width x height %dx%d", i_width, i_height );
397 free( val.psz_string );
399 p_sys->b_chroma = false;
400 var_Create( p_this, "dshow-chroma", VLC_VAR_STRING | VLC_VAR_DOINHERIT );
401 var_Get( p_this, "dshow-chroma", &val );
402 if( val.psz_string && strlen( val.psz_string ) >= 4 )
404 i_chroma = VLC_FOURCC( val.psz_string[0], val.psz_string[1],
405 val.psz_string[2], val.psz_string[3] );
406 p_sys->b_chroma = true;
408 free( val.psz_string );
410 var_Create( p_this, "dshow-fps", VLC_VAR_FLOAT | VLC_VAR_DOINHERIT );
411 var_Create( p_this, "dshow-tuner-channel",
412 VLC_VAR_INTEGER | VLC_VAR_DOINHERIT );
413 var_Create( p_this, "dshow-tuner-country",
414 VLC_VAR_INTEGER | VLC_VAR_DOINHERIT );
415 var_Create( p_this, "dshow-tuner-input",
416 VLC_VAR_INTEGER | VLC_VAR_DOINHERIT );
418 var_Create( p_this, "dshow-amtuner-mode",
419 VLC_VAR_INTEGER | VLC_VAR_DOINHERIT );
421 var_Create( p_this, "dshow-caching", VLC_VAR_INTEGER | VLC_VAR_DOINHERIT );
423 var_Create( p_this, "dshow-video-input", VLC_VAR_INTEGER | VLC_VAR_DOINHERIT );
424 var_Create( p_this, "dshow-audio-input", VLC_VAR_INTEGER | VLC_VAR_DOINHERIT );
425 var_Create( p_this, "dshow-video-output", VLC_VAR_INTEGER | VLC_VAR_DOINHERIT );
426 var_Create( p_this, "dshow-audio-output", VLC_VAR_INTEGER | VLC_VAR_DOINHERIT );
428 /* Initialize OLE/COM */
431 /* Initialize some data */
432 p_sys->i_streams = 0;
433 p_sys->pp_streams = 0;
434 p_sys->i_width = i_width;
435 p_sys->i_height = i_height;
436 p_sys->i_chroma = i_chroma;
438 p_sys->p_graph = NULL;
439 p_sys->p_capture_graph_builder2 = NULL;
440 p_sys->p_control = NULL;
442 vlc_mutex_init( &p_sys->lock );
443 vlc_cond_init( p_this, &p_sys->wait );
445 /* Build directshow graph */
446 CreateDirectShowGraph( p_sys );
448 if( OpenDevice( p_this, p_sys, vdevname, 0 ) != VLC_SUCCESS )
450 msg_Err( p_this, "can't open video");
454 /* Check if we can handle the demuxing ourselves or need to spawn
455 * a demuxer module */
456 dshow_stream_t *p_stream = p_sys->pp_streams[p_sys->i_streams-1];
458 if( p_stream->mt.majortype == MEDIATYPE_Video )
460 if( /* Raw DV stream */
461 p_stream->i_fourcc == VLC_FOURCC('d','v','s','l') ||
462 p_stream->i_fourcc == VLC_FOURCC('d','v','s','d') ||
463 p_stream->i_fourcc == VLC_FOURCC('d','v','h','d') ||
464 /* Raw MPEG video stream */
465 p_stream->i_fourcc == VLC_FOURCC('m','p','2','v') )
471 /* Let the access (only) take care of that */
477 if( p_stream->mt.majortype == MEDIATYPE_Stream )
483 /* Let the access (only) take care of that */
487 var_Get( p_this, "dshow-tuner", &val );
490 /* FIXME: we do MEDIATYPE_Stream here so we don't do
492 ShowTunerProperties( p_this, p_sys->p_capture_graph_builder2,
493 p_stream->p_device_filter, 0 );
498 if( b_audio && OpenDevice( p_this, p_sys, adevname, 1 ) != VLC_SUCCESS )
500 msg_Err( p_this, "can't open audio");
503 for( i = p_sys->i_crossbar_route_depth-1; i >= 0 ; --i )
505 var_Get( p_this, "dshow-video-input", &val );
507 p_sys->crossbar_routes[i].VideoInputIndex=val.i_int;
508 var_Get( p_this, "dshow-video-output", &val );
510 p_sys->crossbar_routes[i].VideoOutputIndex=val.i_int;
511 var_Get( p_this, "dshow-audio-input", &val );
513 p_sys->crossbar_routes[i].AudioInputIndex=val.i_int;
514 var_Get( p_this, "dshow-audio-output", &val );
516 p_sys->crossbar_routes[i].AudioOutputIndex=val.i_int;
518 IAMCrossbar *pXbar = p_sys->crossbar_routes[i].pXbar;
519 LONG VideoInputIndex = p_sys->crossbar_routes[i].VideoInputIndex;
520 LONG VideoOutputIndex = p_sys->crossbar_routes[i].VideoOutputIndex;
521 LONG AudioInputIndex = p_sys->crossbar_routes[i].AudioInputIndex;
522 LONG AudioOutputIndex = p_sys->crossbar_routes[i].AudioOutputIndex;
524 if( SUCCEEDED(pXbar->Route(VideoOutputIndex, VideoInputIndex)) )
526 msg_Dbg( p_this, "crossbar at depth %d, routed video "
527 "output %ld to video input %ld", i, VideoOutputIndex,
530 if( AudioOutputIndex != -1 && AudioInputIndex != -1 )
532 if( SUCCEEDED( pXbar->Route(AudioOutputIndex,
535 msg_Dbg(p_this, "crossbar at depth %d, routed audio "
536 "output %ld to audio input %ld", i,
537 AudioOutputIndex, AudioInputIndex );
544 ** Show properties pages from other filters in graph
546 var_Get( p_this, "dshow-config", &val );
549 for( i = p_sys->i_crossbar_route_depth-1; i >= 0 ; --i )
551 IAMCrossbar *pXbar = p_sys->crossbar_routes[i].pXbar;
554 if( SUCCEEDED( pXbar->QueryInterface( IID_IBaseFilter,
557 ShowPropertyPage( p_XF );
563 /* Initialize some data */
564 p_sys->i_current_stream = 0;
566 if( !p_sys->i_streams ) return VLC_EGENERIC;
571 /*****************************************************************************
572 * DemuxOpen: open direct show device as an access_demux module
573 *****************************************************************************/
574 static int DemuxOpen( vlc_object_t *p_this )
576 demux_t *p_demux = (demux_t *)p_this;
580 p_sys = (access_sys_t *)malloc( sizeof( access_sys_t ) );
583 memset( p_sys, 0, sizeof( access_sys_t ) );
584 p_demux->p_sys = (demux_sys_t *)p_sys;
586 if( CommonOpen( p_this, p_sys, true ) != VLC_SUCCESS )
588 CommonClose( p_this, p_sys );
592 /* Everything is ready. Let's rock baby */
593 msg_Dbg( p_this, "Playing...");
594 p_sys->p_control->Run();
596 p_demux->pf_demux = Demux;
597 p_demux->pf_control = DemuxControl;
598 p_demux->info.i_update = 0;
599 p_demux->info.i_title = 0;
600 p_demux->info.i_seekpoint = 0;
602 for( i = 0; i < p_sys->i_streams; i++ )
604 dshow_stream_t *p_stream = p_sys->pp_streams[i];
607 if( p_stream->mt.majortype == MEDIATYPE_Video )
609 es_format_Init( &fmt, VIDEO_ES, p_stream->i_fourcc );
611 fmt.video.i_width = p_stream->header.video.bmiHeader.biWidth;
612 fmt.video.i_height = p_stream->header.video.bmiHeader.biHeight;
613 fmt.video.i_aspect = 4 * VOUT_ASPECT_FACTOR / 3;
615 if( !p_stream->header.video.bmiHeader.biCompression )
617 /* RGB DIB are coded from bottom to top */
618 fmt.video.i_height = (unsigned int)(-(int)fmt.video.i_height);
621 /* Setup rgb mask for RGB formats */
622 if( p_stream->i_fourcc == VLC_FOURCC('R','V','2','4') )
624 /* This is in BGR format */
625 fmt.video.i_bmask = 0x00ff0000;
626 fmt.video.i_gmask = 0x0000ff00;
627 fmt.video.i_rmask = 0x000000ff;
630 if( p_stream->header.video.AvgTimePerFrame )
632 fmt.video.i_frame_rate = 10000000;
633 fmt.video.i_frame_rate_base =
634 p_stream->header.video.AvgTimePerFrame;
637 else if( p_stream->mt.majortype == MEDIATYPE_Audio )
639 es_format_Init( &fmt, AUDIO_ES, p_stream->i_fourcc );
641 fmt.audio.i_channels = p_stream->header.audio.nChannels;
642 fmt.audio.i_rate = p_stream->header.audio.nSamplesPerSec;
643 fmt.audio.i_bitspersample = p_stream->header.audio.wBitsPerSample;
644 fmt.audio.i_blockalign = fmt.audio.i_channels *
645 fmt.audio.i_bitspersample / 8;
646 fmt.i_bitrate = fmt.audio.i_channels * fmt.audio.i_rate *
647 fmt.audio.i_bitspersample;
650 p_stream->p_es = es_out_Add( p_demux->out, &fmt );
656 /*****************************************************************************
657 * AccessOpen: open direct show device as an access module
658 *****************************************************************************/
659 static int AccessOpen( vlc_object_t *p_this )
661 access_t *p_access = (access_t*)p_this;
664 p_access->p_sys = p_sys = (access_sys_t *)malloc( sizeof( access_sys_t ) );
667 memset( p_sys, 0, sizeof( access_sys_t ) );
669 if( CommonOpen( p_this, p_sys, false ) != VLC_SUCCESS )
671 CommonClose( p_this, p_sys );
675 dshow_stream_t *p_stream = p_sys->pp_streams[0];
677 /* Check if we need to force demuxers */
678 if( !p_access->psz_demux || !*p_access->psz_demux )
680 if( p_stream->i_fourcc == VLC_FOURCC('d','v','s','l') ||
681 p_stream->i_fourcc == VLC_FOURCC('d','v','s','d') ||
682 p_stream->i_fourcc == VLC_FOURCC('d','v','h','d') )
684 free( p_access->psz_demux );
685 p_access->psz_demux = strdup( "rawdv" );
687 else if( p_stream->i_fourcc == VLC_FOURCC('m','p','2','v') )
689 free( p_access->psz_demux );
690 p_access->psz_demux = strdup( "mpgv" );
695 p_access->pf_read = NULL;
696 p_access->pf_block = ReadCompressed;
697 p_access->pf_control = AccessControl;
698 p_access->pf_seek = NULL;
699 p_access->info.i_update = 0;
700 p_access->info.i_size = 0;
701 p_access->info.i_pos = 0;
702 p_access->info.b_eof = false;
703 p_access->info.i_title = 0;
704 p_access->info.i_seekpoint = 0;
705 p_access->p_sys = p_sys;
707 /* Everything is ready. Let's rock baby */
708 msg_Dbg( p_this, "Playing...");
709 p_sys->p_control->Run();
714 /*****************************************************************************
715 * CommonClose: close device
716 *****************************************************************************/
717 static void CommonClose( vlc_object_t *p_this, access_sys_t *p_sys )
719 msg_Dbg( p_this, "releasing DirectShow");
721 DeleteDirectShowGraph( p_sys );
723 /* Uninitialize OLE/COM */
726 for( int i = 0; i < p_sys->i_streams; i++ ) delete p_sys->pp_streams[i];
727 if( p_sys->i_streams ) free( p_sys->pp_streams );
729 vlc_mutex_destroy( &p_sys->lock );
730 vlc_cond_destroy( &p_sys->wait );
735 /*****************************************************************************
736 * AccessClose: close device
737 *****************************************************************************/
738 static void AccessClose( vlc_object_t *p_this )
740 access_t *p_access = (access_t *)p_this;
741 access_sys_t *p_sys = p_access->p_sys;
743 /* Stop capturing stuff */
744 p_sys->p_control->Stop();
746 CommonClose( p_this, p_sys );
749 /*****************************************************************************
750 * DemuxClose: close device
751 *****************************************************************************/
752 static void DemuxClose( vlc_object_t *p_this )
754 demux_t *p_demux = (demux_t *)p_this;
755 access_sys_t *p_sys = (access_sys_t *)p_demux->p_sys;
757 /* Stop capturing stuff */
758 p_sys->p_control->Stop();
760 CommonClose( p_this, p_sys );
763 /****************************************************************************
765 ****************************************************************************/
766 static bool ConnectFilters( vlc_object_t *p_this, access_sys_t *p_sys,
767 IBaseFilter *p_filter,
768 CaptureFilter *p_capture_filter )
770 CapturePin *p_input_pin = p_capture_filter->CustomGetPin();
772 AM_MEDIA_TYPE mediaType = p_input_pin->CustomGetMediaType();
774 if( p_sys->p_capture_graph_builder2 )
776 if( FAILED(p_sys->p_capture_graph_builder2->
777 RenderStream( &PIN_CATEGORY_CAPTURE, &mediaType.majortype,
778 p_filter, 0, (IBaseFilter *)p_capture_filter )) )
783 // Sort out all the possible video inputs
784 // The class needs to be given the capture filters ANALOGVIDEO input pin
786 if( ( mediaType.majortype == MEDIATYPE_Video ||
787 mediaType.majortype == MEDIATYPE_Stream ) &&
788 SUCCEEDED(p_filter->EnumPins(&pins)) )
794 IKsPropertySet *pKs=0;
798 while( !Found && ( S_OK == pins->Next(1, &pP, &n) ) )
800 if( S_OK == pP->QueryPinInfo(&pinInfo) )
802 // is this pin an ANALOGVIDEOIN input pin?
803 if( pinInfo.dir == PINDIR_INPUT &&
804 pP->QueryInterface( IID_IKsPropertySet,
805 (void **)&pKs ) == S_OK )
807 if( pKs->Get( AMPROPSETID_Pin,
808 AMPROPERTY_PIN_CATEGORY, NULL, 0,
809 &guid, sizeof(GUID), &dw ) == S_OK )
811 if( guid == PIN_CATEGORY_ANALOGVIDEOIN )
813 // recursively search crossbar routes
814 FindCrossbarRoutes( p_this, p_sys, pP, 0 );
821 pinInfo.pFilter->Release();
831 IEnumPins *p_enumpins;
834 if( S_OK != p_filter->EnumPins( &p_enumpins ) ) return false;
836 while( S_OK == p_enumpins->Next( 1, &p_pin, NULL ) )
838 PIN_DIRECTION pin_dir;
839 p_pin->QueryDirection( &pin_dir );
841 if( pin_dir == PINDIR_OUTPUT &&
842 p_sys->p_graph->ConnectDirect( p_pin, (IPin *)p_input_pin,
846 p_enumpins->Release();
852 p_enumpins->Release();
858 * get fourcc priority from arbritary preference, the higher the better
860 static int GetFourCCPriority( int i_fourcc )
864 case VLC_FOURCC('I','4','2','0'):
865 case VLC_FOURCC('f','l','3','2'):
867 case VLC_FOURCC('Y','V','1','2'):
868 case VLC_FOURCC('a','r','a','w'):
870 case VLC_FOURCC('R','V','2','4'):
872 case VLC_FOURCC('Y','U','Y','2'):
873 case VLC_FOURCC('R','V','3','2'):
874 case VLC_FOURCC('R','G','B','A'):
881 #define MAX_MEDIA_TYPES 32
883 static int OpenDevice( vlc_object_t *p_this, access_sys_t *p_sys,
884 string devicename, bool b_audio )
886 /* See if device is already opened */
887 for( int i = 0; i < p_sys->i_streams; i++ )
889 if( devicename.size() &&
890 p_sys->pp_streams[i]->devicename == devicename )
897 list<string> list_devices;
899 /* Enumerate devices and display their names */
900 FindCaptureDevice( p_this, NULL, &list_devices, b_audio );
902 if( !list_devices.size() )
905 list<string>::iterator iter;
906 for( iter = list_devices.begin(); iter != list_devices.end(); iter++ )
907 msg_Dbg( p_this, "found device: %s", iter->c_str() );
909 /* If no device name was specified, pick the 1st one */
910 if( devicename.size() == 0 )
912 devicename = *list_devices.begin();
915 // Use the system device enumerator and class enumerator to find
916 // a capture/preview device, such as a desktop USB video camera.
917 IBaseFilter *p_device_filter =
918 FindCaptureDevice( p_this, &devicename, 0, b_audio );
919 if( p_device_filter )
920 msg_Dbg( p_this, "using device: %s", devicename.c_str() );
923 msg_Err( p_this, "can't use device: %s, unsupported device type",
924 devicename.c_str() );
925 intf_UserFatal( p_this, false, _("Capturing failed"),
926 _("VLC cannot use the device \"%s\", because its "
927 "type is not supported.") );
931 // Retreive acceptable media types supported by device
932 AM_MEDIA_TYPE media_types[MAX_MEDIA_TYPES];
934 EnumDeviceCaps( p_this, p_device_filter, b_audio ? 0 : p_sys->i_chroma,
935 p_sys->i_width, p_sys->i_height,
936 b_audio ? var_CreateGetInteger( p_this, "dshow-audio-channels" ) : 0,
937 b_audio ? var_CreateGetInteger( p_this, "dshow-audio-samplerate" ) : 0,
938 b_audio ? var_CreateGetInteger( p_this, "dshow-audio-bitspersample" ) : 0,
939 media_types, MAX_MEDIA_TYPES );
941 AM_MEDIA_TYPE *mt = NULL;
943 if( media_count > 0 )
945 mt = (AM_MEDIA_TYPE *)CoTaskMemAlloc(sizeof(AM_MEDIA_TYPE) * media_count);
947 // Order and copy returned media types according to arbitrary
949 for( size_t c = 0; c < media_count; c++ )
952 GetFourCCPriority(GetFourCCFromMediaType(media_types[c]));
953 size_t slot_copy = c;
954 for( size_t d = c+1; d < media_count; d++ )
957 GetFourCCPriority(GetFourCCFromMediaType(media_types[d]));
958 if( priority > slot_priority )
960 slot_priority = priority;
966 mt[c] = media_types[slot_copy];
967 media_types[slot_copy] = media_types[c];
971 mt[c] = media_types[c];
977 msg_Err( p_this, "capture device '%s' does not support required parameters !", devicename.c_str() );
978 intf_UserFatal( p_this, false, _("Capturing failed"),
979 _("The capture device \"%s\" does not support the "
980 "required parameters."), devicename.c_str() );
981 p_device_filter->Release();
985 /* Create and add our capture filter */
986 CaptureFilter *p_capture_filter =
987 new CaptureFilter( p_this, p_sys, mt, media_count );
988 p_sys->p_graph->AddFilter( p_capture_filter, 0 );
990 /* Add the device filter to the graph (seems necessary with VfW before
991 * accessing pin attributes). */
992 p_sys->p_graph->AddFilter( p_device_filter, 0 );
994 /* Attempt to connect one of this device's capture output pins */
995 msg_Dbg( p_this, "connecting filters" );
996 if( ConnectFilters( p_this, p_sys, p_device_filter, p_capture_filter ) )
999 msg_Dbg( p_this, "filters connected successfully !" );
1001 dshow_stream_t dshow_stream;
1002 dshow_stream.b_pts = false;
1003 dshow_stream.p_es = 0;
1005 p_capture_filter->CustomGetPin()->CustomGetMediaType();
1007 /* Show Device properties. Done here so the VLC stream is setup with
1008 * the proper parameters. */
1010 var_Get( p_this, "dshow-config", &val );
1013 ShowDeviceProperties( p_this, p_sys->p_capture_graph_builder2,
1014 p_device_filter, b_audio );
1017 ConfigTuner( p_this, p_sys->p_capture_graph_builder2,
1020 var_Get( p_this, "dshow-tuner", &val );
1021 if( val.b_bool && dshow_stream.mt.majortype != MEDIATYPE_Stream )
1023 /* FIXME: we do MEDIATYPE_Stream later so we don't do it twice. */
1024 ShowTunerProperties( p_this, p_sys->p_capture_graph_builder2,
1025 p_device_filter, b_audio );
1029 p_capture_filter->CustomGetPin()->CustomGetMediaType();
1031 dshow_stream.i_fourcc = GetFourCCFromMediaType( dshow_stream.mt );
1032 if( dshow_stream.i_fourcc )
1034 if( dshow_stream.mt.majortype == MEDIATYPE_Video )
1036 dshow_stream.header.video =
1037 *(VIDEOINFOHEADER *)dshow_stream.mt.pbFormat;
1038 msg_Dbg( p_this, "MEDIATYPE_Video" );
1039 msg_Dbg( p_this, "selected video pin accepts format: %4.4s",
1040 (char *)&dshow_stream.i_fourcc);
1042 else if( dshow_stream.mt.majortype == MEDIATYPE_Audio )
1044 dshow_stream.header.audio =
1045 *(WAVEFORMATEX *)dshow_stream.mt.pbFormat;
1046 msg_Dbg( p_this, "MEDIATYPE_Audio" );
1047 msg_Dbg( p_this, "selected audio pin accepts format: %4.4s",
1048 (char *)&dshow_stream.i_fourcc);
1050 else if( dshow_stream.mt.majortype == MEDIATYPE_Stream )
1052 msg_Dbg( p_this, "MEDIATYPE_Stream" );
1053 msg_Dbg( p_this, "selected stream pin accepts format: %4.4s",
1054 (char *)&dshow_stream.i_fourcc);
1058 msg_Dbg( p_this, "unknown stream majortype" );
1062 /* Add directshow elementary stream to our list */
1063 dshow_stream.p_device_filter = p_device_filter;
1064 dshow_stream.p_capture_filter = p_capture_filter;
1066 p_sys->pp_streams = (dshow_stream_t **)realloc( p_sys->pp_streams,
1067 sizeof(dshow_stream_t *) * (p_sys->i_streams + 1) );
1068 p_sys->pp_streams[p_sys->i_streams] = new dshow_stream_t;
1069 *p_sys->pp_streams[p_sys->i_streams++] = dshow_stream;
1076 /* Remove filters from graph */
1077 p_sys->p_graph->RemoveFilter( p_device_filter );
1078 p_sys->p_graph->RemoveFilter( p_capture_filter );
1080 /* Release objects */
1081 p_device_filter->Release();
1082 p_capture_filter->Release();
1084 return VLC_EGENERIC;
1087 static IBaseFilter *
1088 FindCaptureDevice( vlc_object_t *p_this, string *p_devicename,
1089 list<string> *p_listdevices, bool b_audio )
1091 IBaseFilter *p_base_filter = NULL;
1092 IMoniker *p_moniker = NULL;
1095 list<string> devicelist;
1097 /* Create the system device enumerator */
1098 ICreateDevEnum *p_dev_enum = NULL;
1100 hr = CoCreateInstance( CLSID_SystemDeviceEnum, NULL, CLSCTX_INPROC,
1101 IID_ICreateDevEnum, (void **)&p_dev_enum );
1104 msg_Err( p_this, "failed to create the device enumerator (0x%lx)", hr);
1108 /* Create an enumerator for the video capture devices */
1109 IEnumMoniker *p_class_enum = NULL;
1111 hr = p_dev_enum->CreateClassEnumerator( CLSID_VideoInputDeviceCategory,
1114 hr = p_dev_enum->CreateClassEnumerator( CLSID_AudioInputDeviceCategory,
1116 p_dev_enum->Release();
1119 msg_Err( p_this, "failed to create the class enumerator (0x%lx)", hr );
1123 /* If there are no enumerators for the requested type, then
1124 * CreateClassEnumerator will succeed, but p_class_enum will be NULL */
1125 if( p_class_enum == NULL )
1127 msg_Err( p_this, "no capture device was detected" );
1131 /* Enumerate the devices */
1133 /* Note that if the Next() call succeeds but there are no monikers,
1134 * it will return S_FALSE (which is not a failure). Therefore, we check
1135 * that the return code is S_OK instead of using SUCCEEDED() macro. */
1137 while( p_class_enum->Next( 1, &p_moniker, &i_fetched ) == S_OK )
1139 /* Getting the property page to get the device name */
1140 IPropertyBag *p_bag;
1141 hr = p_moniker->BindToStorage( 0, 0, IID_IPropertyBag,
1147 hr = p_bag->Read( L"FriendlyName", &var, NULL );
1151 int i_convert = WideCharToMultiByte(CP_ACP, 0, var.bstrVal,
1152 SysStringLen(var.bstrVal), NULL, 0, NULL, NULL);
1153 char *p_buf = (char *)alloca( i_convert+1 ); p_buf[0] = 0;
1154 WideCharToMultiByte( CP_ACP, 0, var.bstrVal,
1155 SysStringLen(var.bstrVal), p_buf, i_convert, NULL, NULL );
1156 SysFreeString(var.bstrVal);
1157 p_buf[i_convert] = '\0';
1159 string devname = string(p_buf);
1162 /* find out if this name is already used by a previously found device */
1163 list<string>::const_iterator iter = devicelist.begin();
1164 list<string>::const_iterator end = devicelist.end();
1165 while ( iter != end )
1167 if( 0 == (*iter).compare(0, devname.size(), devname) )
1173 /* we have a duplicate device name, append a sequence number to name
1174 to provive a unique list back to the user */
1176 sprintf(seq, " #%d", dup);
1177 devname.append(seq);
1179 devicelist.push_back( devname );
1181 if( p_devicename && *p_devicename == devname )
1183 /* Bind Moniker to a filter object */
1184 hr = p_moniker->BindToObject( 0, 0, IID_IBaseFilter,
1185 (void **)&p_base_filter );
1188 msg_Err( p_this, "couldn't bind moniker to filter "
1189 "object (0x%lx)", hr );
1190 p_moniker->Release();
1191 p_class_enum->Release();
1194 p_moniker->Release();
1195 p_class_enum->Release();
1196 return p_base_filter;
1201 p_moniker->Release();
1204 p_class_enum->Release();
1206 if( p_listdevices ) {
1208 *p_listdevices = devicelist;
1213 static size_t EnumDeviceCaps( vlc_object_t *p_this, IBaseFilter *p_filter,
1214 int i_fourcc, int i_width, int i_height,
1215 int i_channels, int i_samplespersec,
1216 int i_bitspersample, AM_MEDIA_TYPE *mt,
1219 IEnumPins *p_enumpins;
1221 IEnumMediaTypes *p_enummt;
1222 size_t mt_count = 0;
1224 LONGLONG i_AvgTimePerFrame = 0;
1225 float r_fps = var_GetFloat( p_this, "dshow-fps" );
1227 i_AvgTimePerFrame = 10000000000LL/(LONGLONG)(r_fps*1000.0f);
1229 if( FAILED(p_filter->EnumPins( &p_enumpins )) )
1231 msg_Dbg( p_this, "EnumDeviceCaps failed: no pin enumeration !");
1235 while( S_OK == p_enumpins->Next( 1, &p_output_pin, NULL ) )
1239 if( S_OK == p_output_pin->QueryPinInfo( &info ) )
1241 msg_Dbg( p_this, "EnumDeviceCaps: %s pin: %S",
1242 info.dir == PINDIR_INPUT ? "input" : "output",
1244 if( info.pFilter ) info.pFilter->Release();
1247 p_output_pin->Release();
1250 p_enumpins->Reset();
1252 while( !mt_count && p_enumpins->Next( 1, &p_output_pin, NULL ) == S_OK )
1256 if( S_OK == p_output_pin->QueryPinInfo( &info ) )
1258 if( info.pFilter ) info.pFilter->Release();
1259 if( info.dir == PINDIR_INPUT )
1261 p_output_pin->Release();
1264 msg_Dbg( p_this, "EnumDeviceCaps: trying pin %S", info.achName );
1267 AM_MEDIA_TYPE *p_mt;
1270 ** Configure pin with a default compatible media if possible
1273 IAMStreamConfig *pSC;
1274 if( SUCCEEDED(p_output_pin->QueryInterface( IID_IAMStreamConfig,
1277 int piCount, piSize;
1278 if( SUCCEEDED(pSC->GetNumberOfCapabilities(&piCount, &piSize)) )
1280 BYTE *pSCC= (BYTE *)CoTaskMemAlloc(piSize);
1283 int i_priority = -1;
1284 for( int i=0; i<piCount; ++i )
1286 if( SUCCEEDED(pSC->GetStreamCaps(i, &p_mt, pSCC)) )
1288 int i_current_fourcc = GetFourCCFromMediaType( *p_mt );
1289 int i_current_priority = GetFourCCPriority(i_current_fourcc);
1291 if( (i_fourcc && (i_current_fourcc != i_fourcc))
1292 || (i_priority > i_current_priority) )
1294 // unwanted chroma, try next media type
1295 FreeMediaType( *p_mt );
1296 CoTaskMemFree( (PVOID)p_mt );
1300 if( MEDIATYPE_Video == p_mt->majortype
1301 && FORMAT_VideoInfo == p_mt->formattype )
1303 VIDEO_STREAM_CONFIG_CAPS *pVSCC = reinterpret_cast<VIDEO_STREAM_CONFIG_CAPS*>(pSCC);
1304 VIDEOINFOHEADER *pVih = reinterpret_cast<VIDEOINFOHEADER*>(p_mt->pbFormat);
1306 if( i_AvgTimePerFrame )
1308 if( pVSCC->MinFrameInterval > i_AvgTimePerFrame
1309 || i_AvgTimePerFrame > pVSCC->MaxFrameInterval )
1311 // required frame rate not compatible, try next media type
1312 FreeMediaType( *p_mt );
1313 CoTaskMemFree( (PVOID)p_mt );
1316 pVih->AvgTimePerFrame = i_AvgTimePerFrame;
1321 if( i_width % pVSCC->OutputGranularityX
1322 || pVSCC->MinOutputSize.cx > i_width
1323 || i_width > pVSCC->MaxOutputSize.cx )
1325 // required width not compatible, try next media type
1326 FreeMediaType( *p_mt );
1327 CoTaskMemFree( (PVOID)p_mt );
1330 pVih->bmiHeader.biWidth = i_width;
1335 if( i_height % pVSCC->OutputGranularityY
1336 || pVSCC->MinOutputSize.cy > i_height
1337 || i_height > pVSCC->MaxOutputSize.cy )
1339 // required height not compatible, try next media type
1340 FreeMediaType( *p_mt );
1341 CoTaskMemFree( (PVOID)p_mt );
1344 pVih->bmiHeader.biHeight = i_height;
1347 // Set the sample size and image size.
1348 // (Round the image width up to a DWORD boundary.)
1349 p_mt->lSampleSize = pVih->bmiHeader.biSizeImage =
1350 ((pVih->bmiHeader.biWidth + 3) & ~3) *
1351 pVih->bmiHeader.biHeight * (pVih->bmiHeader.biBitCount>>3);
1353 // no cropping, use full video input buffer
1354 memset(&(pVih->rcSource), 0, sizeof(RECT));
1355 memset(&(pVih->rcTarget), 0, sizeof(RECT));
1357 // select this format as default
1358 if( SUCCEEDED( pSC->SetFormat(p_mt) ) )
1360 i_priority = i_current_priority;
1362 // no need to check any more media types
1366 else if( p_mt->majortype == MEDIATYPE_Audio
1367 && p_mt->formattype == FORMAT_WaveFormatEx )
1369 AUDIO_STREAM_CONFIG_CAPS *pASCC = reinterpret_cast<AUDIO_STREAM_CONFIG_CAPS*>(pSCC);
1370 WAVEFORMATEX *pWfx = reinterpret_cast<WAVEFORMATEX*>(p_mt->pbFormat);
1372 if( i_current_fourcc && (WAVE_FORMAT_PCM == pWfx->wFormatTag) )
1374 int val = i_channels;
1378 if( val % pASCC->ChannelsGranularity
1379 || (unsigned int)val < pASCC->MinimumChannels
1380 || (unsigned int)val > pASCC->MaximumChannels )
1382 // required number channels not available, try next media type
1383 FreeMediaType( *p_mt );
1384 CoTaskMemFree( (PVOID)p_mt );
1387 pWfx->nChannels = val;
1389 val = i_samplespersec;
1393 if( val % pASCC->SampleFrequencyGranularity
1394 || (unsigned int)val < pASCC->MinimumSampleFrequency
1395 || (unsigned int)val > pASCC->MaximumSampleFrequency )
1397 // required sampling rate not available, try next media type
1398 FreeMediaType( *p_mt );
1399 CoTaskMemFree( (PVOID)p_mt );
1402 pWfx->nSamplesPerSec = val;
1404 val = i_bitspersample;
1407 if( VLC_FOURCC('f', 'l', '3', '2') == i_current_fourcc )
1413 if( val % pASCC->BitsPerSampleGranularity
1414 || (unsigned int)val < pASCC->MinimumBitsPerSample
1415 || (unsigned int)val > pASCC->MaximumBitsPerSample )
1417 // required sample size not available, try next media type
1418 FreeMediaType( *p_mt );
1419 CoTaskMemFree( (PVOID)p_mt );
1423 pWfx->wBitsPerSample = val;
1424 pWfx->nBlockAlign = (pWfx->wBitsPerSample * pWfx->nChannels)/8;
1425 pWfx->nAvgBytesPerSec = pWfx->nSamplesPerSec * pWfx->nBlockAlign;
1427 // select this format as default
1428 if( SUCCEEDED( pSC->SetFormat(p_mt) ) )
1430 i_priority = i_current_priority;
1434 FreeMediaType( *p_mt );
1435 CoTaskMemFree( (PVOID)p_mt );
1438 CoTaskMemFree( (LPVOID)pSCC );
1439 if( i_priority >= 0 )
1440 msg_Dbg( p_this, "EnumDeviceCaps: input pin default format configured");
1447 ** Probe pin for available medias (may be a previously configured one)
1450 if( FAILED( p_output_pin->EnumMediaTypes( &p_enummt ) ) )
1452 p_output_pin->Release();
1456 while( p_enummt->Next( 1, &p_mt, NULL ) == S_OK )
1458 int i_current_fourcc = GetFourCCFromMediaType( *p_mt );
1459 if( i_current_fourcc && p_mt->majortype == MEDIATYPE_Video
1460 && p_mt->formattype == FORMAT_VideoInfo )
1462 int i_current_width = ((VIDEOINFOHEADER *)p_mt->pbFormat)->bmiHeader.biWidth;
1463 int i_current_height = ((VIDEOINFOHEADER *)p_mt->pbFormat)->bmiHeader.biHeight;
1464 LONGLONG i_current_atpf = ((VIDEOINFOHEADER *)p_mt->pbFormat)->AvgTimePerFrame;
1466 if( i_current_height < 0 )
1467 i_current_height = -i_current_height;
1469 msg_Dbg( p_this, "EnumDeviceCaps: input pin "
1470 "accepts chroma: %4.4s, width:%i, height:%i, fps:%f",
1471 (char *)&i_current_fourcc, i_current_width,
1472 i_current_height, (10000000.0f/((float)i_current_atpf)) );
1474 if( ( !i_fourcc || i_fourcc == i_current_fourcc ) &&
1475 ( !i_width || i_width == i_current_width ) &&
1476 ( !i_height || i_height == i_current_height ) &&
1477 ( !i_AvgTimePerFrame || i_AvgTimePerFrame == i_current_atpf ) &&
1481 mt[mt_count++] = *p_mt;
1483 else FreeMediaType( *p_mt );
1485 else if( i_current_fourcc && p_mt->majortype == MEDIATYPE_Audio
1486 && p_mt->formattype == FORMAT_WaveFormatEx)
1488 int i_current_channels =
1489 ((WAVEFORMATEX *)p_mt->pbFormat)->nChannels;
1490 int i_current_samplespersec =
1491 ((WAVEFORMATEX *)p_mt->pbFormat)->nSamplesPerSec;
1492 int i_current_bitspersample =
1493 ((WAVEFORMATEX *)p_mt->pbFormat)->wBitsPerSample;
1495 msg_Dbg( p_this, "EnumDeviceCaps: input pin "
1496 "accepts format: %4.4s, channels:%i, "
1497 "samples/sec:%i bits/sample:%i",
1498 (char *)&i_current_fourcc, i_current_channels,
1499 i_current_samplespersec, i_current_bitspersample);
1501 if( (!i_channels || i_channels == i_current_channels) &&
1502 (!i_samplespersec ||
1503 i_samplespersec == i_current_samplespersec) &&
1504 (!i_bitspersample ||
1505 i_bitspersample == i_current_bitspersample) &&
1509 mt[mt_count++] = *p_mt;
1511 /* Setup a few properties like the audio latency */
1512 IAMBufferNegotiation *p_ambuf;
1513 if( SUCCEEDED( p_output_pin->QueryInterface(
1514 IID_IAMBufferNegotiation, (void **)&p_ambuf ) ) )
1516 ALLOCATOR_PROPERTIES AllocProp;
1517 AllocProp.cbAlign = -1;
1519 /* 100 ms of latency */
1520 AllocProp.cbBuffer = i_current_channels *
1521 i_current_samplespersec *
1522 i_current_bitspersample / 8 / 10;
1524 AllocProp.cbPrefix = -1;
1525 AllocProp.cBuffers = -1;
1526 p_ambuf->SuggestAllocatorProperties( &AllocProp );
1530 else FreeMediaType( *p_mt );
1532 else if( i_current_fourcc && p_mt->majortype == MEDIATYPE_Stream )
1534 msg_Dbg( p_this, "EnumDeviceCaps: input pin "
1535 "accepts stream format: %4.4s",
1536 (char *)&i_current_fourcc );
1538 if( ( !i_fourcc || i_fourcc == i_current_fourcc ) &&
1542 mt[mt_count++] = *p_mt;
1543 i_fourcc = i_current_fourcc;
1545 else FreeMediaType( *p_mt );
1549 char *psz_type = "unknown";
1550 if( p_mt->majortype == MEDIATYPE_Video ) psz_type = "video";
1551 if( p_mt->majortype == MEDIATYPE_Audio ) psz_type = "audio";
1552 if( p_mt->majortype == MEDIATYPE_Stream ) psz_type = "stream";
1553 msg_Dbg( p_this, "EnumDeviceCaps: input pin media: unsupported format "
1554 "(%s %4.4s)", psz_type, (char *)&p_mt->subtype );
1556 FreeMediaType( *p_mt );
1558 CoTaskMemFree( (PVOID)p_mt );
1561 if( !mt_count && p_enummt->Reset() == S_OK )
1563 // VLC did not find any supported MEDIATYPE for this output pin.
1564 // However the graph builder might insert converter filters in
1565 // the graph if we use a different codec in VLC filter input pin.
1566 // however, in order to avoid nasty surprises, make use of this
1567 // facility only for known unsupported codecs.
1569 while( !mt_count && p_enummt->Next( 1, &p_mt, NULL ) == S_OK )
1571 // the first four bytes of subtype GUID contains the codec FOURCC
1572 const char *pfcc = (char *)&p_mt->subtype;
1573 int i_current_fourcc = VLC_FOURCC(pfcc[0], pfcc[1], pfcc[2], pfcc[3]);
1574 if( VLC_FOURCC('H','C','W','2') == i_current_fourcc
1575 && p_mt->majortype == MEDIATYPE_Video )
1577 // output format for 'Hauppauge WinTV PVR PCI II Capture'
1578 // try I420 as an input format
1579 i_current_fourcc = VLC_FOURCC('I','4','2','0');
1580 if( !i_fourcc || i_fourcc == i_current_fourcc )
1582 // return alternative media type
1586 mtr.majortype = MEDIATYPE_Video;
1587 mtr.subtype = MEDIASUBTYPE_I420;
1588 mtr.bFixedSizeSamples = TRUE;
1589 mtr.bTemporalCompression = FALSE;
1591 mtr.formattype = FORMAT_VideoInfo;
1592 mtr.cbFormat = sizeof(vh);
1593 mtr.pbFormat = (BYTE *)&vh;
1595 memset(&vh, 0, sizeof(vh));
1597 vh.bmiHeader.biSize = sizeof(vh.bmiHeader);
1598 vh.bmiHeader.biWidth = i_width > 0 ? i_width :
1599 ((VIDEOINFOHEADER *)p_mt->pbFormat)->bmiHeader.biWidth;
1600 vh.bmiHeader.biHeight = i_height > 0 ? i_height :
1601 ((VIDEOINFOHEADER *)p_mt->pbFormat)->bmiHeader.biHeight;
1602 vh.bmiHeader.biPlanes = 3;
1603 vh.bmiHeader.biBitCount = 12;
1604 vh.bmiHeader.biCompression = VLC_FOURCC('I','4','2','0');
1605 vh.bmiHeader.biSizeImage = vh.bmiHeader.biWidth * 12 *
1606 vh.bmiHeader.biHeight / 8;
1607 mtr.lSampleSize = vh.bmiHeader.biSizeImage;
1609 msg_Dbg( p_this, "EnumDeviceCaps: input pin media: using 'I420' in place of unsupported format 'HCW2'");
1611 if( SUCCEEDED(CopyMediaType(mt+mt_count, &mtr)) )
1615 FreeMediaType( *p_mt );
1619 p_enummt->Release();
1620 p_output_pin->Release();
1623 p_enumpins->Release();
1627 /*****************************************************************************
1628 * ReadCompressed: reads compressed (MPEG/DV) data from the device.
1629 *****************************************************************************
1630 * Returns -1 in case of error, 0 in case of EOF, otherwise the number of
1632 *****************************************************************************/
1633 static block_t *ReadCompressed( access_t *p_access )
1635 access_sys_t *p_sys = p_access->p_sys;
1636 dshow_stream_t *p_stream = NULL;
1637 VLCMediaSample sample;
1639 /* Read 1 DV/MPEG frame (they contain the video and audio data) */
1641 /* There must be only 1 elementary stream to produce a valid stream
1642 * of MPEG or DV data */
1643 p_stream = p_sys->pp_streams[0];
1647 if( !vlc_object_alive (p_access) || p_access->b_error ) return 0;
1649 /* Get new sample/frame from the elementary stream (blocking). */
1650 vlc_mutex_lock( &p_sys->lock );
1652 if( p_stream->p_capture_filter->CustomGetPin()
1653 ->CustomGetSample( &sample ) != S_OK )
1655 /* No data available. Wait until some data has arrived */
1656 vlc_cond_wait( &p_sys->wait, &p_sys->lock );
1657 vlc_mutex_unlock( &p_sys->lock );
1661 vlc_mutex_unlock( &p_sys->lock );
1668 int i_data_size = sample.p_sample->GetActualDataLength();
1670 if( !i_data_size || !(p_block = block_New( p_access, i_data_size )) )
1672 sample.p_sample->Release();
1676 sample.p_sample->GetPointer( &p_data );
1677 vlc_memcpy( p_block->p_buffer, p_data, i_data_size );
1678 sample.p_sample->Release();
1680 /* The caller got what he wanted */
1684 return 0; /* never reached */
1687 /****************************************************************************
1689 ****************************************************************************/
1690 static int Demux( demux_t *p_demux )
1692 access_sys_t *p_sys = (access_sys_t *)p_demux->p_sys;
1693 dshow_stream_t *p_stream = NULL;
1694 VLCMediaSample sample;
1695 int i_data_size, i_stream;
1699 vlc_mutex_lock( &p_sys->lock );
1701 /* Try to grab an audio sample (audio has a higher priority) */
1702 for( i_stream = 0; i_stream < p_sys->i_streams; i_stream++ )
1704 p_stream = p_sys->pp_streams[i_stream];
1705 if( p_stream->mt.majortype == MEDIATYPE_Audio &&
1706 p_stream->p_capture_filter &&
1707 p_stream->p_capture_filter->CustomGetPin()
1708 ->CustomGetSample( &sample ) == S_OK )
1713 /* Try to grab a video sample */
1714 if( i_stream == p_sys->i_streams )
1716 for( i_stream = 0; i_stream < p_sys->i_streams; i_stream++ )
1718 p_stream = p_sys->pp_streams[i_stream];
1719 if( p_stream->p_capture_filter &&
1720 p_stream->p_capture_filter->CustomGetPin()
1721 ->CustomGetSample( &sample ) == S_OK )
1728 vlc_mutex_unlock( &p_sys->lock );
1730 if( i_stream == p_sys->i_streams )
1732 /* Sleep so we do not consume all the cpu, 10ms seems
1733 * like a good value (100fps) */
1741 i_data_size = sample.p_sample->GetActualDataLength();
1742 sample.p_sample->GetPointer( &p_data );
1744 REFERENCE_TIME i_pts, i_end_date;
1745 HRESULT hr = sample.p_sample->GetTime( &i_pts, &i_end_date );
1746 if( hr != VFW_S_NO_STOP_TIME && hr != S_OK ) i_pts = 0;
1750 if( p_stream->mt.majortype == MEDIATYPE_Video || !p_stream->b_pts )
1752 /* Use our data timestamp */
1753 i_pts = sample.i_timestamp;
1754 p_stream->b_pts = true;
1758 i_pts /= 10; /* Dshow works with 100 nano-seconds resolution */
1761 msg_Dbg( p_demux, "Read() stream: %i, size: %i, PTS: %"PRId64,
1762 i_stream, i_data_size, i_pts );
1765 p_block = block_New( p_demux, i_data_size );
1766 vlc_memcpy( p_block->p_buffer, p_data, i_data_size );
1767 p_block->i_pts = p_block->i_dts = i_pts;
1768 sample.p_sample->Release();
1770 es_out_Control( p_demux->out, ES_OUT_SET_PCR, i_pts > 0 ? i_pts : 0 );
1771 es_out_Send( p_demux->out, p_stream->p_es, p_block );
1776 /*****************************************************************************
1778 *****************************************************************************/
1779 static int AccessControl( access_t *p_access, int i_query, va_list args )
1788 case ACCESS_CAN_SEEK:
1789 case ACCESS_CAN_FASTSEEK:
1790 case ACCESS_CAN_PAUSE:
1791 case ACCESS_CAN_CONTROL_PACE:
1792 pb_bool = (bool*)va_arg( args, bool* );
1797 case ACCESS_GET_MTU:
1798 pi_int = (int*)va_arg( args, int * );
1802 case ACCESS_GET_PTS_DELAY:
1803 pi_64 = (int64_t*)va_arg( args, int64_t * );
1804 *pi_64 = (int64_t)var_GetInteger( p_access, "dshow-caching" ) * 1000;
1808 case ACCESS_SET_PAUSE_STATE:
1809 case ACCESS_GET_TITLE_INFO:
1810 case ACCESS_SET_TITLE:
1811 case ACCESS_SET_SEEKPOINT:
1812 case ACCESS_SET_PRIVATE_ID_STATE:
1813 return VLC_EGENERIC;
1816 msg_Warn( p_access, "unimplemented query in control" );
1817 return VLC_EGENERIC;
1823 /****************************************************************************
1825 ****************************************************************************/
1826 static int DemuxControl( demux_t *p_demux, int i_query, va_list args )
1833 /* Special for access_demux */
1834 case DEMUX_CAN_PAUSE:
1835 case DEMUX_CAN_SEEK:
1836 case DEMUX_SET_PAUSE_STATE:
1837 case DEMUX_CAN_CONTROL_PACE:
1838 pb = (bool*)va_arg( args, bool * );
1842 case DEMUX_GET_PTS_DELAY:
1843 pi64 = (int64_t*)va_arg( args, int64_t * );
1844 *pi64 = (int64_t)var_GetInteger( p_demux, "dshow-caching" ) * 1000;
1847 case DEMUX_GET_TIME:
1848 pi64 = (int64_t*)va_arg( args, int64_t * );
1852 /* TODO implement others */
1854 return VLC_EGENERIC;
1857 return VLC_EGENERIC;
1860 /*****************************************************************************
1861 * config variable callback
1862 *****************************************************************************/
1863 static int FindDevicesCallback( vlc_object_t *p_this, char const *psz_name,
1864 vlc_value_t newval, vlc_value_t oldval, void * )
1866 module_config_t *p_item;
1867 bool b_audio = false;
1870 p_item = config_FindConfig( p_this, psz_name );
1871 if( !p_item ) return VLC_SUCCESS;
1873 if( !strcmp( psz_name, "dshow-adev" ) ) b_audio = true;
1875 /* Clear-up the current list */
1876 if( p_item->i_list )
1878 /* Keep the 2 first entries */
1879 for( i = 2; i < p_item->i_list; i++ )
1881 free( const_cast<char *>(p_item->ppsz_list[i]) );
1882 free( const_cast<char *>(p_item->ppsz_list_text[i]) );
1884 /* TODO: Remove when no more needed */
1885 p_item->ppsz_list[i] = NULL;
1886 p_item->ppsz_list_text[i] = NULL;
1890 /* Find list of devices */
1891 list<string> list_devices;
1893 /* Initialize OLE/COM */
1896 FindCaptureDevice( p_this, NULL, &list_devices, b_audio );
1898 /* Uninitialize OLE/COM */
1901 if( !list_devices.size() ) return VLC_SUCCESS;
1904 (char **)realloc( p_item->ppsz_list,
1905 (list_devices.size()+3) * sizeof(char *) );
1906 p_item->ppsz_list_text =
1907 (char **)realloc( p_item->ppsz_list_text,
1908 (list_devices.size()+3) * sizeof(char *) );
1910 list<string>::iterator iter;
1911 for( iter = list_devices.begin(), i = 2; iter != list_devices.end();
1914 p_item->ppsz_list[i] = strdup( iter->c_str() );
1915 p_item->ppsz_list_text[i] = NULL;
1918 p_item->ppsz_list[i] = NULL;
1919 p_item->ppsz_list_text[i] = NULL;
1921 /* Signal change to the interface */
1922 p_item->b_dirty = true;
1927 static int ConfigDevicesCallback( vlc_object_t *p_this, char const *psz_name,
1928 vlc_value_t newval, vlc_value_t oldval, void * )
1930 module_config_t *p_item;
1931 bool b_audio = false;
1933 /* Initialize OLE/COM */
1936 p_item = config_FindConfig( p_this, psz_name );
1937 if( !p_item ) return VLC_SUCCESS;
1939 if( !strcmp( psz_name, "dshow-adev" ) ) b_audio = true;
1943 if( newval.psz_string && *newval.psz_string )
1945 devicename = newval.psz_string;
1949 /* If no device name was specified, pick the 1st one */
1950 list<string> list_devices;
1952 /* Enumerate devices */
1953 FindCaptureDevice( p_this, NULL, &list_devices, b_audio );
1954 if( !list_devices.size() ) return VLC_EGENERIC;
1955 devicename = *list_devices.begin();
1958 IBaseFilter *p_device_filter =
1959 FindCaptureDevice( p_this, &devicename, NULL, b_audio );
1960 if( p_device_filter )
1962 ShowPropertyPage( p_device_filter );
1963 p_device_filter->Release();
1967 /* Uninitialize OLE/COM */
1970 msg_Err( p_this, "didn't find device: %s", devicename.c_str() );
1971 return VLC_EGENERIC;
1974 /* Uninitialize OLE/COM */
1980 /*****************************************************************************
1982 *****************************************************************************/
1983 static void ShowPropertyPage( IUnknown *obj )
1985 ISpecifyPropertyPages *p_spec;
1988 HRESULT hr = obj->QueryInterface( IID_ISpecifyPropertyPages,
1990 if( FAILED(hr) ) return;
1992 if( SUCCEEDED(p_spec->GetPages( &cauuid )) )
1994 if( cauuid.cElems > 0 )
1996 HWND hwnd_desktop = ::GetDesktopWindow();
1998 OleCreatePropertyFrame( hwnd_desktop, 30, 30, NULL, 1, &obj,
1999 cauuid.cElems, cauuid.pElems, 0, 0, NULL );
2001 CoTaskMemFree( cauuid.pElems );
2007 static void ShowDeviceProperties( vlc_object_t *p_this,
2008 ICaptureGraphBuilder2 *p_graph,
2009 IBaseFilter *p_device_filter,
2013 msg_Dbg( p_this, "configuring Device Properties" );
2016 * Video or audio capture filter page
2018 ShowPropertyPage( p_device_filter );
2023 if( p_graph && b_audio )
2025 IAMStreamConfig *p_SC;
2027 msg_Dbg( p_this, "showing WDM Audio Configuration Pages" );
2029 hr = p_graph->FindInterface( &PIN_CATEGORY_CAPTURE,
2030 &MEDIATYPE_Audio, p_device_filter,
2031 IID_IAMStreamConfig, (void **)&p_SC );
2034 ShowPropertyPage(p_SC);
2042 HRESULT hr = p_graph->FindInterface( &PIN_CATEGORY_CAPTURE,
2043 &MEDIATYPE_Audio, p_device_filter,
2044 IID_IAMTVAudio, (void **)&p_TVA );
2047 ShowPropertyPage(p_TVA);
2055 if( p_graph && !b_audio )
2057 IAMStreamConfig *p_SC;
2059 msg_Dbg( p_this, "showing WDM Video Configuration Pages" );
2061 hr = p_graph->FindInterface( &PIN_CATEGORY_CAPTURE,
2062 &MEDIATYPE_Interleaved, p_device_filter,
2063 IID_IAMStreamConfig, (void **)&p_SC );
2066 hr = p_graph->FindInterface( &PIN_CATEGORY_CAPTURE,
2067 &MEDIATYPE_Video, p_device_filter,
2068 IID_IAMStreamConfig, (void **)&p_SC );
2073 hr = p_graph->FindInterface( &PIN_CATEGORY_CAPTURE,
2074 &MEDIATYPE_Stream, p_device_filter,
2075 IID_IAMStreamConfig, (void **)&p_SC );
2080 ShowPropertyPage(p_SC);
2086 static void ShowTunerProperties( vlc_object_t *p_this,
2087 ICaptureGraphBuilder2 *p_graph,
2088 IBaseFilter *p_device_filter,
2092 msg_Dbg( p_this, "configuring Tuner Properties" );
2094 if( !p_graph || b_audio ) return;
2097 hr = p_graph->FindInterface( &PIN_CATEGORY_CAPTURE,
2098 &MEDIATYPE_Interleaved, p_device_filter,
2099 IID_IAMTVTuner, (void **)&p_TV );
2102 hr = p_graph->FindInterface( &PIN_CATEGORY_CAPTURE,
2103 &MEDIATYPE_Video, p_device_filter,
2104 IID_IAMTVTuner, (void **)&p_TV );
2109 hr = p_graph->FindInterface( &PIN_CATEGORY_CAPTURE,
2110 &MEDIATYPE_Stream, p_device_filter,
2111 IID_IAMTVTuner, (void **)&p_TV );
2116 ShowPropertyPage(p_TV);
2121 static void ConfigTuner( vlc_object_t *p_this, ICaptureGraphBuilder2 *p_graph,
2122 IBaseFilter *p_device_filter )
2124 int i_channel, i_country, i_input, i_amtuner_mode;
2129 if( !p_graph ) return;
2131 i_channel = var_GetInteger( p_this, "dshow-tuner-channel" );
2132 i_country = var_GetInteger( p_this, "dshow-tuner-country" );
2133 i_input = var_GetInteger( p_this, "dshow-tuner-input" );
2134 i_amtuner_mode = var_GetInteger( p_this, "dshow-amtuner-mode" );
2136 if( !i_channel && !i_country && !i_input ) return; /* Nothing to do */
2138 msg_Dbg( p_this, "tuner config: channel %i, country %i, input type %i",
2139 i_channel, i_country, i_input );
2141 hr = p_graph->FindInterface( &PIN_CATEGORY_CAPTURE, &MEDIATYPE_Interleaved,
2142 p_device_filter, IID_IAMTVTuner,
2146 hr = p_graph->FindInterface( &PIN_CATEGORY_CAPTURE, &MEDIATYPE_Video,
2147 p_device_filter, IID_IAMTVTuner,
2153 hr = p_graph->FindInterface( &PIN_CATEGORY_CAPTURE, &MEDIATYPE_Stream,
2154 p_device_filter, IID_IAMTVTuner,
2160 msg_Dbg( p_this, "couldn't find tuner interface" );
2164 hr = p_TV->GetAvailableModes( &l_modes );
2165 if( SUCCEEDED(hr) && (l_modes & i_amtuner_mode) )
2167 hr = p_TV->put_Mode( (AMTunerModeType)i_amtuner_mode );
2170 if( i_input == 1 ) p_TV->put_InputType( 0, TunerInputCable );
2171 else if( i_input == 2 ) p_TV->put_InputType( 0, TunerInputAntenna );
2173 p_TV->put_CountryCode( i_country );
2174 p_TV->put_Channel( i_channel, AMTUNER_SUBCHAN_NO_TUNE,
2175 AMTUNER_SUBCHAN_NO_TUNE );