Main Page | Modules | Class Hierarchy | Class List | Directories | File List | Class Members | File Members | Related Pages

dshow.cpp

00001 /*****************************************************************************
00002  * dshow.cpp : DirectShow access module for vlc
00003  *****************************************************************************
00004  * Copyright (C) 2002, 2003 the VideoLAN team
00005  * $Id: dshow.cpp 13470 2005-11-30 15:15:25Z damienf $
00006  *
00007  * Author: Gildas Bazin <[email protected]>
00008  *
00009  * This program is free software; you can redistribute it and/or modify
00010  * it under the terms of the GNU General Public License as published by
00011  * the Free Software Foundation; either version 2 of the License, or
00012  * (at your option) any later version.
00013  *
00014  * This program is distributed in the hope that it will be useful,
00015  * but WITHOUT ANY WARRANTY; without even the implied warranty of
00016  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
00017  * GNU General Public License for more details.
00018  *
00019  * You should have received a copy of the GNU General Public License
00020  * along with this program; if not, write to the Free Software
00021  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111, USA.
00022  *****************************************************************************/
00023 
00024 /*****************************************************************************
00025  * Preamble
00026  *****************************************************************************/
00027 #include <stdlib.h>
00028 #include <stdio.h>
00029 #include <string.h>
00030 
00031 #include <vlc/vlc.h>
00032 #include <vlc/input.h>
00033 #include <vlc/vout.h>
00034 
00035 #include "common.h"
00036 #include "filter.h"
00037 
00038 /*****************************************************************************
00039  * Access: local prototypes
00040  *****************************************************************************/
00041 static block_t *ReadCompressed( access_t * );
00042 static int AccessControl ( access_t *, int, va_list );
00043 
00044 static int Demux       ( demux_t * );
00045 static int DemuxControl( demux_t *, int, va_list );
00046 
00047 static int OpenDevice( vlc_object_t *, access_sys_t *, string, vlc_bool_t );
00048 static IBaseFilter *FindCaptureDevice( vlc_object_t *, string *,
00049                                        list<string> *, vlc_bool_t );
00050 static size_t EnumDeviceCaps( vlc_object_t *, IBaseFilter *,
00051                               int, int, int, int, int, int,
00052                               AM_MEDIA_TYPE *mt, size_t );
00053 static bool ConnectFilters( vlc_object_t *, access_sys_t *,
00054                             IBaseFilter *, CaptureFilter * );
00055 static int FindDevicesCallback( vlc_object_t *, char const *,
00056                                 vlc_value_t, vlc_value_t, void * );
00057 static int ConfigDevicesCallback( vlc_object_t *, char const *,
00058                                   vlc_value_t, vlc_value_t, void * );
00059 
00060 static void ShowPropertyPage( IUnknown * );
00061 static void ShowDeviceProperties( vlc_object_t *, ICaptureGraphBuilder2 *, 
00062                                   IBaseFilter *, vlc_bool_t );
00063 static void ShowTunerProperties( vlc_object_t *, ICaptureGraphBuilder2 *, 
00064                                  IBaseFilter *, vlc_bool_t );
00065 static void ConfigTuner( vlc_object_t *, ICaptureGraphBuilder2 *,
00066                          IBaseFilter * );
00067 
00068 /*****************************************************************************
00069  * Module descriptor
00070  *****************************************************************************/
00071 static char *ppsz_vdev[] = { "", "none" };
00072 static char *ppsz_vdev_text[] = { N_("Default"), N_("None") };
00073 static char *ppsz_adev[] = { "", "none" };
00074 static char *ppsz_adev_text[] = { N_("Default"), N_("None") };
00075 static int  pi_tuner_input[] = { 0, 1, 2 };
00076 static char *ppsz_tuner_input_text[] =
00077     {N_("Default"), N_("Cable"), N_("Antenna")};
00078 
00079 #define CACHING_TEXT N_("Caching value in ms")
00080 #define CACHING_LONGTEXT N_( \
00081     "Allows you to modify the default caching value for DirectShow streams. " \
00082     "This value should be set in milliseconds units." )
00083 #define VDEV_TEXT N_("Video device name")
00084 #define VDEV_LONGTEXT N_( \
00085     "You can specify the name of the video device that will be used by the " \
00086     "DirectShow plugin. If you don't specify anything, the default device " \
00087     "will be used.")
00088 #define ADEV_TEXT N_("Audio device name")
00089 #define ADEV_LONGTEXT N_( \
00090     "You can specify the name of the audio device that will be used by the " \
00091     "DirectShow plugin. If you don't specify anything, the default device " \
00092     "will be used.")
00093 #define SIZE_TEXT N_("Video size")
00094 #define SIZE_LONGTEXT N_( \
00095     "You can specify the size of the video that will be displayed by the " \
00096     "DirectShow plugin. If you don't specify anything the default size for " \
00097     "your device will be used.")
00098 #define CHROMA_TEXT N_("Video input chroma format")
00099 #define CHROMA_LONGTEXT N_( \
00100     "Force the DirectShow video input to use a specific chroma format " \
00101     "(eg. I420 (default), RV24, etc.)")
00102 #define FPS_TEXT N_("Video input frame rate")
00103 #define FPS_LONGTEXT N_( \
00104     "Force the DirectShow video input to use a specific frame rate" \
00105     "(eg. 0 means default, 25, 29.97, 50, 59.94, etc.)")
00106 #define CONFIG_TEXT N_("Device properties")
00107 #define CONFIG_LONGTEXT N_( \
00108     "Show the properties dialog of the selected device before starting the " \
00109     "stream.")
00110 #define TUNER_TEXT N_("Tuner properties")
00111 #define TUNER_LONGTEXT N_( \
00112     "Show the tuner properties [channel selection] page." )
00113 #define CHANNEL_TEXT N_("Tuner TV Channel")
00114 #define CHANNEL_LONGTEXT N_( \
00115     "Allows you to set the TV channel the tuner will set to " \
00116     "(0 means default)." )
00117 #define COUNTRY_TEXT N_("Tuner country code")
00118 #define COUNTRY_LONGTEXT N_( \
00119     "Allows you to set the tuner country code that establishes the current " \
00120     "channel-to-frequency mapping (0 means default)." )
00121 #define TUNER_INPUT_TEXT N_("Tuner input type")
00122 #define TUNER_INPUT_LONGTEXT N_( \
00123     "Allows you to select the tuner input type (Cable/Antenna)." )
00124 
00125 static int  CommonOpen ( vlc_object_t *, access_sys_t *, vlc_bool_t );
00126 static void CommonClose( vlc_object_t *, access_sys_t * );
00127 
00128 static int  AccessOpen ( vlc_object_t * );
00129 static void AccessClose( vlc_object_t * );
00130 
00131 static int  DemuxOpen  ( vlc_object_t * );
00132 static void DemuxClose ( vlc_object_t * );
00133 
00134 vlc_module_begin();
00135     set_shortname( _("DirectShow") );
00136     set_description( _("DirectShow input") );
00137     set_category( CAT_INPUT );
00138     set_subcategory( SUBCAT_INPUT_ACCESS );
00139     add_integer( "dshow-caching", (mtime_t)(0.2*CLOCK_FREQ) / 1000, NULL,
00140                  CACHING_TEXT, CACHING_LONGTEXT, VLC_TRUE );
00141 
00142     add_string( "dshow-vdev", NULL, NULL, VDEV_TEXT, VDEV_LONGTEXT, VLC_FALSE);
00143         change_string_list( ppsz_vdev, ppsz_vdev_text, FindDevicesCallback );
00144         change_action_add( FindDevicesCallback, N_("Refresh list") );
00145         change_action_add( ConfigDevicesCallback, N_("Configure") );
00146 
00147     add_string( "dshow-adev", NULL, NULL, ADEV_TEXT, ADEV_LONGTEXT, VLC_FALSE);
00148         change_string_list( ppsz_adev, ppsz_adev_text, FindDevicesCallback );
00149         change_action_add( FindDevicesCallback, N_("Refresh list") );
00150         change_action_add( ConfigDevicesCallback, N_("Configure") );
00151 
00152     add_string( "dshow-size", NULL, NULL, SIZE_TEXT, SIZE_LONGTEXT, VLC_FALSE);
00153 
00154     add_string( "dshow-chroma", NULL, NULL, CHROMA_TEXT, CHROMA_LONGTEXT,
00155                 VLC_TRUE );
00156 
00157     add_float( "dshow-fps", 0.0f, NULL, FPS_TEXT, FPS_LONGTEXT,
00158                 VLC_TRUE );
00159 
00160     add_bool( "dshow-config", VLC_FALSE, NULL, CONFIG_TEXT, CONFIG_LONGTEXT,
00161               VLC_TRUE );
00162 
00163     add_bool( "dshow-tuner", VLC_FALSE, NULL, TUNER_TEXT, TUNER_LONGTEXT,
00164               VLC_TRUE );
00165 
00166     add_integer( "dshow-tuner-channel", 0, NULL, CHANNEL_TEXT,
00167                  CHANNEL_LONGTEXT, VLC_TRUE );
00168 
00169     add_integer( "dshow-tuner-country", 0, NULL, COUNTRY_TEXT,
00170                  COUNTRY_LONGTEXT, VLC_TRUE );
00171 
00172     add_integer( "dshow-tuner-input", 0, NULL, TUNER_INPUT_TEXT,
00173                  TUNER_INPUT_LONGTEXT, VLC_TRUE );
00174         change_integer_list( pi_tuner_input, ppsz_tuner_input_text, 0 );
00175 
00176     add_shortcut( "dshow" );
00177     set_capability( "access_demux", 0 );
00178     set_callbacks( DemuxOpen, DemuxClose );
00179 
00180     add_submodule();
00181     set_description( _("DirectShow input") );
00182     add_shortcut( "dshow" );
00183     set_capability( "access2", 0 );
00184     set_callbacks( AccessOpen, AccessClose );
00185 
00186 vlc_module_end();
00187 
00188 /*****************************************************************************
00189  * DirectShow elementary stream descriptor
00190  *****************************************************************************/
00191 typedef struct dshow_stream_t
00192 {
00193     string          devicename;
00194     IBaseFilter     *p_device_filter;
00195     CaptureFilter   *p_capture_filter;
00196     AM_MEDIA_TYPE   mt;
00197 
00198     union
00199     {
00200       VIDEOINFOHEADER video;
00201       WAVEFORMATEX    audio;
00202 
00203     } header;
00204 
00205     int             i_fourcc;
00206     es_out_id_t     *p_es;
00207 
00208     vlc_bool_t      b_pts;
00209 
00210 } dshow_stream_t;
00211 
00212 /*****************************************************************************
00213  * DirectShow utility functions
00214  *****************************************************************************/
00215 static void CreateDirectShowGraph( access_sys_t *p_sys )
00216 {
00217     p_sys->i_crossbar_route_depth = 0;
00218 
00219     /* Create directshow filter graph */
00220     if( SUCCEEDED( CoCreateInstance( CLSID_FilterGraph, 0, CLSCTX_INPROC,
00221                        (REFIID)IID_IFilterGraph, (void **)&p_sys->p_graph) ) )
00222     {
00223         /* Create directshow capture graph builder if available */
00224         if( SUCCEEDED( CoCreateInstance( CLSID_CaptureGraphBuilder2, 0,
00225                          CLSCTX_INPROC, (REFIID)IID_ICaptureGraphBuilder2,
00226                          (void **)&p_sys->p_capture_graph_builder2 ) ) )
00227         {
00228             p_sys->p_capture_graph_builder2->
00229                 SetFiltergraph((IGraphBuilder *)p_sys->p_graph);
00230         }
00231 
00232         p_sys->p_graph->QueryInterface( IID_IMediaControl,
00233                                         (void **)&p_sys->p_control );
00234     }
00235 }
00236 
00237 static void DeleteDirectShowGraph( access_sys_t *p_sys )
00238 {
00239     DeleteCrossbarRoutes( p_sys );
00240 
00241     /* Remove filters from graph */
00242     for( int i = 0; i < p_sys->i_streams; i++ )
00243     {
00244         p_sys->p_graph->RemoveFilter( p_sys->pp_streams[i]->p_capture_filter );
00245         p_sys->p_graph->RemoveFilter( p_sys->pp_streams[i]->p_device_filter );
00246         p_sys->pp_streams[i]->p_capture_filter->Release();
00247         p_sys->pp_streams[i]->p_device_filter->Release();
00248     }
00249 
00250     /* Release directshow objects */
00251     if( p_sys->p_control )
00252     {
00253         p_sys->p_control->Release();
00254         p_sys->p_control = NULL;
00255     }
00256     if( p_sys->p_capture_graph_builder2 )
00257     {
00258         p_sys->p_capture_graph_builder2->Release();
00259         p_sys->p_capture_graph_builder2 = NULL;
00260     }
00261 
00262     if( p_sys->p_graph )
00263     {
00264         p_sys->p_graph->Release();
00265         p_sys->p_graph = NULL;
00266     }
00267 }
00268 
00269 /*****************************************************************************
00270  * CommonOpen: open direct show device
00271  *****************************************************************************/
00272 static int CommonOpen( vlc_object_t *p_this, access_sys_t *p_sys,
00273                        vlc_bool_t b_access_demux )
00274 {
00275     vlc_value_t  val;
00276     int i;
00277 
00278     /* Get/parse options and open device(s) */
00279     string vdevname, adevname;
00280     int i_width = 0, i_height = 0, i_chroma = 0;
00281     vlc_bool_t b_audio = VLC_TRUE;
00282 
00283     var_Create( p_this, "dshow-config", VLC_VAR_BOOL | VLC_VAR_DOINHERIT );
00284     var_Create( p_this, "dshow-tuner", VLC_VAR_BOOL | VLC_VAR_DOINHERIT );
00285 
00286     var_Create( p_this, "dshow-vdev", VLC_VAR_STRING | VLC_VAR_DOINHERIT );
00287     var_Get( p_this, "dshow-vdev", &val );
00288     if( val.psz_string ) vdevname = string( val.psz_string );
00289     if( val.psz_string ) free( val.psz_string );
00290 
00291     var_Create( p_this, "dshow-adev", VLC_VAR_STRING | VLC_VAR_DOINHERIT );
00292     var_Get( p_this, "dshow-adev", &val );
00293     if( val.psz_string ) adevname = string( val.psz_string );
00294     if( val.psz_string ) free( val.psz_string );
00295 
00296     static struct {char *psz_size; int  i_width; int  i_height;} size_table[] =
00297     { { "subqcif", 128, 96 }, { "qsif", 160, 120 }, { "qcif", 176, 144 },
00298       { "sif", 320, 240 }, { "cif", 352, 288 }, { "cif", 640, 480 },
00299       { 0, 0, 0 },
00300     };
00301 
00302     var_Create( p_this, "dshow-size", VLC_VAR_STRING | VLC_VAR_DOINHERIT );
00303     var_Get( p_this, "dshow-size", &val );
00304     if( val.psz_string && *val.psz_string )
00305     {
00306         for( i = 0; size_table[i].psz_size; i++ )
00307         {
00308             if( !strcmp( val.psz_string, size_table[i].psz_size ) )
00309             {
00310                 i_width = size_table[i].i_width;
00311                 i_height = size_table[i].i_height;
00312                 break;
00313             }
00314         }
00315         if( !size_table[i].psz_size ) /* Try to parse "WidthxHeight" */
00316         {
00317             char *psz_parser;
00318             i_width = strtol( val.psz_string, &psz_parser, 0 );
00319             if( *psz_parser == 'x' || *psz_parser == 'X')
00320             {
00321                 i_height = strtol( psz_parser + 1, &psz_parser, 0 );
00322             }
00323             msg_Dbg( p_this, "Width x Height %dx%d", i_width, i_height );
00324         }
00325     }
00326     if( val.psz_string ) free( val.psz_string );
00327 
00328     var_Create( p_this, "dshow-chroma", VLC_VAR_STRING | VLC_VAR_DOINHERIT );
00329     var_Get( p_this, "dshow-chroma", &val );
00330     if( val.psz_string && strlen( val.psz_string ) >= 4 )
00331     {
00332         i_chroma = VLC_FOURCC( val.psz_string[0], val.psz_string[1],
00333                                val.psz_string[2], val.psz_string[3] );
00334     }
00335     if( val.psz_string ) free( val.psz_string );
00336 
00337     var_Create( p_this, "dshow-fps", VLC_VAR_FLOAT | VLC_VAR_DOINHERIT );
00338     var_Create( p_this, "dshow-tuner-channel",
00339                 VLC_VAR_INTEGER | VLC_VAR_DOINHERIT );
00340     var_Create( p_this, "dshow-tuner-country",
00341                 VLC_VAR_INTEGER | VLC_VAR_DOINHERIT );
00342     var_Create( p_this, "dshow-tuner-input",
00343                 VLC_VAR_INTEGER | VLC_VAR_DOINHERIT );
00344 
00345     var_Create( p_this, "dshow-caching", VLC_VAR_INTEGER | VLC_VAR_DOINHERIT );
00346 
00347     /* Initialize OLE/COM */
00348     CoInitialize( 0 );
00349 
00350     /* Initialize some data */
00351     p_sys->i_streams = 0;
00352     p_sys->pp_streams = 0;
00353     p_sys->i_width = i_width;
00354     p_sys->i_height = i_height;
00355     p_sys->i_chroma = i_chroma;
00356 
00357     p_sys->p_graph = NULL;
00358     p_sys->p_capture_graph_builder2 = NULL;
00359     p_sys->p_control = NULL;
00360 
00361     vlc_mutex_init( p_this, &p_sys->lock );
00362     vlc_cond_init( p_this, &p_sys->wait );
00363 
00364     /* Build directshow graph */
00365     CreateDirectShowGraph( p_sys );
00366 
00367     if( OpenDevice( p_this, p_sys, vdevname, 0 ) != VLC_SUCCESS )
00368     {
00369         msg_Err( p_this, "can't open video");
00370     }
00371     else
00372     {
00373         /* Check if we can handle the demuxing ourselves or need to spawn
00374          * a demuxer module */
00375         dshow_stream_t *p_stream = p_sys->pp_streams[p_sys->i_streams-1];
00376 
00377         if( p_stream->mt.majortype == MEDIATYPE_Video )
00378         {
00379             if( /* Raw DV stream */
00380                 p_stream->i_fourcc == VLC_FOURCC('d','v','s','l') ||
00381                 p_stream->i_fourcc == VLC_FOURCC('d','v','s','d') ||
00382                 p_stream->i_fourcc == VLC_FOURCC('d','v','h','d') ||
00383                 /* Raw MPEG video stream */
00384                 p_stream->i_fourcc == VLC_FOURCC('m','p','2','v') )
00385             {
00386                 b_audio = VLC_FALSE;
00387 
00388                 if( b_access_demux )
00389                 {
00390                     /* Let the access (only) take care of that */
00391                     return VLC_EGENERIC;
00392                 }
00393             }
00394         }
00395 
00396         if( p_stream->mt.majortype == MEDIATYPE_Stream )
00397         {
00398             b_audio = VLC_FALSE;
00399 
00400             if( b_access_demux )
00401             {
00402                 /* Let the access (only) take care of that */
00403                 return VLC_EGENERIC;
00404             }
00405 
00406             var_Get( p_this, "dshow-tuner", &val );
00407             if( val.b_bool )
00408             {
00409                 /* FIXME: we do MEDIATYPE_Stream here so we don't do
00410                  * it twice. */
00411                 ShowTunerProperties( p_this, p_sys->p_capture_graph_builder2,
00412                                      p_stream->p_device_filter, 0 );
00413             }
00414         }
00415     }
00416 
00417     if( b_audio && OpenDevice( p_this, p_sys, adevname, 1 ) != VLC_SUCCESS )
00418     {
00419         msg_Err( p_this, "can't open audio");
00420     }
00421 
00422     for( i = p_sys->i_crossbar_route_depth-1; i >= 0 ; --i )
00423     {
00424         IAMCrossbar *pXbar = p_sys->crossbar_routes[i].pXbar;
00425         LONG VideoInputIndex = p_sys->crossbar_routes[i].VideoInputIndex;
00426         LONG VideoOutputIndex = p_sys->crossbar_routes[i].VideoOutputIndex;
00427         LONG AudioInputIndex = p_sys->crossbar_routes[i].AudioInputIndex;
00428         LONG AudioOutputIndex = p_sys->crossbar_routes[i].AudioOutputIndex;
00429 
00430         if( SUCCEEDED(pXbar->Route(VideoOutputIndex, VideoInputIndex)) )
00431         {
00432             msg_Dbg( p_this, "Crossbar at depth %d, Routed video "
00433                      "ouput %ld to video input %ld", i, VideoOutputIndex,
00434                      VideoInputIndex );
00435 
00436             if( AudioOutputIndex != -1 && AudioInputIndex != -1 )
00437             {
00438                 if( SUCCEEDED( pXbar->Route(AudioOutputIndex,
00439                                             AudioInputIndex)) )
00440                 {
00441                     msg_Dbg(p_this, "Crossbar at depth %d, Routed audio "
00442                             "ouput %ld to audio input %ld", i,
00443                             AudioOutputIndex, AudioInputIndex );
00444                 }
00445             }
00446         }
00447     }
00448 
00449     /*
00450     ** Show properties pages from other filters in graph
00451     */
00452     var_Get( p_this, "dshow-config", &val );
00453     if( val.b_bool )
00454     {
00455         for( i = p_sys->i_crossbar_route_depth-1; i >= 0 ; --i )
00456         {
00457             IAMCrossbar *pXbar = p_sys->crossbar_routes[i].pXbar;
00458             IBaseFilter *p_XF;
00459 
00460             if( SUCCEEDED( pXbar->QueryInterface( IID_IBaseFilter,
00461                                                   (void **)&p_XF ) ) )
00462             {
00463                 ShowPropertyPage( p_XF );
00464                 p_XF->Release();
00465             }
00466         }
00467     }
00468 
00469     /* Initialize some data */
00470     p_sys->i_current_stream = 0;
00471 
00472     if( !p_sys->i_streams ) return VLC_EGENERIC;
00473 
00474     return VLC_SUCCESS;
00475 }
00476 
00477 /*****************************************************************************
00478  * DemuxOpen: open direct show device as an access_demux module
00479  *****************************************************************************/
00480 static int DemuxOpen( vlc_object_t *p_this )
00481 {
00482     demux_t      *p_demux = (demux_t *)p_this;
00483     access_sys_t *p_sys;
00484     int i;
00485 
00486     p_sys = (access_sys_t *)malloc( sizeof( access_sys_t ) );
00487     memset( p_sys, 0, sizeof( access_sys_t ) );
00488     p_demux->p_sys = (demux_sys_t *)p_sys;
00489 
00490     if( CommonOpen( p_this, p_sys, VLC_TRUE ) != VLC_SUCCESS )
00491     {
00492         CommonClose( p_this, p_sys );
00493         return VLC_EGENERIC;
00494     }
00495 
00496     /* Everything is ready. Let's rock baby */
00497     msg_Dbg( p_this, "Playing...");
00498     p_sys->p_control->Run();
00499 
00500     p_demux->pf_demux   = Demux;
00501     p_demux->pf_control = DemuxControl;
00502     p_demux->info.i_update = 0;
00503     p_demux->info.i_title = 0;
00504     p_demux->info.i_seekpoint = 0;
00505 
00506     for( i = 0; i < p_sys->i_streams; i++ )
00507     {
00508         dshow_stream_t *p_stream = p_sys->pp_streams[i];
00509         es_format_t fmt;
00510 
00511         if( p_stream->mt.majortype == MEDIATYPE_Video )
00512         {
00513             es_format_Init( &fmt, VIDEO_ES, p_stream->i_fourcc );
00514 
00515             fmt.video.i_width  = p_stream->header.video.bmiHeader.biWidth;
00516             fmt.video.i_height = p_stream->header.video.bmiHeader.biHeight;
00517             fmt.video.i_aspect = 4 * VOUT_ASPECT_FACTOR / 3;
00518 
00519             if( !p_stream->header.video.bmiHeader.biCompression )
00520             {
00521                 /* RGB DIB are coded from bottom to top */
00522                 fmt.video.i_height = (unsigned int)(-(int)fmt.video.i_height);
00523             }
00524 
00525             /* Setup rgb mask for RGB formats */
00526             if( p_stream->i_fourcc == VLC_FOURCC('R','V','2','4') )
00527             {
00528                 /* This is in BGR format */
00529                 fmt.video.i_bmask = 0x00ff0000;
00530                 fmt.video.i_gmask = 0x0000ff00;
00531                 fmt.video.i_rmask = 0x000000ff;
00532             }
00533 
00534             if( p_stream->header.video.AvgTimePerFrame )
00535             {
00536                 fmt.video.i_frame_rate = 10000000;
00537                 fmt.video.i_frame_rate_base =
00538                     p_stream->header.video.AvgTimePerFrame;
00539             }
00540         }
00541         else if( p_stream->mt.majortype == MEDIATYPE_Audio )
00542         {
00543             es_format_Init( &fmt, AUDIO_ES, p_stream->i_fourcc );
00544 
00545             fmt.audio.i_channels = p_stream->header.audio.nChannels;
00546             fmt.audio.i_rate = p_stream->header.audio.nSamplesPerSec;
00547             fmt.audio.i_bitspersample = p_stream->header.audio.wBitsPerSample;
00548             fmt.audio.i_blockalign = fmt.audio.i_channels *
00549                 fmt.audio.i_bitspersample / 8;
00550             fmt.i_bitrate = fmt.audio.i_channels * fmt.audio.i_rate *
00551                 fmt.audio.i_bitspersample;
00552         }
00553 
00554         p_stream->p_es = es_out_Add( p_demux->out, &fmt );
00555     }
00556 
00557     return VLC_SUCCESS;
00558 }
00559 
00560 /*****************************************************************************
00561  * AccessOpen: open direct show device as an access module
00562  *****************************************************************************/
00563 static int AccessOpen( vlc_object_t *p_this )
00564 {
00565     access_t     *p_access = (access_t*)p_this;
00566     access_sys_t *p_sys;
00567 
00568     p_access->p_sys = p_sys = (access_sys_t *)malloc( sizeof( access_sys_t ) );
00569     memset( p_sys, 0, sizeof( access_sys_t ) );
00570 
00571     if( CommonOpen( p_this, p_sys, VLC_FALSE ) != VLC_SUCCESS )
00572     {
00573         CommonClose( p_this, p_sys );
00574         return VLC_EGENERIC;
00575     }
00576 
00577     dshow_stream_t *p_stream = p_sys->pp_streams[0];
00578 
00579     /* Check if we need to force demuxers */
00580     if( !p_access->psz_demux || !*p_access->psz_demux )
00581     {
00582         if( p_stream->i_fourcc == VLC_FOURCC('d','v','s','l') ||
00583             p_stream->i_fourcc == VLC_FOURCC('d','v','s','d') ||
00584             p_stream->i_fourcc == VLC_FOURCC('d','v','h','d') )
00585         {
00586             p_access->psz_demux = strdup( "rawdv" );
00587         }
00588         else if( p_stream->i_fourcc == VLC_FOURCC('m','p','2','v') )
00589         {
00590             p_access->psz_demux = "mpgv";
00591         }
00592     }
00593 
00594     /* Setup Access */
00595     p_access->pf_read = NULL;
00596     p_access->pf_block = ReadCompressed;
00597     p_access->pf_control = AccessControl;
00598     p_access->pf_seek = NULL;
00599     p_access->info.i_update = 0;
00600     p_access->info.i_size = 0;
00601     p_access->info.i_pos = 0;
00602     p_access->info.b_eof = VLC_FALSE;
00603     p_access->info.i_title = 0;
00604     p_access->info.i_seekpoint = 0;
00605     p_access->p_sys = p_sys;
00606 
00607     /* Everything is ready. Let's rock baby */
00608     msg_Dbg( p_this, "Playing...");
00609     p_sys->p_control->Run();
00610 
00611     return VLC_SUCCESS;
00612 }
00613 
00614 /*****************************************************************************
00615  * CommonClose: close device
00616  *****************************************************************************/
00617 static void CommonClose( vlc_object_t *p_this, access_sys_t *p_sys )
00618 {
00619     msg_Dbg( p_this, "Releasing DirectShow");
00620 
00621     DeleteDirectShowGraph( p_sys );
00622 
00623     /* Uninitialize OLE/COM */
00624     CoUninitialize();
00625 
00626     for( int i = 0; i < p_sys->i_streams; i++ ) delete p_sys->pp_streams[i];
00627     if( p_sys->i_streams ) free( p_sys->pp_streams );
00628 
00629     vlc_mutex_destroy( &p_sys->lock );
00630     vlc_cond_destroy( &p_sys->wait );
00631 
00632     free( p_sys );
00633 }
00634 
00635 /*****************************************************************************
00636  * AccessClose: close device
00637  *****************************************************************************/
00638 static void AccessClose( vlc_object_t *p_this )
00639 {
00640     access_t     *p_access = (access_t *)p_this;
00641     access_sys_t *p_sys    = p_access->p_sys;
00642 
00643     /* Stop capturing stuff */
00644     p_sys->p_control->Stop();
00645 
00646     CommonClose( p_this, p_sys );
00647 }
00648 
00649 /*****************************************************************************
00650  * DemuxClose: close device
00651  *****************************************************************************/
00652 static void DemuxClose( vlc_object_t *p_this )
00653 {
00654     demux_t      *p_demux = (demux_t *)p_this;
00655     access_sys_t *p_sys   = (access_sys_t *)p_demux->p_sys;
00656 
00657     /* Stop capturing stuff */
00658     p_sys->p_control->Stop();
00659 
00660     CommonClose( p_this, p_sys );
00661 }
00662 
00663 /****************************************************************************
00664  * ConnectFilters
00665  ****************************************************************************/
00666 static bool ConnectFilters( vlc_object_t *p_this, access_sys_t *p_sys,
00667                             IBaseFilter *p_filter,
00668                             CaptureFilter *p_capture_filter )
00669 {
00670     CapturePin *p_input_pin = p_capture_filter->CustomGetPin();
00671 
00672     AM_MEDIA_TYPE mediaType = p_input_pin->CustomGetMediaType();
00673 
00674     if( p_sys->p_capture_graph_builder2 )
00675     {
00676         if( FAILED(p_sys->p_capture_graph_builder2->
00677                 RenderStream( &PIN_CATEGORY_CAPTURE, &mediaType.majortype,
00678                               p_filter, 0, (IBaseFilter *)p_capture_filter )) )
00679         {
00680             return false;
00681         }
00682 
00683         // Sort out all the possible video inputs
00684         // The class needs to be given the capture filters ANALOGVIDEO input pin
00685         IEnumPins *pins = 0;
00686         if( ( mediaType.majortype == MEDIATYPE_Video ||
00687               mediaType.majortype == MEDIATYPE_Stream ) &&
00688             SUCCEEDED(p_filter->EnumPins(&pins)) )
00689         {
00690             IPin        *pP = 0;
00691             ULONG        n;
00692             PIN_INFO     pinInfo;
00693             BOOL         Found = FALSE;
00694             IKsPropertySet *pKs=0;
00695             GUID guid;
00696             DWORD dw;
00697 
00698             while( !Found && ( S_OK == pins->Next(1, &pP, &n) ) )
00699             {
00700                 if( S_OK == pP->QueryPinInfo(&pinInfo) )
00701                 {
00702                     // is this pin an ANALOGVIDEOIN input pin?
00703                     if( pinInfo.dir == PINDIR_INPUT &&
00704                         pP->QueryInterface( IID_IKsPropertySet,
00705                                             (void **)&pKs ) == S_OK )
00706                     {
00707                         if( pKs->Get( AMPROPSETID_Pin,
00708                                       AMPROPERTY_PIN_CATEGORY, NULL, 0,
00709                                       &guid, sizeof(GUID), &dw ) == S_OK )
00710                         {
00711                             if( guid == PIN_CATEGORY_ANALOGVIDEOIN )
00712                             {
00713                                 // recursively search crossbar routes
00714                                 FindCrossbarRoutes( p_this, p_sys, pP, 0 );
00715                                 // found it
00716                                 Found = TRUE;
00717                             }
00718                         }
00719                         pKs->Release();
00720                     }
00721                     pinInfo.pFilter->Release();
00722                 }
00723                 pP->Release();
00724             }
00725             pins->Release();
00726         }
00727         return true;
00728     }
00729     else
00730     {
00731         IEnumPins *p_enumpins;
00732         IPin *p_pin;
00733 
00734         if( S_OK != p_filter->EnumPins( &p_enumpins ) ) return false;
00735 
00736         while( S_OK == p_enumpins->Next( 1, &p_pin, NULL ) )
00737         {
00738             PIN_DIRECTION pin_dir;
00739             p_pin->QueryDirection( &pin_dir );
00740 
00741             if( pin_dir == PINDIR_OUTPUT &&
00742                 p_sys->p_graph->ConnectDirect( p_pin, (IPin *)p_input_pin,
00743                                                0 ) == S_OK )
00744             {
00745                 p_pin->Release();
00746                 p_enumpins->Release();
00747                 return true;
00748             }
00749             p_pin->Release();
00750         }
00751 
00752         p_enumpins->Release();
00753         return false;
00754     }
00755 }
00756 
00757 /*
00758  * get fourcc priority from arbritary preference, the higher the better
00759  */
00760 static int GetFourCCPriority( int i_fourcc )
00761 {
00762     switch( i_fourcc )
00763     {
00764     case VLC_FOURCC('I','4','2','0'):
00765     case VLC_FOURCC('f','l','3','2'):
00766         return 9;
00767     case VLC_FOURCC('Y','V','1','2'):
00768     case VLC_FOURCC('a','r','a','w'):
00769         return 8;
00770     case VLC_FOURCC('R','V','2','4'):
00771         return 7;
00772     case VLC_FOURCC('Y','U','Y','2'):
00773     case VLC_FOURCC('R','V','3','2'):
00774     case VLC_FOURCC('R','G','B','A'):
00775         return 6;
00776     }
00777 
00778     return 0;
00779 }
00780 
00781 #define MAX_MEDIA_TYPES 32
00782 
00783 static int OpenDevice( vlc_object_t *p_this, access_sys_t *p_sys,
00784                        string devicename, vlc_bool_t b_audio )
00785 {
00786     /* See if device is already opened */
00787     for( int i = 0; i < p_sys->i_streams; i++ )
00788     {
00789         if( devicename.size() &&
00790             p_sys->pp_streams[i]->devicename == devicename )
00791         {
00792             /* Already opened */
00793             return VLC_SUCCESS;
00794         }
00795     }
00796 
00797     list<string> list_devices;
00798 
00799     /* Enumerate devices and display their names */
00800     FindCaptureDevice( p_this, NULL, &list_devices, b_audio );
00801 
00802     if( !list_devices.size() )
00803         return VLC_EGENERIC;
00804 
00805     list<string>::iterator iter;
00806     for( iter = list_devices.begin(); iter != list_devices.end(); iter++ )
00807         msg_Dbg( p_this, "found device: %s", iter->c_str() );
00808 
00809     /* If no device name was specified, pick the 1st one */
00810     if( devicename.size() == 0 )
00811     {
00812         devicename = *list_devices.begin();
00813     }
00814 
00815     // Use the system device enumerator and class enumerator to find
00816     // a capture/preview device, such as a desktop USB video camera.
00817     IBaseFilter *p_device_filter =
00818         FindCaptureDevice( p_this, &devicename, 0, b_audio );
00819     if( p_device_filter )
00820         msg_Dbg( p_this, "using device: %s", devicename.c_str() );
00821     else
00822     {
00823         msg_Err( p_this, "can't use device: %s, unsupported device type",
00824                  devicename.c_str() );
00825         return VLC_EGENERIC;
00826     }
00827 
00828     // Retreive acceptable media types supported by device
00829     AM_MEDIA_TYPE media_types[MAX_MEDIA_TYPES];
00830     size_t media_count =
00831         EnumDeviceCaps( p_this, p_device_filter, p_sys->i_chroma,
00832                         p_sys->i_width, p_sys->i_height,
00833                         0, 0, 0, media_types, MAX_MEDIA_TYPES );
00834 
00835     /* Find out if the pin handles MEDIATYPE_Stream, in which case we
00836      * won't add a prefered media type as this doesn't seem to work well
00837      * -- to investigate. */
00838     vlc_bool_t b_stream_type = VLC_FALSE;
00839     for( size_t i = 0; i < media_count; i++ )
00840     {
00841         if( media_types[i].majortype == MEDIATYPE_Stream )
00842         {
00843             b_stream_type = VLC_TRUE;
00844             break;
00845         }
00846     }
00847 
00848     size_t mt_count = 0;
00849     AM_MEDIA_TYPE *mt = NULL;
00850 
00851     if( !b_stream_type && !b_audio )
00852     {
00853         // Insert prefered video media type
00854         AM_MEDIA_TYPE mtr;
00855         VIDEOINFOHEADER vh;
00856 
00857         mtr.majortype            = MEDIATYPE_Video;
00858         mtr.subtype              = MEDIASUBTYPE_I420;
00859         mtr.bFixedSizeSamples    = TRUE;
00860         mtr.bTemporalCompression = FALSE;
00861         mtr.pUnk                 = NULL;
00862         mtr.formattype           = FORMAT_VideoInfo;
00863         mtr.cbFormat             = sizeof(vh);
00864         mtr.pbFormat             = (BYTE *)&vh;
00865 
00866         memset(&vh, 0, sizeof(vh));
00867 
00868         vh.bmiHeader.biSize   = sizeof(vh.bmiHeader);
00869         vh.bmiHeader.biWidth  = p_sys->i_width > 0 ? p_sys->i_width : 320;
00870         vh.bmiHeader.biHeight = p_sys->i_height > 0 ? p_sys->i_height : 240;
00871         vh.bmiHeader.biPlanes      = 3;
00872         vh.bmiHeader.biBitCount    = 12;
00873         vh.bmiHeader.biCompression = VLC_FOURCC('I','4','2','0');
00874         vh.bmiHeader.biSizeImage   = vh.bmiHeader.biWidth * 12 *
00875             vh.bmiHeader.biHeight / 8;
00876         mtr.lSampleSize            = vh.bmiHeader.biSizeImage;
00877 
00878         mt_count = 1;
00879         mt = (AM_MEDIA_TYPE *)malloc( sizeof(AM_MEDIA_TYPE)*mt_count );
00880         CopyMediaType(mt, &mtr);
00881     }
00882     else if( !b_stream_type )
00883     {
00884         // Insert prefered audio media type
00885         AM_MEDIA_TYPE mtr;
00886         WAVEFORMATEX wf;
00887 
00888         mtr.majortype            = MEDIATYPE_Audio;
00889         mtr.subtype              = MEDIASUBTYPE_PCM;
00890         mtr.bFixedSizeSamples    = TRUE;
00891         mtr.bTemporalCompression = FALSE;
00892         mtr.lSampleSize          = 0;
00893         mtr.pUnk                 = NULL;
00894         mtr.formattype           = FORMAT_WaveFormatEx;
00895         mtr.cbFormat             = sizeof(wf);
00896         mtr.pbFormat             = (BYTE *)&wf;
00897 
00898         memset(&wf, 0, sizeof(wf));
00899 
00900         wf.wFormatTag = WAVE_FORMAT_PCM;
00901         wf.nChannels = 2;
00902         wf.nSamplesPerSec = 44100;
00903         wf.wBitsPerSample = 16;
00904         wf.nBlockAlign = wf.nSamplesPerSec * wf.wBitsPerSample / 8;
00905         wf.nAvgBytesPerSec = wf.nSamplesPerSec * wf.nBlockAlign;
00906         wf.cbSize = 0;
00907 
00908         mt_count = 1;
00909         mt = (AM_MEDIA_TYPE *)malloc( sizeof(AM_MEDIA_TYPE)*mt_count );
00910         CopyMediaType(mt, &mtr);
00911     }
00912 
00913     if( media_count > 0 )
00914     {
00915         mt = (AM_MEDIA_TYPE *)realloc( mt, sizeof(AM_MEDIA_TYPE) *
00916                                        (mt_count + media_count) );
00917 
00918         // Order and copy returned media types according to arbitrary
00919         // fourcc priority
00920         for( size_t c = 0; c < media_count; c++ )
00921         {
00922             int slot_priority =
00923                 GetFourCCPriority(GetFourCCFromMediaType(media_types[c]));
00924             size_t slot_copy = c;
00925             for( size_t d = c+1; d < media_count; d++ )
00926             {
00927                 int priority =
00928                     GetFourCCPriority(GetFourCCFromMediaType(media_types[d]));
00929                 if( priority > slot_priority )
00930                 {
00931                     slot_priority = priority;
00932                     slot_copy = d;
00933                 }
00934             }
00935             if( slot_copy != c )
00936             {
00937                 mt[c+mt_count] = media_types[slot_copy];
00938                 media_types[slot_copy] = media_types[c];
00939             }
00940             else
00941             {
00942                 mt[c+mt_count] = media_types[c];
00943             }
00944         }
00945         mt_count += media_count;
00946     }
00947 
00948     /* Create and add our capture filter */
00949     CaptureFilter *p_capture_filter =
00950         new CaptureFilter( p_this, p_sys, mt, mt_count );
00951     p_sys->p_graph->AddFilter( p_capture_filter, 0 );
00952 
00953     /* Add the device filter to the graph (seems necessary with VfW before
00954      * accessing pin attributes). */
00955     p_sys->p_graph->AddFilter( p_device_filter, 0 );
00956 
00957     /* Attempt to connect one of this device's capture output pins */
00958     msg_Dbg( p_this, "connecting filters" );
00959     if( ConnectFilters( p_this, p_sys, p_device_filter, p_capture_filter ) )
00960     {
00961         /* Success */
00962         msg_Dbg( p_this, "filters connected successfully !" );
00963 
00964         dshow_stream_t dshow_stream;
00965         dshow_stream.b_pts = VLC_FALSE;
00966         dshow_stream.p_es = 0;
00967         dshow_stream.mt =
00968             p_capture_filter->CustomGetPin()->CustomGetMediaType();
00969 
00970         /* Show Device properties. Done here so the VLC stream is setup with
00971          * the proper parameters. */
00972         vlc_value_t val;
00973         var_Get( p_this, "dshow-config", &val );
00974         if( val.b_bool )
00975         {
00976             ShowDeviceProperties( p_this, p_sys->p_capture_graph_builder2,
00977                                   p_device_filter, b_audio );
00978         }
00979 
00980         ConfigTuner( p_this, p_sys->p_capture_graph_builder2,
00981                      p_device_filter );
00982 
00983         var_Get( p_this, "dshow-tuner", &val );
00984         if( val.b_bool && dshow_stream.mt.majortype != MEDIATYPE_Stream )
00985         {
00986             /* FIXME: we do MEDIATYPE_Stream later so we don't do it twice. */
00987             ShowTunerProperties( p_this, p_sys->p_capture_graph_builder2,
00988                                  p_device_filter, b_audio );
00989         }
00990 
00991         dshow_stream.mt =
00992             p_capture_filter->CustomGetPin()->CustomGetMediaType();
00993 
00994         dshow_stream.i_fourcc = GetFourCCFromMediaType( dshow_stream.mt );
00995         if( dshow_stream.i_fourcc )
00996         {
00997             if( dshow_stream.mt.majortype == MEDIATYPE_Video )
00998             {
00999                 dshow_stream.header.video =
01000                     *(VIDEOINFOHEADER *)dshow_stream.mt.pbFormat;
01001                 msg_Dbg( p_this, "MEDIATYPE_Video" );
01002                 msg_Dbg( p_this, "selected video pin accepts format: %4.4s",
01003                          (char *)&dshow_stream.i_fourcc);
01004             }
01005             else if( dshow_stream.mt.majortype == MEDIATYPE_Audio )
01006             {
01007                 dshow_stream.header.audio =
01008                     *(WAVEFORMATEX *)dshow_stream.mt.pbFormat;
01009                 msg_Dbg( p_this, "MEDIATYPE_Audio" );
01010                 msg_Dbg( p_this, "selected audio pin accepts format: %4.4s",
01011                          (char *)&dshow_stream.i_fourcc);
01012             }
01013             else if( dshow_stream.mt.majortype == MEDIATYPE_Stream )
01014             {
01015                 msg_Dbg( p_this, "MEDIATYPE_Stream" );
01016                 msg_Dbg( p_this, "selected stream pin accepts format: %4.4s",
01017                          (char *)&dshow_stream.i_fourcc);
01018             }
01019             else
01020             {
01021                 msg_Dbg( p_this, "unknown stream majortype" );
01022                 goto fail;
01023             }
01024 
01025             /* Add directshow elementary stream to our list */
01026             dshow_stream.p_device_filter = p_device_filter;
01027             dshow_stream.p_capture_filter = p_capture_filter;
01028 
01029             p_sys->pp_streams = (dshow_stream_t **)realloc( p_sys->pp_streams,
01030                 sizeof(dshow_stream_t *) * (p_sys->i_streams + 1) );
01031             p_sys->pp_streams[p_sys->i_streams] = new dshow_stream_t;
01032             *p_sys->pp_streams[p_sys->i_streams++] = dshow_stream;
01033 
01034             return VLC_SUCCESS;
01035         }
01036     }
01037 
01038  fail:
01039     /* Remove filters from graph */
01040     p_sys->p_graph->RemoveFilter( p_device_filter );
01041     p_sys->p_graph->RemoveFilter( p_capture_filter );
01042 
01043     /* Release objects */
01044     p_device_filter->Release();
01045     p_capture_filter->Release();
01046 
01047     return VLC_EGENERIC;
01048 }
01049 
01050 static IBaseFilter *
01051 FindCaptureDevice( vlc_object_t *p_this, string *p_devicename,
01052                    list<string> *p_listdevices, vlc_bool_t b_audio )
01053 {
01054     IBaseFilter *p_base_filter = NULL;
01055     IMoniker *p_moniker = NULL;
01056     ULONG i_fetched;
01057     HRESULT hr;
01058 
01059     /* Create the system device enumerator */
01060     ICreateDevEnum *p_dev_enum = NULL;
01061 
01062     hr = CoCreateInstance( CLSID_SystemDeviceEnum, NULL, CLSCTX_INPROC,
01063                            IID_ICreateDevEnum, (void **)&p_dev_enum );
01064     if( FAILED(hr) )
01065     {
01066         msg_Err( p_this, "failed to create the device enumerator (0x%lx)", hr);
01067         return NULL;
01068     }
01069 
01070     /* Create an enumerator for the video capture devices */
01071     IEnumMoniker *p_class_enum = NULL;
01072     if( !b_audio )
01073         hr = p_dev_enum->CreateClassEnumerator( CLSID_VideoInputDeviceCategory,
01074                                                 &p_class_enum, 0 );
01075     else
01076         hr = p_dev_enum->CreateClassEnumerator( CLSID_AudioInputDeviceCategory,
01077                                                 &p_class_enum, 0 );
01078     p_dev_enum->Release();
01079     if( FAILED(hr) )
01080     {
01081         msg_Err( p_this, "failed to create the class enumerator (0x%lx)", hr );
01082         return NULL;
01083     }
01084 
01085     /* If there are no enumerators for the requested type, then
01086      * CreateClassEnumerator will succeed, but p_class_enum will be NULL */
01087     if( p_class_enum == NULL )
01088     {
01089         msg_Err( p_this, "no capture device was detected" );
01090         return NULL;
01091     }
01092 
01093     /* Enumerate the devices */
01094 
01095     /* Note that if the Next() call succeeds but there are no monikers,
01096      * it will return S_FALSE (which is not a failure). Therefore, we check
01097      * that the return code is S_OK instead of using SUCCEEDED() macro. */
01098 
01099     while( p_class_enum->Next( 1, &p_moniker, &i_fetched ) == S_OK )
01100     {
01101         /* Getting the property page to get the device name */
01102         IPropertyBag *p_bag;
01103         hr = p_moniker->BindToStorage( 0, 0, IID_IPropertyBag,
01104                                        (void **)&p_bag );
01105         if( SUCCEEDED(hr) )
01106         {
01107             VARIANT var;
01108             var.vt = VT_BSTR;
01109             hr = p_bag->Read( L"FriendlyName", &var, NULL );
01110             p_bag->Release();
01111             if( SUCCEEDED(hr) )
01112             {
01113                 int i_convert = WideCharToMultiByte(CP_ACP, 0, var.bstrVal,
01114                         SysStringLen(var.bstrVal), NULL, 0, NULL, NULL);
01115                 char *p_buf = (char *)alloca( i_convert+1 ); p_buf[0] = 0;
01116                 WideCharToMultiByte( CP_ACP, 0, var.bstrVal,
01117                         SysStringLen(var.bstrVal), p_buf, i_convert, NULL, NULL );
01118                 SysFreeString(var.bstrVal);
01119                 p_buf[i_convert] = '\0';
01120 
01121                 if( p_listdevices ) p_listdevices->push_back( p_buf );
01122 
01123                 if( p_devicename && *p_devicename == string(p_buf) )
01124                 {
01125                     /* Bind Moniker to a filter object */
01126                     hr = p_moniker->BindToObject( 0, 0, IID_IBaseFilter,
01127                                                   (void **)&p_base_filter );
01128                     if( FAILED(hr) )
01129                     {
01130                         msg_Err( p_this, "couldn't bind moniker to filter "
01131                                  "object (0x%lx)", hr );
01132                         p_moniker->Release();
01133                         p_class_enum->Release();
01134                         return NULL;
01135                     }
01136                     p_moniker->Release();
01137                     p_class_enum->Release();
01138                     return p_base_filter;
01139                 }
01140             }
01141         }
01142 
01143         p_moniker->Release();
01144     }
01145 
01146     p_class_enum->Release();
01147     return NULL;
01148 }
01149 
01150 static size_t EnumDeviceCaps( vlc_object_t *p_this, IBaseFilter *p_filter,
01151                               int i_fourcc, int i_width, int i_height,
01152                               int i_channels, int i_samplespersec,
01153                               int i_bitspersample, AM_MEDIA_TYPE *mt,
01154                               size_t mt_max )
01155 {
01156     IEnumPins *p_enumpins;
01157     IPin *p_output_pin;
01158     IEnumMediaTypes *p_enummt;
01159     size_t mt_count = 0;
01160 
01161     LONGLONG i_AvgTimePerFrame = 0;
01162     float r_fps = var_GetFloat( p_this, "dshow-fps" );
01163     if( r_fps )
01164         i_AvgTimePerFrame = 10000000000LL/(LONGLONG)(r_fps*1000.0f);
01165 
01166     if( FAILED(p_filter->EnumPins( &p_enumpins )) )
01167     {
01168         msg_Dbg( p_this, "EnumDeviceCaps failed: no pin enumeration !");
01169         return 0;
01170     }
01171 
01172     while( S_OK == p_enumpins->Next( 1, &p_output_pin, NULL ) )
01173     {
01174         PIN_INFO info;
01175 
01176         if( S_OK == p_output_pin->QueryPinInfo( &info ) )
01177         {
01178             msg_Dbg( p_this, "EnumDeviceCaps: %s pin: %S",
01179                      info.dir == PINDIR_INPUT ? "input" : "output",
01180                      info.achName );
01181             if( info.pFilter ) info.pFilter->Release();
01182         }
01183 
01184         p_output_pin->Release();
01185     }
01186 
01187     p_enumpins->Reset();
01188 
01189     while( !mt_count && p_enumpins->Next( 1, &p_output_pin, NULL ) == S_OK )
01190     {
01191         PIN_INFO info;
01192 
01193         if( S_OK == p_output_pin->QueryPinInfo( &info ) )
01194         {
01195             if( info.pFilter ) info.pFilter->Release();
01196             if( info.dir == PINDIR_INPUT )
01197             {
01198                 p_output_pin->Release();
01199                 continue;
01200             }
01201             msg_Dbg( p_this, "EnumDeviceCaps: trying pin %S", info.achName );
01202         }
01203 
01204         AM_MEDIA_TYPE *p_mt;
01205 
01206         /*
01207         ** Configure pin with a default compatible media if possible
01208         */
01209 
01210         IAMStreamConfig *pSC;
01211         if( SUCCEEDED(p_output_pin->QueryInterface( IID_IAMStreamConfig,
01212                                             (void **)&pSC )) )
01213         {
01214             int piCount, piSize;
01215             if( SUCCEEDED(pSC->GetNumberOfCapabilities(&piCount, &piSize)) )
01216             {
01217                 BYTE *pSCC= (BYTE *)CoTaskMemAlloc(piSize);
01218                 if( NULL != pSCC )
01219                 {
01220                     for( int i=0; i<piCount; ++i )
01221                     {
01222                         if( SUCCEEDED(pSC->GetStreamCaps(i, &p_mt, pSCC)) )
01223                         {
01224                             int i_current_fourcc = GetFourCCFromMediaType( *p_mt );
01225 
01226                             if( !i_current_fourcc || (i_fourcc && (i_current_fourcc != i_fourcc)) )
01227                             {
01228                                 // incompatible or unrecognized chroma, try next media type
01229                                 FreeMediaType( *p_mt );
01230                                 CoTaskMemFree( (PVOID)p_mt );
01231                                 continue;
01232                             }
01233 
01234                             if( MEDIATYPE_Video == p_mt->majortype
01235                                     && FORMAT_VideoInfo == p_mt->formattype )
01236                             {
01237                                 VIDEO_STREAM_CONFIG_CAPS *pVSCC = reinterpret_cast<VIDEO_STREAM_CONFIG_CAPS*>(pSCC);
01238                                 VIDEOINFOHEADER *pVih = reinterpret_cast<VIDEOINFOHEADER*>(p_mt->pbFormat);
01239 
01240                                 if( i_AvgTimePerFrame )
01241                                 {
01242                                     if( pVSCC->MinFrameInterval > i_AvgTimePerFrame
01243                                       || i_AvgTimePerFrame > pVSCC->MaxFrameInterval )
01244                                     {
01245                                         // required frame rate not compatible, try next media type
01246                                         FreeMediaType( *p_mt );
01247                                         CoTaskMemFree( (PVOID)p_mt );
01248                                         continue;
01249                                     }
01250                                     pVih->AvgTimePerFrame = i_AvgTimePerFrame;
01251                                 }
01252 
01253                                 if( i_width )
01254                                 {
01255                                     if( i_width % pVSCC->OutputGranularityX
01256                                      || pVSCC->MinOutputSize.cx > i_width
01257                                      || i_width > pVSCC->MaxOutputSize.cx )
01258                                     {
01259                                         // required width not compatible, try next media type
01260                                         FreeMediaType( *p_mt );
01261                                         CoTaskMemFree( (PVOID)p_mt );
01262                                         continue;
01263                                     }
01264                                     pVih->bmiHeader.biWidth = i_width;
01265                                 }
01266 
01267                                 if( i_height )
01268                                 {
01269                                     if( i_height % pVSCC->OutputGranularityY
01270                                      || pVSCC->MinOutputSize.cy > i_height 
01271                                      || i_height > pVSCC->MaxOutputSize.cy )
01272                                     {
01273                                         // required height not compatible, try next media type
01274                                         FreeMediaType( *p_mt );
01275                                         CoTaskMemFree( (PVOID)p_mt );
01276                                         continue;
01277                                     }
01278                                     pVih->bmiHeader.biHeight = i_height;
01279                                 }
01280 
01281                                 // Set the sample size and image size.
01282                                 // (Round the image width up to a DWORD boundary.)
01283                                 p_mt->lSampleSize = pVih->bmiHeader.biSizeImage = 
01284                                     ((pVih->bmiHeader.biWidth + 3) & ~3) *
01285                                     pVih->bmiHeader.biHeight * (pVih->bmiHeader.biBitCount>>3);
01286 
01287                                 // no cropping, use full video input buffer
01288                                 memset(&(pVih->rcSource), 0, sizeof(RECT));
01289                                 memset(&(pVih->rcTarget), 0, sizeof(RECT));
01290 
01291                                 // select this format as default
01292                                 if( SUCCEEDED( pSC->SetFormat(p_mt) ) )
01293                                 {
01294                                     msg_Dbg( p_this, "EnumDeviceCaps: input pin video format configured");
01295                                     // no need to check any more media types 
01296                                     i = piCount;
01297                                 }
01298                             }
01299                             else if( p_mt->majortype == MEDIATYPE_Audio
01300                                     && p_mt->formattype == FORMAT_WaveFormatEx )
01301                             {
01302                                 AUDIO_STREAM_CONFIG_CAPS *pASCC = reinterpret_cast<AUDIO_STREAM_CONFIG_CAPS*>(pSCC);
01303                                 WAVEFORMATEX *pWfx = reinterpret_cast<WAVEFORMATEX*>(p_mt->pbFormat);
01304 
01305                                 if( i_channels )
01306                                 {
01307                                     if( i_channels % pASCC->ChannelsGranularity
01308                                      || (unsigned int)i_channels < pASCC->MinimumChannels
01309                                      || (unsigned int)i_channels > pASCC->MaximumChannels )
01310                                     {
01311                                         // required channels not compatible, try next media type
01312                                         FreeMediaType( *p_mt );
01313                                         CoTaskMemFree( (PVOID)p_mt );
01314                                         continue;
01315                                     }
01316                                     pWfx->nChannels = i_channels;
01317                                 }
01318 
01319                                 if( i_samplespersec )
01320                                 {
01321                                     if( i_samplespersec % pASCC->BitsPerSampleGranularity
01322                                      || (unsigned int)i_samplespersec < pASCC->MinimumSampleFrequency
01323                                      || (unsigned int)i_samplespersec > pASCC->MaximumSampleFrequency )
01324                                     {
01325                                         // required sampling rate not compatible, try next media type
01326                                         FreeMediaType( *p_mt );
01327                                         CoTaskMemFree( (PVOID)p_mt );
01328                                         continue;
01329                                     }
01330                                     pWfx->nSamplesPerSec = i_samplespersec;
01331                                 }
01332 
01333                                 if( i_bitspersample )
01334                                 {
01335                                     if( i_bitspersample % pASCC->BitsPerSampleGranularity
01336                                      || (unsigned int)i_bitspersample < pASCC->MinimumBitsPerSample
01337                                      || (unsigned int)i_bitspersample > pASCC->MaximumBitsPerSample )
01338                                     {
01339                                         // required sample size not compatible, try next media type
01340                                         FreeMediaType( *p_mt );
01341                                         CoTaskMemFree( (PVOID)p_mt );
01342                                         continue;
01343                                     }
01344                                     pWfx->wBitsPerSample = i_bitspersample;
01345                                 }
01346 
01347                                 // select this format as default
01348                                 if( SUCCEEDED( pSC->SetFormat(p_mt) ) )
01349                                 {
01350                                     msg_Dbg( p_this, "EnumDeviceCaps: input pin default format configured");
01351                                     // no need to check any more media types 
01352                                     i = piCount;
01353                                 }
01354                             }
01355                             FreeMediaType( *p_mt );
01356                             CoTaskMemFree( (PVOID)p_mt );
01357                         }
01358                     }
01359                     CoTaskMemFree( (LPVOID)pSCC );
01360                 }
01361             }
01362             pSC->Release();
01363         }
01364 
01365         /*
01366         ** Probe pin for available medias (may be a previously configured one)
01367         */
01368 
01369         if( FAILED( p_output_pin->EnumMediaTypes( &p_enummt ) ) )
01370         {
01371             p_output_pin->Release();
01372             continue;
01373         }
01374 
01375 
01376         while( p_enummt->Next( 1, &p_mt, NULL ) == S_OK )
01377         {
01378             int i_current_fourcc = GetFourCCFromMediaType( *p_mt );
01379             if( i_current_fourcc && p_mt->majortype == MEDIATYPE_Video
01380                 && p_mt->formattype == FORMAT_VideoInfo )
01381             {
01382                 int i_current_width = ((VIDEOINFOHEADER *)p_mt->pbFormat)->bmiHeader.biWidth;
01383                 int i_current_height = ((VIDEOINFOHEADER *)p_mt->pbFormat)->bmiHeader.biHeight;
01384                 LONGLONG i_current_atpf = ((VIDEOINFOHEADER *)p_mt->pbFormat)->AvgTimePerFrame;
01385 
01386                 if( i_current_height < 0 )
01387                     i_current_height = -i_current_height; 
01388 
01389                 msg_Dbg( p_this, "EnumDeviceCaps: input pin "
01390                          "accepts chroma: %4.4s, width:%i, height:%i, fps:%f",
01391                          (char *)&i_current_fourcc, i_current_width,
01392                          i_current_height, (10000000.0f/((float)i_current_atpf)) );
01393 
01394                 if( ( !i_fourcc || i_fourcc == i_current_fourcc ) &&
01395                     ( !i_width || i_width == i_current_width ) &&
01396                     ( !i_height || i_height == i_current_height ) &&
01397                     ( !i_AvgTimePerFrame || i_AvgTimePerFrame == i_current_atpf ) &&
01398                     mt_count < mt_max )
01399                 {
01400                     /* Pick match */
01401                     mt[mt_count++] = *p_mt;
01402                 }
01403                 else FreeMediaType( *p_mt );
01404             }
01405             else if( i_current_fourcc && p_mt->majortype == MEDIATYPE_Audio 
01406                     && p_mt->formattype == FORMAT_WaveFormatEx)
01407             {
01408                 int i_current_channels =
01409                     ((WAVEFORMATEX *)p_mt->pbFormat)->nChannels;
01410                 int i_current_samplespersec =
01411                     ((WAVEFORMATEX *)p_mt->pbFormat)->nSamplesPerSec;
01412                 int i_current_bitspersample =
01413                     ((WAVEFORMATEX *)p_mt->pbFormat)->wBitsPerSample;
01414 
01415                 msg_Dbg( p_this, "EnumDeviceCaps: input pin "
01416                          "accepts format: %4.4s, channels:%i, "
01417                          "samples/sec:%i bits/sample:%i",
01418                          (char *)&i_current_fourcc, i_current_channels,
01419                          i_current_samplespersec, i_current_bitspersample);
01420 
01421                 if( (!i_channels || i_channels == i_current_channels) &&
01422                     (!i_samplespersec ||
01423                      i_samplespersec == i_current_samplespersec) &&
01424                     (!i_bitspersample ||
01425                      i_bitspersample == i_current_bitspersample) &&
01426                     mt_count < mt_max )
01427                 {
01428                     /* Pick  match */
01429                     mt[mt_count++] = *p_mt;
01430 
01431                     /* Setup a few properties like the audio latency */
01432                     IAMBufferNegotiation *p_ambuf;
01433                     if( SUCCEEDED( p_output_pin->QueryInterface(
01434                           IID_IAMBufferNegotiation, (void **)&p_ambuf ) ) )
01435                     {
01436                         ALLOCATOR_PROPERTIES AllocProp;
01437                         AllocProp.cbAlign = -1;
01438 
01439                         /* 100 ms of latency */
01440                         AllocProp.cbBuffer = i_current_channels *
01441                           i_current_samplespersec *
01442                           i_current_bitspersample / 8 / 10;
01443 
01444                         AllocProp.cbPrefix = -1;
01445                         AllocProp.cBuffers = -1;
01446                         p_ambuf->SuggestAllocatorProperties( &AllocProp );
01447                         p_ambuf->Release();
01448                     }
01449                 }
01450                 else FreeMediaType( *p_mt );
01451             }
01452             else if( i_current_fourcc && p_mt->majortype == MEDIATYPE_Stream )
01453             {
01454                 msg_Dbg( p_this, "EnumDeviceCaps: input pin "
01455                          "accepts stream format: %4.4s",
01456                          (char *)&i_current_fourcc );
01457 
01458                 if( ( !i_fourcc || i_fourcc == i_current_fourcc ) &&
01459                     mt_count < mt_max )
01460                 {
01461                     /* Pick match */
01462                     mt[mt_count++] = *p_mt;
01463                     i_fourcc = i_current_fourcc;
01464                 }
01465                 else FreeMediaType( *p_mt );
01466             }
01467             else
01468             {
01469                 char *psz_type = "unknown";
01470                 if( p_mt->majortype == MEDIATYPE_Video ) psz_type = "video";
01471                 if( p_mt->majortype == MEDIATYPE_Audio ) psz_type = "audio";
01472                 if( p_mt->majortype == MEDIATYPE_Stream ) psz_type = "stream";
01473                 msg_Dbg( p_this, "EnumDeviceCaps: input pin media: unknown format "
01474                          "(%s %4.4s)", psz_type, (char *)&p_mt->subtype );
01475                 FreeMediaType( *p_mt );
01476             }
01477             CoTaskMemFree( (PVOID)p_mt );
01478         }
01479 
01480         p_enummt->Release();
01481         p_output_pin->Release();
01482     }
01483 
01484     p_enumpins->Release();
01485     return mt_count;
01486 }
01487 
01488 /*****************************************************************************
01489  * ReadCompressed: reads compressed (MPEG/DV) data from the device.
01490  *****************************************************************************
01491  * Returns -1 in case of error, 0 in case of EOF, otherwise the number of
01492  * bytes.
01493  *****************************************************************************/
01494 static block_t *ReadCompressed( access_t *p_access )
01495 {
01496     access_sys_t   *p_sys = p_access->p_sys;
01497     dshow_stream_t *p_stream = NULL;
01498     VLCMediaSample sample;
01499 
01500     /* Read 1 DV/MPEG frame (they contain the video and audio data) */
01501 
01502     /* There must be only 1 elementary stream to produce a valid stream
01503      * of MPEG or DV data */
01504     p_stream = p_sys->pp_streams[0];
01505 
01506     while( 1 )
01507     {
01508         if( p_access->b_die || p_access->b_error ) return 0;
01509 
01510         /* Get new sample/frame from the elementary stream (blocking). */
01511         vlc_mutex_lock( &p_sys->lock );
01512 
01513         if( p_stream->p_capture_filter->CustomGetPin()
01514               ->CustomGetSample( &sample ) != S_OK )
01515         {
01516             /* No data available. Wait until some data has arrived */
01517             vlc_cond_wait( &p_sys->wait, &p_sys->lock );
01518             vlc_mutex_unlock( &p_sys->lock );
01519             continue;
01520         }
01521 
01522         vlc_mutex_unlock( &p_sys->lock );
01523 
01524         /*
01525          * We got our sample
01526          */
01527         block_t *p_block;
01528         uint8_t *p_data;
01529         int i_data_size = sample.p_sample->GetActualDataLength();
01530 
01531         if( !i_data_size || !(p_block = block_New( p_access, i_data_size )) )
01532         {
01533             sample.p_sample->Release();
01534             continue;
01535         }
01536 
01537         sample.p_sample->GetPointer( &p_data );
01538         p_access->p_vlc->pf_memcpy( p_block->p_buffer, p_data, i_data_size );
01539         sample.p_sample->Release();
01540 
01541         /* The caller got what he wanted */
01542         return p_block;
01543     }
01544 
01545     return 0; /* never reached */
01546 }
01547 
01548 /****************************************************************************
01549  * Demux:
01550  ****************************************************************************/
01551 static int Demux( demux_t *p_demux )
01552 {
01553     access_sys_t *p_sys = (access_sys_t *)p_demux->p_sys;
01554     dshow_stream_t *p_stream = NULL;
01555     VLCMediaSample sample;
01556     int i_data_size, i_stream;
01557     uint8_t *p_data;
01558     block_t *p_block;
01559 
01560     vlc_mutex_lock( &p_sys->lock );
01561 
01562     /* Try to grab an audio sample (audio has a higher priority) */
01563     for( i_stream = 0; i_stream < p_sys->i_streams; i_stream++ )
01564     {
01565         p_stream = p_sys->pp_streams[i_stream];
01566         if( p_stream->mt.majortype == MEDIATYPE_Audio &&
01567             p_stream->p_capture_filter &&
01568             p_stream->p_capture_filter->CustomGetPin()
01569               ->CustomGetSample( &sample ) == S_OK )
01570         {
01571             break;
01572         }
01573     }
01574     /* Try to grab a video sample */
01575     if( i_stream == p_sys->i_streams )
01576     {
01577         for( i_stream = 0; i_stream < p_sys->i_streams; i_stream++ )
01578         {
01579             p_stream = p_sys->pp_streams[i_stream];
01580             if( p_stream->p_capture_filter &&
01581                 p_stream->p_capture_filter->CustomGetPin()
01582                     ->CustomGetSample( &sample ) == S_OK )
01583             {
01584                 break;
01585             }
01586         }
01587     }
01588 
01589     vlc_mutex_unlock( &p_sys->lock );
01590 
01591     if( i_stream == p_sys->i_streams )
01592     {
01593         /* Sleep so we do not consume all the cpu, 10ms seems
01594          * like a good value (100fps) */
01595         msleep( 10000 );
01596         return 1;
01597     }
01598 
01599     /*
01600      * We got our sample
01601      */
01602     i_data_size = sample.p_sample->GetActualDataLength();
01603     sample.p_sample->GetPointer( &p_data );
01604 
01605     REFERENCE_TIME i_pts, i_end_date;
01606     HRESULT hr = sample.p_sample->GetTime( &i_pts, &i_end_date );
01607     if( hr != VFW_S_NO_STOP_TIME && hr != S_OK ) i_pts = 0;
01608 
01609     if( !i_pts )
01610     {
01611         if( p_stream->mt.majortype == MEDIATYPE_Video || !p_stream->b_pts )
01612         {
01613             /* Use our data timestamp */
01614             i_pts = sample.i_timestamp;
01615             p_stream->b_pts = VLC_TRUE;
01616         }
01617     }
01618 
01619     i_pts /= 10; /* Dshow works with 100 nano-seconds resolution */
01620 
01621 #if 0
01622     msg_Dbg( p_demux, "Read() stream: %i, size: %i, PTS: "I64Fd,
01623              i_stream, i_data_size, i_pts );
01624 #endif
01625 
01626     p_block = block_New( p_demux, i_data_size );
01627     p_demux->p_vlc->pf_memcpy( p_block->p_buffer, p_data, i_data_size );
01628     p_block->i_pts = p_block->i_dts = i_pts;
01629     sample.p_sample->Release();
01630 
01631     es_out_Control( p_demux->out, ES_OUT_SET_PCR, i_pts > 0 ? i_pts : 0 );
01632     es_out_Send( p_demux->out, p_stream->p_es, p_block );
01633 
01634     return 1;
01635 }
01636 
01637 /*****************************************************************************
01638  * AccessControl:
01639  *****************************************************************************/
01640 static int AccessControl( access_t *p_access, int i_query, va_list args )
01641 {
01642     vlc_bool_t   *pb_bool;
01643     int          *pi_int;
01644     int64_t      *pi_64;
01645 
01646     switch( i_query )
01647     {
01648     /* */
01649     case ACCESS_CAN_SEEK:
01650     case ACCESS_CAN_FASTSEEK:
01651     case ACCESS_CAN_PAUSE:
01652     case ACCESS_CAN_CONTROL_PACE:
01653         pb_bool = (vlc_bool_t*)va_arg( args, vlc_bool_t* );
01654         *pb_bool = VLC_FALSE;
01655         break;
01656 
01657     /* */
01658     case ACCESS_GET_MTU:
01659         pi_int = (int*)va_arg( args, int * );
01660         *pi_int = 0;
01661         break;
01662 
01663     case ACCESS_GET_PTS_DELAY:
01664         pi_64 = (int64_t*)va_arg( args, int64_t * );
01665         *pi_64 = (int64_t)var_GetInteger( p_access, "dshow-caching" ) * 1000;
01666         break;
01667 
01668     /* */
01669     case ACCESS_SET_PAUSE_STATE:
01670     case ACCESS_GET_TITLE_INFO:
01671     case ACCESS_SET_TITLE:
01672     case ACCESS_SET_SEEKPOINT:
01673     case ACCESS_SET_PRIVATE_ID_STATE:
01674         return VLC_EGENERIC;
01675 
01676     default:
01677         msg_Warn( p_access, "unimplemented query in control" );
01678         return VLC_EGENERIC;
01679     }
01680 
01681     return VLC_SUCCESS;
01682 }
01683 
01684 /****************************************************************************
01685  * DemuxControl:
01686  ****************************************************************************/
01687 static int DemuxControl( demux_t *p_demux, int i_query, va_list args )
01688 {
01689     vlc_bool_t *pb;
01690     int64_t    *pi64;
01691 
01692     switch( i_query )
01693     {
01694     /* Special for access_demux */
01695     case DEMUX_CAN_PAUSE:
01696     case DEMUX_SET_PAUSE_STATE:
01697     case DEMUX_CAN_CONTROL_PACE:
01698         pb = (vlc_bool_t*)va_arg( args, vlc_bool_t * );
01699         *pb = VLC_FALSE;
01700         return VLC_SUCCESS;
01701 
01702     case DEMUX_GET_PTS_DELAY:
01703         pi64 = (int64_t*)va_arg( args, int64_t * );
01704         *pi64 = (int64_t)var_GetInteger( p_demux, "dshow-caching" ) * 1000;
01705         return VLC_SUCCESS;
01706 
01707     case DEMUX_GET_TIME:
01708         pi64 = (int64_t*)va_arg( args, int64_t * );
01709         *pi64 = mdate();
01710         return VLC_SUCCESS;
01711 
01712     /* TODO implement others */
01713     default:
01714         return VLC_EGENERIC;
01715     }
01716 
01717     return VLC_EGENERIC;
01718 }
01719 
01720 /*****************************************************************************
01721  * config variable callback
01722  *****************************************************************************/
01723 static int FindDevicesCallback( vlc_object_t *p_this, char const *psz_name,
01724                                vlc_value_t newval, vlc_value_t oldval, void * )
01725 {
01726     module_config_t *p_item;
01727     vlc_bool_t b_audio = VLC_FALSE;
01728     int i;
01729 
01730     p_item = config_FindConfig( p_this, psz_name );
01731     if( !p_item ) return VLC_SUCCESS;
01732 
01733     if( !strcmp( psz_name, "dshow-adev" ) ) b_audio = VLC_TRUE;
01734 
01735     /* Clear-up the current list */
01736     if( p_item->i_list )
01737     {
01738         /* Keep the 2 first entries */
01739         for( i = 2; i < p_item->i_list; i++ )
01740         {
01741             free( p_item->ppsz_list[i] );
01742             free( p_item->ppsz_list_text[i] );
01743         }
01744         /* TODO: Remove when no more needed */
01745         p_item->ppsz_list[i] = NULL;
01746         p_item->ppsz_list_text[i] = NULL;
01747     }
01748     p_item->i_list = 2;
01749 
01750     /* Find list of devices */
01751     list<string> list_devices;
01752 
01753     /* Initialize OLE/COM */
01754     CoInitialize( 0 );
01755 
01756     FindCaptureDevice( p_this, NULL, &list_devices, b_audio );
01757 
01758     /* Uninitialize OLE/COM */
01759     CoUninitialize();
01760 
01761     if( !list_devices.size() ) return VLC_SUCCESS;
01762 
01763     p_item->ppsz_list =
01764         (char **)realloc( p_item->ppsz_list,
01765                           (list_devices.size()+3) * sizeof(char *) );
01766     p_item->ppsz_list_text =
01767         (char **)realloc( p_item->ppsz_list_text,
01768                           (list_devices.size()+3) * sizeof(char *) );
01769 
01770     list<string>::iterator iter;
01771     for( iter = list_devices.begin(), i = 2; iter != list_devices.end();
01772          iter++, i++ )
01773     {
01774         p_item->ppsz_list[i] = strdup( iter->c_str() );
01775         p_item->ppsz_list_text[i] = NULL;
01776         p_item->i_list++;
01777     }
01778     p_item->ppsz_list[i] = NULL;
01779     p_item->ppsz_list_text[i] = NULL;
01780 
01781     /* Signal change to the interface */
01782     p_item->b_dirty = VLC_TRUE;
01783 
01784     return VLC_SUCCESS;
01785 }
01786 
01787 static int ConfigDevicesCallback( vlc_object_t *p_this, char const *psz_name,
01788                                vlc_value_t newval, vlc_value_t oldval, void * )
01789 {
01790     module_config_t *p_item;
01791     vlc_bool_t b_audio = VLC_FALSE;
01792 
01793     /* Initialize OLE/COM */
01794     CoInitialize( 0 );
01795 
01796     p_item = config_FindConfig( p_this, psz_name );
01797     if( !p_item ) return VLC_SUCCESS;
01798 
01799     if( !strcmp( psz_name, "dshow-adev" ) ) b_audio = VLC_TRUE;
01800 
01801     string devicename;
01802 
01803     if( newval.psz_string && *newval.psz_string )
01804     {
01805         devicename = newval.psz_string;
01806     }
01807     else
01808     {
01809         /* If no device name was specified, pick the 1st one */
01810         list<string> list_devices;
01811 
01812         /* Enumerate devices */
01813         FindCaptureDevice( p_this, NULL, &list_devices, b_audio );
01814         if( !list_devices.size() ) return VLC_EGENERIC;
01815         devicename = *list_devices.begin();
01816     }
01817 
01818     IBaseFilter *p_device_filter =
01819         FindCaptureDevice( p_this, &devicename, NULL, b_audio );
01820     if( p_device_filter )
01821     {
01822         ShowPropertyPage( p_device_filter );
01823     }
01824     else
01825     {
01826         /* Uninitialize OLE/COM */
01827         CoUninitialize();
01828 
01829         msg_Err( p_this, "didn't find device: %s", devicename.c_str() );
01830         return VLC_EGENERIC;
01831     }
01832 
01833     /* Uninitialize OLE/COM */
01834     CoUninitialize();
01835 
01836     return VLC_SUCCESS;
01837 }
01838 
01839 /*****************************************************************************
01840  * Properties
01841  *****************************************************************************/
01842 static void ShowPropertyPage( IUnknown *obj )
01843 {
01844     ISpecifyPropertyPages *p_spec;
01845     CAUUID cauuid;
01846 
01847     HRESULT hr = obj->QueryInterface( IID_ISpecifyPropertyPages,
01848                                       (void **)&p_spec );
01849     if( FAILED(hr) ) return;
01850 
01851     if( SUCCEEDED(p_spec->GetPages( &cauuid )) )
01852     {
01853         if( cauuid.cElems > 0 )
01854         {
01855             HWND hwnd_desktop = ::GetDesktopWindow();
01856 
01857             OleCreatePropertyFrame( hwnd_desktop, 30, 30, NULL, 1, &obj,
01858                                     cauuid.cElems, cauuid.pElems, 0, 0, NULL );
01859 
01860             CoTaskMemFree( cauuid.pElems );
01861         }
01862         p_spec->Release();
01863     }
01864 }
01865 
01866 static void ShowDeviceProperties( vlc_object_t *p_this,
01867                                   ICaptureGraphBuilder2 *p_graph,
01868                                   IBaseFilter *p_device_filter,
01869                                   vlc_bool_t b_audio )
01870 {
01871     HRESULT hr;
01872     msg_Dbg( p_this, "Configuring Device Properties" );
01873 
01874     /*
01875      * Video or audio capture filter page
01876      */
01877     ShowPropertyPage( p_device_filter );
01878 
01879     /*
01880      * Audio capture pin
01881      */
01882     if( p_graph && b_audio )
01883     {
01884         IAMStreamConfig *p_SC;
01885 
01886         msg_Dbg( p_this, "Showing WDM Audio Configuration Pages" );
01887 
01888         hr = p_graph->FindInterface( &PIN_CATEGORY_CAPTURE,
01889                                      &MEDIATYPE_Audio, p_device_filter,
01890                                      IID_IAMStreamConfig, (void **)&p_SC );
01891         if( SUCCEEDED(hr) )
01892         {
01893             ShowPropertyPage(p_SC);
01894             p_SC->Release();
01895         }
01896 
01897         /*
01898          * TV Audio filter
01899          */
01900         IAMTVAudio *p_TVA;
01901         HRESULT hr = p_graph->FindInterface( &PIN_CATEGORY_CAPTURE,
01902                                              &MEDIATYPE_Audio, p_device_filter,
01903                                              IID_IAMTVAudio, (void **)&p_TVA );
01904         if( SUCCEEDED(hr) )
01905         {
01906             ShowPropertyPage(p_TVA);
01907             p_TVA->Release();
01908         }
01909     }
01910 
01911     /*
01912      * Video capture pin
01913      */
01914     if( p_graph && !b_audio )
01915     {
01916         IAMStreamConfig *p_SC;
01917 
01918         msg_Dbg( p_this, "Showing WDM Video Configuration Pages" );
01919 
01920         hr = p_graph->FindInterface( &PIN_CATEGORY_CAPTURE,
01921                                      &MEDIATYPE_Interleaved, p_device_filter,
01922                                      IID_IAMStreamConfig, (void **)&p_SC );
01923         if( FAILED(hr) )
01924         {
01925             hr = p_graph->FindInterface( &PIN_CATEGORY_CAPTURE,
01926                                          &MEDIATYPE_Video, p_device_filter,
01927                                          IID_IAMStreamConfig, (void **)&p_SC );
01928         }
01929 
01930         if( FAILED(hr) )
01931         {
01932             hr = p_graph->FindInterface( &PIN_CATEGORY_CAPTURE,
01933                                          &MEDIATYPE_Stream, p_device_filter,
01934                                          IID_IAMStreamConfig, (void **)&p_SC );
01935         }
01936 
01937         if( SUCCEEDED(hr) )
01938         {
01939             ShowPropertyPage(p_SC);
01940             p_SC->Release();
01941         }
01942     }
01943 }
01944 
01945 static void ShowTunerProperties( vlc_object_t *p_this,
01946                                  ICaptureGraphBuilder2 *p_graph,
01947                                  IBaseFilter *p_device_filter,
01948                                  vlc_bool_t b_audio )
01949 {
01950     HRESULT hr;
01951     msg_Dbg( p_this, "Configuring Tuner Properties" );
01952 
01953     if( !p_graph || b_audio ) return;
01954 
01955     IAMTVTuner *p_TV;
01956     hr = p_graph->FindInterface( &PIN_CATEGORY_CAPTURE,
01957                                  &MEDIATYPE_Interleaved, p_device_filter,
01958                                  IID_IAMTVTuner, (void **)&p_TV );
01959     if( FAILED(hr) )
01960     {
01961         hr = p_graph->FindInterface( &PIN_CATEGORY_CAPTURE,
01962                                      &MEDIATYPE_Video, p_device_filter,
01963                                      IID_IAMTVTuner, (void **)&p_TV );
01964     }
01965 
01966     if( FAILED(hr) )
01967     {
01968         hr = p_graph->FindInterface( &PIN_CATEGORY_CAPTURE,
01969                                      &MEDIATYPE_Stream, p_device_filter,
01970                                      IID_IAMTVTuner, (void **)&p_TV );
01971     }
01972 
01973     if( SUCCEEDED(hr) )
01974     {
01975         ShowPropertyPage(p_TV);
01976         p_TV->Release();
01977     }
01978 }
01979 
01980 static void ConfigTuner( vlc_object_t *p_this, ICaptureGraphBuilder2 *p_graph,
01981                          IBaseFilter *p_device_filter )
01982 {
01983     int i_channel, i_country, i_input;
01984     long l_modes = 0;
01985     IAMTVTuner *p_TV;
01986     HRESULT hr;
01987 
01988     if( !p_graph ) return;
01989 
01990     i_channel = var_GetInteger( p_this, "dshow-tuner-channel" );
01991     i_country = var_GetInteger( p_this, "dshow-tuner-country" );
01992     i_input = var_GetInteger( p_this, "dshow-tuner-input" );
01993 
01994     if( !i_channel && !i_country && !i_input ) return; /* Nothing to do */
01995 
01996     msg_Dbg( p_this, "tuner config: channel %i, country %i, input type %i",
01997              i_channel, i_country, i_input );
01998 
01999     hr = p_graph->FindInterface( &PIN_CATEGORY_CAPTURE, &MEDIATYPE_Interleaved,
02000                                  p_device_filter, IID_IAMTVTuner,
02001                                  (void **)&p_TV );
02002     if( FAILED(hr) )
02003     {
02004         hr = p_graph->FindInterface( &PIN_CATEGORY_CAPTURE, &MEDIATYPE_Video,
02005                                      p_device_filter, IID_IAMTVTuner,
02006                                      (void **)&p_TV );
02007     }
02008 
02009     if( FAILED(hr) )
02010     {
02011         hr = p_graph->FindInterface( &PIN_CATEGORY_CAPTURE, &MEDIATYPE_Stream,
02012                                      p_device_filter, IID_IAMTVTuner,
02013                                      (void **)&p_TV );
02014     }
02015 
02016     if( FAILED(hr) )
02017     {
02018         msg_Dbg( p_this, "couldn't find tuner interface" );
02019         return;
02020     }
02021 
02022     hr = p_TV->GetAvailableModes( &l_modes );
02023     if( SUCCEEDED(hr) && (l_modes & AMTUNER_MODE_TV) )
02024     {
02025         hr = p_TV->put_Mode( AMTUNER_MODE_TV );
02026     }
02027 
02028     if( i_input == 1 ) p_TV->put_InputType( 0, TunerInputCable );
02029     else if( i_input == 2 ) p_TV->put_InputType( 0, TunerInputAntenna );
02030 
02031     p_TV->put_CountryCode( i_country );
02032     p_TV->put_Channel( i_channel, AMTUNER_SUBCHAN_NO_TUNE,
02033                        AMTUNER_SUBCHAN_NO_TUNE );
02034     p_TV->Release();
02035 }

Generated on Tue Dec 20 10:14:24 2005 for vlc-0.8.4a by  doxygen 1.4.2