dshow.cpp
上传用户:kjfoods
上传日期:2020-07-06
资源大小:29949k
文件大小:83k
源码类别:

midi

开发平台:

Unix_Linux

  1. /*****************************************************************************
  2.  * dshow.cpp : DirectShow access module for vlc
  3.  *****************************************************************************
  4.  * Copyright (C) 2002, 2003 the VideoLAN team
  5.  * $Id: 3119bbc9ae528a83fd2adedf79b5108e174323bb $
  6.  *
  7.  * Author: Gildas Bazin <gbazin@videolan.org>
  8.  *         Damien Fouilleul <damienf@videolan.org>
  9.  *
  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.
  14.  *
  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.
  19.  *
  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.  *****************************************************************************/
  24. /*****************************************************************************
  25.  * Preamble
  26.  *****************************************************************************/
  27. #ifdef HAVE_CONFIG_H
  28. # include "config.h"
  29. #endif
  30. #define __STDC_FORMAT_MACROS 1
  31. #include <inttypes.h>
  32. #include <vlc_common.h>
  33. #include <vlc_plugin.h>
  34. #include <vlc_input.h>
  35. #include <vlc_access.h>
  36. #include <vlc_demux.h>
  37. #include <vlc_vout.h>
  38. #include <vlc_dialog.h>
  39. #include <vlc_charset.h>
  40. #include "common.h"
  41. #include "filter.h"
  42. /*****************************************************************************
  43.  * Access: local prototypes
  44.  *****************************************************************************/
  45. static block_t *ReadCompressed( access_t * );
  46. static int AccessControl ( access_t *, int, va_list );
  47. static int Demux       ( demux_t * );
  48. static int DemuxControl( demux_t *, int, va_list );
  49. static int OpenDevice( vlc_object_t *, access_sys_t *, string, bool );
  50. static IBaseFilter *FindCaptureDevice( vlc_object_t *, string *,
  51.                                        list<string> *, bool );
  52. static size_t EnumDeviceCaps( vlc_object_t *, IBaseFilter *,
  53.                               int, int, int, int, int, int,
  54.                               AM_MEDIA_TYPE *mt, size_t );
  55. static bool ConnectFilters( vlc_object_t *, access_sys_t *,
  56.                             IBaseFilter *, CaptureFilter * );
  57. static int FindDevicesCallback( vlc_object_t *, char const *,
  58.                                 vlc_value_t, vlc_value_t, void * );
  59. static int ConfigDevicesCallback( vlc_object_t *, char const *,
  60.                                   vlc_value_t, vlc_value_t, void * );
  61. static void ShowPropertyPage( IUnknown * );
  62. static void ShowDeviceProperties( vlc_object_t *, ICaptureGraphBuilder2 *,
  63.                                   IBaseFilter *, bool );
  64. static void ShowTunerProperties( vlc_object_t *, ICaptureGraphBuilder2 *,
  65.                                  IBaseFilter *, bool );
  66. static void ConfigTuner( vlc_object_t *, ICaptureGraphBuilder2 *,
  67.                          IBaseFilter * );
  68. /*****************************************************************************
  69.  * Module descriptor
  70.  *****************************************************************************/
  71. static const char *const ppsz_vdev[] = { "", "none" };
  72. static const char *const ppsz_vdev_text[] = { N_("Default"), N_("None") };
  73. static const char *const ppsz_adev[] = { "", "none" };
  74. static const char *const ppsz_adev_text[] = { N_("Default"), N_("None") };
  75. static const int pi_tuner_input[] = { 0, 1, 2 };
  76. static const char *const ppsz_tuner_input_text[] =
  77.     {N_("Default"), N_("Cable"), N_("Antenna")};
  78. static const int pi_amtuner_mode[]  = { AMTUNER_MODE_DEFAULT,
  79.                                  AMTUNER_MODE_TV,
  80.                                  AMTUNER_MODE_FM_RADIO,
  81.                                  AMTUNER_MODE_AM_RADIO,
  82.                                  AMTUNER_MODE_DSS };
  83. static const char *const ppsz_amtuner_mode_text[] = { N_("Default"),
  84.                                           N_("TV"),
  85.                                           N_("FM radio"),
  86.                                           N_("AM radio"),
  87.                                           N_("DSS") };
  88. #define CACHING_TEXT N_("Caching value in ms")
  89. #define CACHING_LONGTEXT N_( 
  90.     "Caching value for DirectShow streams. " 
  91.     "This value should be set in milliseconds." )
  92. #define VDEV_TEXT N_("Video device name")
  93. #define VDEV_LONGTEXT N_( 
  94.     "Name of the video device that will be used by the " 
  95.     "DirectShow plugin. If you don't specify anything, the default device " 
  96.     "will be used.")
  97. #define ADEV_TEXT N_("Audio device name")
  98. #define ADEV_LONGTEXT N_( 
  99.     "Name of the audio device that will be used by the " 
  100.     "DirectShow plugin. If you don't specify anything, the default device " 
  101.     "will be used. ")
  102. #define SIZE_TEXT N_("Video size")
  103. #define SIZE_LONGTEXT N_( 
  104.     "Size of the video that will be displayed by the " 
  105.     "DirectShow plugin. If you don't specify anything the default size for " 
  106.     "your device will be used. You can specify a standard size (cif, d1, ...) or <width>x<height>.")
  107. #define CHROMA_TEXT N_("Video input chroma format")
  108. #define CHROMA_LONGTEXT N_( 
  109.     "Force the DirectShow video input to use a specific chroma format " 
  110.     "(eg. I420 (default), RV24, etc.)")
  111. #define FPS_TEXT N_("Video input frame rate")
  112. #define FPS_LONGTEXT N_( 
  113.     "Force the DirectShow video input to use a specific frame rate" 
  114.     "(eg. 0 means default, 25, 29.97, 50, 59.94, etc.)")
  115. #define CONFIG_TEXT N_("Device properties")
  116. #define CONFIG_LONGTEXT N_( 
  117.     "Show the properties dialog of the selected device before starting the " 
  118.     "stream.")
  119. #define TUNER_TEXT N_("Tuner properties")
  120. #define TUNER_LONGTEXT N_( 
  121.     "Show the tuner properties [channel selection] page." )
  122. #define CHANNEL_TEXT N_("Tuner TV Channel")
  123. #define CHANNEL_LONGTEXT N_( 
  124.     "Set the TV channel the tuner will set to " 
  125.     "(0 means default)." )
  126. #define COUNTRY_TEXT N_("Tuner country code")
  127. #define COUNTRY_LONGTEXT N_( 
  128.     "Set the tuner country code that establishes the current " 
  129.     "channel-to-frequency mapping (0 means default)." )
  130. #define TUNER_INPUT_TEXT N_("Tuner input type")
  131. #define TUNER_INPUT_LONGTEXT N_( 
  132.     "Select the tuner input type (Cable/Antenna)." )
  133. #define VIDEO_IN_TEXT N_("Video input pin")
  134. #define VIDEO_IN_LONGTEXT N_( 
  135.   "Select the video input source, such as composite, s-video, " 
  136.   "or tuner. Since these settings are hardware-specific, you should find good " 
  137.   "settings in the "Device config" area, and use those numbers here. -1 " 
  138.   "means that settings will not be changed.")
  139. #define AUDIO_IN_TEXT N_("Audio input pin")
  140. #define AUDIO_IN_LONGTEXT N_( 
  141.   "Select the audio input source. See the "video input" option." )
  142. #define VIDEO_OUT_TEXT N_("Video output pin")
  143. #define VIDEO_OUT_LONGTEXT N_( 
  144.   "Select the video output type. See the "video input" option." )
  145. #define AUDIO_OUT_TEXT N_("Audio output pin")
  146. #define AUDIO_OUT_LONGTEXT N_( 
  147.   "Select the audio output type. See the "video input" option." )
  148. #define AMTUNER_MODE_TEXT N_("AM Tuner mode")
  149. #define AMTUNER_MODE_LONGTEXT N_( 
  150.     "AM Tuner mode. Can be one of Default (0), TV (1)," 
  151.      "AM Radio (2), FM Radio (3) or DSS (4).")
  152. #define AUDIO_CHANNELS_TEXT N_("Number of audio channels")
  153. #define AUDIO_CHANNELS_LONGTEXT N_( 
  154.     "Select audio input format with the given number of audio channels (if non 0)" )
  155. #define AUDIO_SAMPLERATE_TEXT N_("Audio sample rate")
  156. #define AUDIO_SAMPLERATE_LONGTEXT N_( 
  157.     "Select audio input format with the given sample rate (if non 0)" )
  158. #define AUDIO_BITSPERSAMPLE_TEXT N_("Audio bits per sample")
  159. #define AUDIO_BITSPERSAMPLE_LONGTEXT N_( 
  160.     "Select audio input format with the given bits/sample (if non 0)" )
  161. static int  CommonOpen ( vlc_object_t *, access_sys_t *, bool );
  162. static void CommonClose( vlc_object_t *, access_sys_t * );
  163. static int  AccessOpen ( vlc_object_t * );
  164. static void AccessClose( vlc_object_t * );
  165. static int  DemuxOpen  ( vlc_object_t * );
  166. static void DemuxClose ( vlc_object_t * );
  167. vlc_module_begin ()
  168.     set_shortname( N_("DirectShow") )
  169.     set_description( N_("DirectShow input") )
  170.     set_category( CAT_INPUT )
  171.     set_subcategory( SUBCAT_INPUT_ACCESS )
  172.     add_integer( "dshow-caching", (mtime_t)(0.2*CLOCK_FREQ) / 1000, NULL,
  173.                  CACHING_TEXT, CACHING_LONGTEXT, true )
  174.     add_string( "dshow-vdev", NULL, NULL, VDEV_TEXT, VDEV_LONGTEXT, false)
  175.         change_string_list( ppsz_vdev, ppsz_vdev_text, FindDevicesCallback )
  176.         change_action_add( FindDevicesCallback, N_("Refresh list") )
  177.         change_action_add( ConfigDevicesCallback, N_("Configure") )
  178.     add_string( "dshow-adev", NULL, NULL, ADEV_TEXT, ADEV_LONGTEXT, false)
  179.         change_string_list( ppsz_adev, ppsz_adev_text, FindDevicesCallback )
  180.         change_action_add( FindDevicesCallback, N_("Refresh list") )
  181.         change_action_add( ConfigDevicesCallback, N_("Configure") )
  182.     add_string( "dshow-size", NULL, NULL, SIZE_TEXT, SIZE_LONGTEXT, false)
  183.     add_string( "dshow-chroma", NULL, NULL, CHROMA_TEXT, CHROMA_LONGTEXT, true )
  184.     add_float( "dshow-fps", 0.0f, NULL, FPS_TEXT, FPS_LONGTEXT, true )
  185.     add_bool( "dshow-config", false, NULL, CONFIG_TEXT, CONFIG_LONGTEXT, true )
  186.     add_bool( "dshow-tuner", false, NULL, TUNER_TEXT, TUNER_LONGTEXT, true )
  187.     add_integer( "dshow-tuner-channel", 0, NULL, CHANNEL_TEXT, CHANNEL_LONGTEXT,
  188.                 true )
  189.     add_integer( "dshow-tuner-country", 0, NULL, COUNTRY_TEXT, COUNTRY_LONGTEXT,
  190.                 true )
  191.     add_integer( "dshow-tuner-input", 0, NULL, TUNER_INPUT_TEXT,
  192.                  TUNER_INPUT_LONGTEXT, true )
  193.         change_integer_list( pi_tuner_input, ppsz_tuner_input_text, NULL )
  194.     add_integer( "dshow-video-input",  -1, NULL, VIDEO_IN_TEXT,
  195.                  VIDEO_IN_LONGTEXT, true )
  196.     add_integer( "dshow-video-output", -1, NULL, VIDEO_OUT_TEXT,
  197.                  VIDEO_OUT_LONGTEXT, true )
  198.     add_integer( "dshow-audio-input",  -1, NULL, AUDIO_IN_TEXT,
  199.                  AUDIO_IN_LONGTEXT, true )
  200.     add_integer( "dshow-audio-output", -1, NULL, AUDIO_OUT_TEXT,
  201.                  AUDIO_OUT_LONGTEXT, true )
  202.     add_integer( "dshow-amtuner-mode", AMTUNER_MODE_TV, NULL,
  203.                 AMTUNER_MODE_TEXT, AMTUNER_MODE_LONGTEXT, false)
  204.         change_integer_list( pi_amtuner_mode, ppsz_amtuner_mode_text, NULL )
  205.     add_integer( "dshow-audio-channels", 0, NULL, AUDIO_CHANNELS_TEXT,
  206.                  AUDIO_CHANNELS_LONGTEXT, true )
  207.     add_integer( "dshow-audio-samplerate", 0, NULL, AUDIO_SAMPLERATE_TEXT,
  208.                  AUDIO_SAMPLERATE_LONGTEXT, true )
  209.     add_integer( "dshow-audio-bitspersample", 0, NULL, AUDIO_BITSPERSAMPLE_TEXT,
  210.                  AUDIO_BITSPERSAMPLE_LONGTEXT, true )
  211.     add_shortcut( "dshow" )
  212.     set_capability( "access_demux", 0 )
  213.     set_callbacks( DemuxOpen, DemuxClose )
  214.     add_submodule ()
  215.     set_description( N_("DirectShow input") )
  216.     add_shortcut( "dshow" )
  217.     set_capability( "access", 0 )
  218.     set_callbacks( AccessOpen, AccessClose )
  219. vlc_module_end ()
  220. /*****************************************************************************
  221.  * DirectShow elementary stream descriptor
  222.  *****************************************************************************/
  223. typedef struct dshow_stream_t
  224. {
  225.     string          devicename;
  226.     IBaseFilter     *p_device_filter;
  227.     CaptureFilter   *p_capture_filter;
  228.     AM_MEDIA_TYPE   mt;
  229.     union
  230.     {
  231.       VIDEOINFOHEADER video;
  232.       WAVEFORMATEX    audio;
  233.     } header;
  234.     int             i_fourcc;
  235.     es_out_id_t     *p_es;
  236.     bool      b_pts;
  237.     deque<VLCMediaSample> samples_queue;
  238. } dshow_stream_t;
  239. /*****************************************************************************
  240.  * DirectShow utility functions
  241.  *****************************************************************************/
  242. static void CreateDirectShowGraph( access_sys_t *p_sys )
  243. {
  244.     p_sys->i_crossbar_route_depth = 0;
  245.     /* Create directshow filter graph */
  246.     if( SUCCEEDED( CoCreateInstance( CLSID_FilterGraph, 0, CLSCTX_INPROC,
  247.                        (REFIID)IID_IFilterGraph, (void **)&p_sys->p_graph) ) )
  248.     {
  249.         /* Create directshow capture graph builder if available */
  250.         if( SUCCEEDED( CoCreateInstance( CLSID_CaptureGraphBuilder2, 0,
  251.                          CLSCTX_INPROC, (REFIID)IID_ICaptureGraphBuilder2,
  252.                          (void **)&p_sys->p_capture_graph_builder2 ) ) )
  253.         {
  254.             p_sys->p_capture_graph_builder2->
  255.                 SetFiltergraph((IGraphBuilder *)p_sys->p_graph);
  256.         }
  257.         p_sys->p_graph->QueryInterface( IID_IMediaControl,
  258.                                         (void **)&p_sys->p_control );
  259.     }
  260. }
  261. static void DeleteDirectShowGraph( access_sys_t *p_sys )
  262. {
  263.     DeleteCrossbarRoutes( p_sys );
  264.     /* Remove filters from graph */
  265.     for( int i = 0; i < p_sys->i_streams; i++ )
  266.     {
  267.         p_sys->p_graph->RemoveFilter( p_sys->pp_streams[i]->p_capture_filter );
  268.         p_sys->p_graph->RemoveFilter( p_sys->pp_streams[i]->p_device_filter );
  269.         p_sys->pp_streams[i]->p_capture_filter->Release();
  270.         p_sys->pp_streams[i]->p_device_filter->Release();
  271.     }
  272.     /* Release directshow objects */
  273.     if( p_sys->p_control )
  274.     {
  275.         p_sys->p_control->Release();
  276.         p_sys->p_control = NULL;
  277.     }
  278.     if( p_sys->p_capture_graph_builder2 )
  279.     {
  280.         p_sys->p_capture_graph_builder2->Release();
  281.         p_sys->p_capture_graph_builder2 = NULL;
  282.     }
  283.     if( p_sys->p_graph )
  284.     {
  285.         p_sys->p_graph->Release();
  286.         p_sys->p_graph = NULL;
  287.     }
  288. }
  289. /*****************************************************************************
  290.  * CommonOpen: open direct show device
  291.  *****************************************************************************/
  292. static int CommonOpen( vlc_object_t *p_this, access_sys_t *p_sys,
  293.                        bool b_access_demux )
  294. {
  295.     vlc_value_t  val;
  296.     int i;
  297.     /* Get/parse options and open device(s) */
  298.     string vdevname, adevname;
  299.     int i_width = 0, i_height = 0, i_chroma = 0;
  300.     bool b_use_audio = true;
  301.     bool b_use_video = true;
  302.     /* Initialize OLE/COM */
  303.     CoInitialize( 0 );
  304.     var_Create( p_this, "dshow-config", VLC_VAR_BOOL | VLC_VAR_DOINHERIT );
  305.     var_Create( p_this, "dshow-tuner", VLC_VAR_BOOL | VLC_VAR_DOINHERIT );
  306.     var_Create( p_this, "dshow-vdev", VLC_VAR_STRING | VLC_VAR_DOINHERIT );
  307.     var_Get( p_this, "dshow-vdev", &val );
  308.     if( val.psz_string )
  309.     {
  310.         msg_Dbg( p_this, "dshow-vdev: %s", val.psz_string ) ;
  311.         /* skip none device */
  312.         if ( strncasecmp( val.psz_string, "none", 4 ) != 0 )
  313.             vdevname = string( val.psz_string );
  314.         else
  315.             b_use_video = false ;
  316.     }
  317.     free( val.psz_string );
  318.     var_Create( p_this, "dshow-adev", VLC_VAR_STRING | VLC_VAR_DOINHERIT );
  319.     var_Get( p_this, "dshow-adev", &val );
  320.     if( val.psz_string )
  321.     {
  322.         msg_Dbg( p_this, "dshow-adev: %s", val.psz_string ) ;
  323.         /* skip none device */
  324.         if ( strncasecmp( val.psz_string, "none", 4 ) != 0 )
  325.             adevname = string( val.psz_string );
  326.         else
  327.             b_use_audio = false ;
  328.     }
  329.     free( val.psz_string );
  330.     static struct {const char *psz_size; int  i_width; int  i_height;} size_table[] =
  331.     { { "subqcif", 128, 96 }, { "qsif", 160, 120 }, { "qcif", 176, 144 },
  332.       { "sif", 320, 240 }, { "cif", 352, 288 }, { "d1", 640, 480 },
  333.       { 0, 0, 0 },
  334.     };
  335.     var_Create( p_this, "dshow-size", VLC_VAR_STRING | VLC_VAR_DOINHERIT );
  336.     var_Get( p_this, "dshow-size", &val );
  337.     if( val.psz_string && *val.psz_string )
  338.     {
  339.         for( i = 0; size_table[i].psz_size; i++ )
  340.         {
  341.             if( !strcmp( val.psz_string, size_table[i].psz_size ) )
  342.             {
  343.                 i_width = size_table[i].i_width;
  344.                 i_height = size_table[i].i_height;
  345.                 break;
  346.             }
  347.         }
  348.         if( !size_table[i].psz_size ) /* Try to parse "WidthxHeight" */
  349.         {
  350.             char *psz_parser;
  351.             i_width = strtol( val.psz_string, &psz_parser, 0 );
  352.             if( *psz_parser == 'x' || *psz_parser == 'X')
  353.             {
  354.                 i_height = strtol( psz_parser + 1, &psz_parser, 0 );
  355.             }
  356.             msg_Dbg( p_this, "width x height %dx%d", i_width, i_height );
  357.         }
  358.     }
  359.     free( val.psz_string );
  360.     p_sys->b_chroma = false;
  361.     var_Create( p_this, "dshow-chroma", VLC_VAR_STRING | VLC_VAR_DOINHERIT );
  362.     var_Get( p_this, "dshow-chroma", &val );
  363.     if( val.psz_string && strlen( val.psz_string ) >= 4 )
  364.     {
  365.         i_chroma = VLC_FOURCC( val.psz_string[0], val.psz_string[1],
  366.                                val.psz_string[2], val.psz_string[3] );
  367.         p_sys->b_chroma = true;
  368.     }
  369.     free( val.psz_string );
  370.     var_Create( p_this, "dshow-fps", VLC_VAR_FLOAT | VLC_VAR_DOINHERIT );
  371.     var_Create( p_this, "dshow-tuner-channel",
  372.                 VLC_VAR_INTEGER | VLC_VAR_DOINHERIT );
  373.     var_Create( p_this, "dshow-tuner-country",
  374.                 VLC_VAR_INTEGER | VLC_VAR_DOINHERIT );
  375.     var_Create( p_this, "dshow-tuner-input",
  376.                 VLC_VAR_INTEGER | VLC_VAR_DOINHERIT );
  377.     var_Create( p_this, "dshow-amtuner-mode",
  378.                 VLC_VAR_INTEGER | VLC_VAR_DOINHERIT );
  379.     var_Create( p_this, "dshow-caching", VLC_VAR_INTEGER | VLC_VAR_DOINHERIT );
  380.     var_Create( p_this, "dshow-video-input", VLC_VAR_INTEGER | VLC_VAR_DOINHERIT );
  381.     var_Create( p_this, "dshow-audio-input", VLC_VAR_INTEGER | VLC_VAR_DOINHERIT );
  382.     var_Create( p_this, "dshow-video-output", VLC_VAR_INTEGER | VLC_VAR_DOINHERIT );
  383.     var_Create( p_this, "dshow-audio-output", VLC_VAR_INTEGER | VLC_VAR_DOINHERIT );
  384.     /* Initialize some data */
  385.     p_sys->i_streams = 0;
  386.     p_sys->pp_streams = NULL;
  387.     p_sys->i_width = i_width;
  388.     p_sys->i_height = i_height;
  389.     p_sys->i_chroma = i_chroma;
  390.     p_sys->p_graph = NULL;
  391.     p_sys->p_capture_graph_builder2 = NULL;
  392.     p_sys->p_control = NULL;
  393.     /* Build directshow graph */
  394.     CreateDirectShowGraph( p_sys );
  395.     vlc_mutex_init( &p_sys->lock );
  396.     vlc_cond_init( &p_sys->wait );
  397.     if( !b_use_video && !b_use_audio )
  398.     {
  399.         dialog_Fatal( p_this, _("Capture failed"),
  400.                         _("No video or audio device selected.") );
  401.         return VLC_EGENERIC ;
  402.     }
  403.     if( !b_use_video )
  404.         msg_Dbg( p_this, "skipping video device" ) ;
  405.     bool b_err_video = false ;
  406.     if( b_use_video && OpenDevice( p_this, p_sys, vdevname, 0 ) != VLC_SUCCESS )
  407.     {
  408.         msg_Err( p_this, "can't open video device");
  409.         b_err_video = true ;
  410.     }
  411.     if ( b_use_video && !b_err_video )
  412.     {
  413.         /* Check if we can handle the demuxing ourselves or need to spawn
  414.          * a demuxer module */
  415.         dshow_stream_t *p_stream = p_sys->pp_streams[p_sys->i_streams-1];
  416.         if( p_stream->mt.majortype == MEDIATYPE_Video )
  417.         {
  418.             if( /* Raw DV stream */
  419.                 p_stream->i_fourcc == VLC_FOURCC('d','v','s','l') ||
  420.                 p_stream->i_fourcc == VLC_FOURCC('d','v','s','d') ||
  421.                 p_stream->i_fourcc == VLC_FOURCC('d','v','h','d') ||
  422.                 /* Raw MPEG video stream */
  423.                 p_stream->i_fourcc == VLC_FOURCC('m','p','2','v') )
  424.             {
  425.                 b_use_audio = false;
  426.                 if( b_access_demux )
  427.                 {
  428.                     /* Let the access (only) take care of that */
  429.                     return VLC_EGENERIC;
  430.                 }
  431.             }
  432.         }
  433.         if( p_stream->mt.majortype == MEDIATYPE_Stream )
  434.         {
  435.             b_use_audio = false;
  436.             if( b_access_demux )
  437.             {
  438.                 /* Let the access (only) take care of that */
  439.                 return VLC_EGENERIC;
  440.             }
  441.             var_Get( p_this, "dshow-tuner", &val );
  442.             if( val.b_bool )
  443.             {
  444.                 /* FIXME: we do MEDIATYPE_Stream here so we don't do
  445.                  * it twice. */
  446.                 ShowTunerProperties( p_this, p_sys->p_capture_graph_builder2,
  447.                                      p_stream->p_device_filter, 0 );
  448.             }
  449.         }
  450.     }
  451.     if( !b_use_audio )
  452.         msg_Dbg( p_this, "skipping audio device") ;
  453.     bool b_err_audio = false ;
  454.     if( b_use_audio && OpenDevice( p_this, p_sys, adevname, 1 ) != VLC_SUCCESS )
  455.     {
  456.         msg_Err( p_this, "can't open audio device");
  457.         b_err_audio = true ;
  458.     }
  459.     if( ( b_use_video && b_err_video && b_use_audio && b_err_audio ) ||
  460.         ( !b_use_video && b_use_audio && b_err_audio ) ||
  461.         ( b_use_video && !b_use_audio && b_err_video ) )
  462.     {
  463.         msg_Err( p_this, "FATAL: could not open ANY device" ) ;
  464.         dialog_Fatal( p_this,  _("Capture failed"),
  465.                         _("VLC cannot open ANY capture device."
  466.                           "Check the error log for details.") );
  467.         return VLC_EGENERIC ;
  468.     }
  469.     for( i = p_sys->i_crossbar_route_depth-1; i >= 0 ; --i )
  470.     {
  471.             var_Get( p_this, "dshow-video-input", &val );
  472.             if( val.i_int >= 0 )
  473.                     p_sys->crossbar_routes[i].VideoInputIndex=val.i_int;
  474.             var_Get( p_this, "dshow-video-output", &val );
  475.             if( val.i_int >= 0 )
  476.                     p_sys->crossbar_routes[i].VideoOutputIndex=val.i_int;
  477.             var_Get( p_this, "dshow-audio-input", &val );
  478.             if( val.i_int >= 0 )
  479.                     p_sys->crossbar_routes[i].AudioInputIndex=val.i_int;
  480.             var_Get( p_this, "dshow-audio-output", &val );
  481.             if( val.i_int >= 0 )
  482.                     p_sys->crossbar_routes[i].AudioOutputIndex=val.i_int;
  483.         IAMCrossbar *pXbar = p_sys->crossbar_routes[i].pXbar;
  484.         LONG VideoInputIndex = p_sys->crossbar_routes[i].VideoInputIndex;
  485.         LONG VideoOutputIndex = p_sys->crossbar_routes[i].VideoOutputIndex;
  486.         LONG AudioInputIndex = p_sys->crossbar_routes[i].AudioInputIndex;
  487.         LONG AudioOutputIndex = p_sys->crossbar_routes[i].AudioOutputIndex;
  488.         if( SUCCEEDED(pXbar->Route(VideoOutputIndex, VideoInputIndex)) )
  489.         {
  490.             msg_Dbg( p_this, "crossbar at depth %d, routed video "
  491.                      "output %ld to video input %ld", i, VideoOutputIndex,
  492.                      VideoInputIndex );
  493.             if( AudioOutputIndex != -1 && AudioInputIndex != -1 )
  494.             {
  495.                 if( SUCCEEDED( pXbar->Route(AudioOutputIndex,
  496.                                             AudioInputIndex)) )
  497.                 {
  498.                     msg_Dbg(p_this, "crossbar at depth %d, routed audio "
  499.                             "output %ld to audio input %ld", i,
  500.                             AudioOutputIndex, AudioInputIndex );
  501.                 }
  502.             }
  503.         }
  504.         else
  505.             msg_Err( p_this, "crossbar at depth %d could not route video "
  506.                      "output %ld to input %ld", i, VideoOutputIndex, VideoInputIndex );
  507.     }
  508.     /*
  509.     ** Show properties pages from other filters in graph
  510.     */
  511.     var_Get( p_this, "dshow-config", &val );
  512.     if( val.b_bool )
  513.     {
  514.         for( i = p_sys->i_crossbar_route_depth-1; i >= 0 ; --i )
  515.         {
  516.             IAMCrossbar *pXbar = p_sys->crossbar_routes[i].pXbar;
  517.             IBaseFilter *p_XF;
  518.             if( SUCCEEDED( pXbar->QueryInterface( IID_IBaseFilter,
  519.                                                   (void **)&p_XF ) ) )
  520.             {
  521.                 ShowPropertyPage( p_XF );
  522.                 p_XF->Release();
  523.             }
  524.         }
  525.     }
  526.     /* Initialize some data */
  527.     p_sys->i_current_stream = 0;
  528.     if( !p_sys->i_streams ) return VLC_EGENERIC;
  529.     return VLC_SUCCESS;
  530. }
  531. /*****************************************************************************
  532.  * DemuxOpen: open direct show device as an access_demux module
  533.  *****************************************************************************/
  534. static int DemuxOpen( vlc_object_t *p_this )
  535. {
  536.     demux_t      *p_demux = (demux_t *)p_this;
  537.     access_sys_t *p_sys;
  538.     int i;
  539.     p_sys = (access_sys_t*)calloc( 1, sizeof( access_sys_t ) );
  540.     if( !p_sys )
  541.         return VLC_ENOMEM;
  542.     p_demux->p_sys = (demux_sys_t *)p_sys;
  543.     if( CommonOpen( p_this, p_sys, true ) != VLC_SUCCESS )
  544.     {
  545.         CommonClose( p_this, p_sys );
  546.         return VLC_EGENERIC;
  547.     }
  548.     /* Everything is ready. Let's rock baby */
  549.     msg_Dbg( p_this, "Playing...");
  550.     p_sys->p_control->Run();
  551.     p_demux->pf_demux   = Demux;
  552.     p_demux->pf_control = DemuxControl;
  553.     p_demux->info.i_update = 0;
  554.     p_demux->info.i_title = 0;
  555.     p_demux->info.i_seekpoint = 0;
  556.     for( i = 0; i < p_sys->i_streams; i++ )
  557.     {
  558.         dshow_stream_t *p_stream = p_sys->pp_streams[i];
  559.         es_format_t fmt;
  560.         if( p_stream->mt.majortype == MEDIATYPE_Video )
  561.         {
  562.             es_format_Init( &fmt, VIDEO_ES, p_stream->i_fourcc );
  563.             fmt.video.i_width  = p_stream->header.video.bmiHeader.biWidth;
  564.             fmt.video.i_height = p_stream->header.video.bmiHeader.biHeight;
  565.             fmt.video.i_aspect = 4 * VOUT_ASPECT_FACTOR / 3;
  566.             if( !p_stream->header.video.bmiHeader.biCompression )
  567.             {
  568.                 /* RGB DIB are coded from bottom to top */
  569.                 fmt.video.i_height = (unsigned int)(-(int)fmt.video.i_height);
  570.             }
  571.             /* Setup rgb mask for RGB formats */
  572.             if( p_stream->i_fourcc == VLC_FOURCC('R','V','2','4') )
  573.             {
  574.                 /* This is in BGR format */
  575.                 fmt.video.i_bmask = 0x00ff0000;
  576.                 fmt.video.i_gmask = 0x0000ff00;
  577.                 fmt.video.i_rmask = 0x000000ff;
  578.             }
  579.             if( p_stream->header.video.AvgTimePerFrame )
  580.             {
  581.                 fmt.video.i_frame_rate = 10000000;
  582.                 fmt.video.i_frame_rate_base =
  583.                     p_stream->header.video.AvgTimePerFrame;
  584.             }
  585.         }
  586.         else if( p_stream->mt.majortype == MEDIATYPE_Audio )
  587.         {
  588.             es_format_Init( &fmt, AUDIO_ES, p_stream->i_fourcc );
  589.             fmt.audio.i_channels = p_stream->header.audio.nChannels;
  590.             fmt.audio.i_rate = p_stream->header.audio.nSamplesPerSec;
  591.             fmt.audio.i_bitspersample = p_stream->header.audio.wBitsPerSample;
  592.             fmt.audio.i_blockalign = fmt.audio.i_channels *
  593.                 fmt.audio.i_bitspersample / 8;
  594.             fmt.i_bitrate = fmt.audio.i_channels * fmt.audio.i_rate *
  595.                 fmt.audio.i_bitspersample;
  596.         }
  597.         p_stream->p_es = es_out_Add( p_demux->out, &fmt );
  598.     }
  599.     return VLC_SUCCESS;
  600. }
  601. /*****************************************************************************
  602.  * AccessOpen: open direct show device as an access module
  603.  *****************************************************************************/
  604. static int AccessOpen( vlc_object_t *p_this )
  605. {
  606.     access_t     *p_access = (access_t*)p_this;
  607.     access_sys_t *p_sys;
  608.     p_access->p_sys = p_sys = (access_sys_t*)calloc( 1, sizeof( access_sys_t ) );
  609.     if( !p_sys )
  610.         return VLC_ENOMEM;
  611.     if( CommonOpen( p_this, p_sys, false ) != VLC_SUCCESS )
  612.     {
  613.         CommonClose( p_this, p_sys );
  614.         return VLC_EGENERIC;
  615.     }
  616.     dshow_stream_t *p_stream = p_sys->pp_streams[0];
  617.     /* Check if we need to force demuxers */
  618.     if( !p_access->psz_demux || !*p_access->psz_demux )
  619.     {
  620.         if( p_stream->i_fourcc == VLC_FOURCC('d','v','s','l') ||
  621.             p_stream->i_fourcc == VLC_FOURCC('d','v','s','d') ||
  622.             p_stream->i_fourcc == VLC_FOURCC('d','v','h','d') )
  623.         {
  624.             free( p_access->psz_demux );
  625.             p_access->psz_demux = strdup( "rawdv" );
  626.         }
  627.         else if( p_stream->i_fourcc == VLC_FOURCC('m','p','2','v') )
  628.         {
  629.             free( p_access->psz_demux );
  630.             p_access->psz_demux = strdup( "mpgv" );
  631.         }
  632.     }
  633.     /* Setup Access */
  634.     p_access->pf_read = NULL;
  635.     p_access->pf_block = ReadCompressed;
  636.     p_access->pf_control = AccessControl;
  637.     p_access->pf_seek = NULL;
  638.     p_access->info.i_update = 0;
  639.     p_access->info.i_size = 0;
  640.     p_access->info.i_pos = 0;
  641.     p_access->info.b_eof = false;
  642.     p_access->info.i_title = 0;
  643.     p_access->info.i_seekpoint = 0;
  644.     p_access->p_sys = p_sys;
  645.     /* Everything is ready. Let's rock baby */
  646.     msg_Dbg( p_this, "Playing...");
  647.     p_sys->p_control->Run();
  648.     return VLC_SUCCESS;
  649. }
  650. /*****************************************************************************
  651.  * CommonClose: close device
  652.  *****************************************************************************/
  653. static void CommonClose( vlc_object_t *p_this, access_sys_t *p_sys )
  654. {
  655.     msg_Dbg( p_this, "releasing DirectShow");
  656.     DeleteDirectShowGraph( p_sys );
  657.     /* Uninitialize OLE/COM */
  658.     CoUninitialize();
  659.     for( int i = 0; i < p_sys->i_streams; i++ ) delete p_sys->pp_streams[i];
  660.     if( p_sys->i_streams ) free( p_sys->pp_streams );
  661.     vlc_mutex_destroy( &p_sys->lock );
  662.     vlc_cond_destroy( &p_sys->wait );
  663.     free( p_sys );
  664. }
  665. /*****************************************************************************
  666.  * AccessClose: close device
  667.  *****************************************************************************/
  668. static void AccessClose( vlc_object_t *p_this )
  669. {
  670.     access_t     *p_access = (access_t *)p_this;
  671.     access_sys_t *p_sys    = p_access->p_sys;
  672.     /* Stop capturing stuff */
  673.     p_sys->p_control->Stop();
  674.     CommonClose( p_this, p_sys );
  675. }
  676. /*****************************************************************************
  677.  * DemuxClose: close device
  678.  *****************************************************************************/
  679. static void DemuxClose( vlc_object_t *p_this )
  680. {
  681.     demux_t      *p_demux = (demux_t *)p_this;
  682.     access_sys_t *p_sys   = (access_sys_t *)p_demux->p_sys;
  683.     /* Stop capturing stuff */
  684.     p_sys->p_control->Stop();
  685.     CommonClose( p_this, p_sys );
  686. }
  687. /****************************************************************************
  688.  * ConnectFilters
  689.  ****************************************************************************/
  690. static bool ConnectFilters( vlc_object_t *p_this, access_sys_t *p_sys,
  691.                             IBaseFilter *p_filter,
  692.                             CaptureFilter *p_capture_filter )
  693. {
  694.     CapturePin *p_input_pin = p_capture_filter->CustomGetPin();
  695.     AM_MEDIA_TYPE mediaType = p_input_pin->CustomGetMediaType();
  696.     if( p_sys->p_capture_graph_builder2 )
  697.     {
  698.         if( FAILED(p_sys->p_capture_graph_builder2->
  699.                 RenderStream( &PIN_CATEGORY_CAPTURE, &mediaType.majortype,
  700.                               p_filter, 0, (IBaseFilter *)p_capture_filter )) )
  701.         {
  702.             return false;
  703.         }
  704.         // Sort out all the possible video inputs
  705.         // The class needs to be given the capture filters ANALOGVIDEO input pin
  706.         IEnumPins *pins = NULL;
  707.         if( ( mediaType.majortype == MEDIATYPE_Video ||
  708.               mediaType.majortype == MEDIATYPE_Stream ) &&
  709.             SUCCEEDED(p_filter->EnumPins(&pins)) )
  710.         {
  711.             IPin        *pP = NULL;
  712.             ULONG        n;
  713.             PIN_INFO     pinInfo;
  714.             BOOL         Found = FALSE;
  715.             IKsPropertySet *pKs = NULL;
  716.             GUID guid;
  717.             DWORD dw;
  718.             while( !Found && ( S_OK == pins->Next(1, &pP, &n) ) )
  719.             {
  720.                 if( S_OK == pP->QueryPinInfo(&pinInfo) )
  721.                 {
  722.                     // is this pin an ANALOGVIDEOIN input pin?
  723.                     if( pinInfo.dir == PINDIR_INPUT &&
  724.                         pP->QueryInterface( IID_IKsPropertySet,
  725.                                             (void **)&pKs ) == S_OK )
  726.                     {
  727.                         if( pKs->Get( AMPROPSETID_Pin,
  728.                                       AMPROPERTY_PIN_CATEGORY, NULL, 0,
  729.                                       &guid, sizeof(GUID), &dw ) == S_OK )
  730.                         {
  731.                             if( guid == PIN_CATEGORY_ANALOGVIDEOIN )
  732.                             {
  733.                                 // recursively search crossbar routes
  734.                                 FindCrossbarRoutes( p_this, p_sys, pP, 0 );
  735.                                 // found it
  736.                                 Found = TRUE;
  737.                             }
  738.                         }
  739.                         pKs->Release();
  740.                     }
  741.                     pinInfo.pFilter->Release();
  742.                 }
  743.                 pP->Release();
  744.             }
  745.             pins->Release();
  746.             msg_Dbg( p_this, "ConnectFilters: graph_builder2 available.") ;
  747.             if ( !Found )
  748.                 msg_Warn( p_this, "ConnectFilters: No crossBar routes found (incobatible pin types)" ) ;
  749.         }
  750.         return true;
  751.     }
  752.     else
  753.     {
  754.         IEnumPins *p_enumpins;
  755.         IPin *p_pin;
  756.         if( S_OK != p_filter->EnumPins( &p_enumpins ) ) return false;
  757.         while( S_OK == p_enumpins->Next( 1, &p_pin, NULL ) )
  758.         {
  759.             PIN_DIRECTION pin_dir;
  760.             p_pin->QueryDirection( &pin_dir );
  761.             if( pin_dir == PINDIR_OUTPUT &&
  762.                 p_sys->p_graph->ConnectDirect( p_pin, (IPin *)p_input_pin,
  763.                                                0 ) == S_OK )
  764.             {
  765.                 p_pin->Release();
  766.                 p_enumpins->Release();
  767.                 return true;
  768.             }
  769.             p_pin->Release();
  770.         }
  771.         p_enumpins->Release();
  772.         return false;
  773.     }
  774. }
  775. /*
  776.  * get fourcc priority from arbritary preference, the higher the better
  777.  */
  778. static int GetFourCCPriority( int i_fourcc )
  779. {
  780.     switch( i_fourcc )
  781.     {
  782.     case VLC_FOURCC('I','4','2','0'):
  783.     case VLC_FOURCC('f','l','3','2'):
  784.         return 9;
  785.     case VLC_FOURCC('Y','V','1','2'):
  786.     case VLC_FOURCC('a','r','a','w'):
  787.         return 8;
  788.     case VLC_FOURCC('R','V','2','4'):
  789.         return 7;
  790.     case VLC_FOURCC('Y','U','Y','2'):
  791.     case VLC_FOURCC('R','V','3','2'):
  792.     case VLC_FOURCC('R','G','B','A'):
  793.         return 6;
  794.     }
  795.     return 0;
  796. }
  797. #define MAX_MEDIA_TYPES 32
  798. static int OpenDevice( vlc_object_t *p_this, access_sys_t *p_sys,
  799.                        string devicename, bool b_audio )
  800. {
  801.     /* See if device is already opened */
  802.     for( int i = 0; i < p_sys->i_streams; i++ )
  803.     {
  804.         if( devicename.size() &&
  805.             p_sys->pp_streams[i]->devicename == devicename )
  806.         {
  807.             /* Already opened */
  808.             return VLC_SUCCESS;
  809.         }
  810.     }
  811.     list<string> list_devices;
  812.     /* Enumerate devices and display their names */
  813.     FindCaptureDevice( p_this, NULL, &list_devices, b_audio );
  814.     if( !list_devices.size() )
  815.         return VLC_EGENERIC;
  816.     list<string>::iterator iter;
  817.     for( iter = list_devices.begin(); iter != list_devices.end(); iter++ )
  818.         msg_Dbg( p_this, "found device: %s", iter->c_str() );
  819.     /* If no device name was specified, pick the 1st one */
  820.     if( devicename.size() == 0 )
  821.     {
  822.         /* When none selected */
  823.         devicename = *list_devices.begin();
  824.         msg_Dbg( p_this, "asking for default device: %s", devicename.c_str() ) ;
  825.     }
  826.     else
  827.         msg_Dbg( p_this, "asking for device: %s", devicename.c_str() ) ;
  828.     // Use the system device enumerator and class enumerator to find
  829.     // a capture/preview device, such as a desktop USB video camera.
  830.     IBaseFilter *p_device_filter =
  831.         FindCaptureDevice( p_this, &devicename, NULL, b_audio );
  832.     if( p_device_filter )
  833.         msg_Dbg( p_this, "using device: %s", devicename.c_str() );
  834.     else
  835.     {
  836.         msg_Err( p_this, "can't use device: %s, unsupported device type",
  837.                  devicename.c_str() );
  838.         dialog_Fatal( p_this, _("Capture failed"),
  839.                         _("VLC cannot use the device "%s", because its "
  840.                           "type is not supported."), devicename.c_str() );
  841.         return VLC_EGENERIC;
  842.     }
  843.     // Retreive acceptable media types supported by device
  844.     AM_MEDIA_TYPE media_types[MAX_MEDIA_TYPES];
  845.     size_t media_count =
  846.         EnumDeviceCaps( p_this, p_device_filter, b_audio ? 0 : p_sys->i_chroma,
  847.                         p_sys->i_width, p_sys->i_height,
  848.       b_audio ? var_CreateGetInteger( p_this, "dshow-audio-channels" ) : 0,
  849.       b_audio ? var_CreateGetInteger( p_this, "dshow-audio-samplerate" ) : 0,
  850.       b_audio ? var_CreateGetInteger( p_this, "dshow-audio-bitspersample" ) : 0,
  851.       media_types, MAX_MEDIA_TYPES );
  852.     AM_MEDIA_TYPE *mt = NULL;
  853.     if( media_count > 0 )
  854.     {
  855.         mt = (AM_MEDIA_TYPE *)CoTaskMemAlloc(sizeof(AM_MEDIA_TYPE) * media_count);
  856.         // Order and copy returned media types according to arbitrary
  857.         // fourcc priority
  858.         for( size_t c = 0; c < media_count; c++ )
  859.         {
  860.             int slot_priority =
  861.                 GetFourCCPriority(GetFourCCFromMediaType(media_types[c]));
  862.             size_t slot_copy = c;
  863.             for( size_t d = c+1; d < media_count; d++ )
  864.             {
  865.                 int priority =
  866.                     GetFourCCPriority(GetFourCCFromMediaType(media_types[d]));
  867.                 if( priority > slot_priority )
  868.                 {
  869.                     slot_priority = priority;
  870.                     slot_copy = d;
  871.                 }
  872.             }
  873.             if( slot_copy != c )
  874.             {
  875.                 mt[c] = media_types[slot_copy];
  876.                 media_types[slot_copy] = media_types[c];
  877.             }
  878.             else
  879.             {
  880.                 mt[c] = media_types[c];
  881.             }
  882.         }
  883.     }
  884.     else {
  885.         /* capture device */
  886.         msg_Err( p_this, "capture device '%s' does not support required parameters !", devicename.c_str() );
  887.         dialog_Fatal( p_this, _("Capture failed"),
  888.                         _("The capture device "%s" does not support the "
  889.                           "required parameters."), devicename.c_str() );
  890.         p_device_filter->Release();
  891.         return VLC_EGENERIC;
  892.     }
  893.     /* Create and add our capture filter */
  894.     CaptureFilter *p_capture_filter =
  895.         new CaptureFilter( p_this, p_sys, mt, media_count );
  896.     p_sys->p_graph->AddFilter( p_capture_filter, 0 );
  897.     /* Add the device filter to the graph (seems necessary with VfW before
  898.      * accessing pin attributes). */
  899.     p_sys->p_graph->AddFilter( p_device_filter, 0 );
  900.     /* Attempt to connect one of this device's capture output pins */
  901.     msg_Dbg( p_this, "connecting filters" );
  902.     if( ConnectFilters( p_this, p_sys, p_device_filter, p_capture_filter ) )
  903.     {
  904.         /* Success */
  905.         msg_Dbg( p_this, "filters connected successfully !" );
  906.         dshow_stream_t dshow_stream;
  907.         dshow_stream.b_pts = false;
  908.         dshow_stream.p_es = 0;
  909.         dshow_stream.mt =
  910.             p_capture_filter->CustomGetPin()->CustomGetMediaType();
  911.         /* Show Device properties. Done here so the VLC stream is setup with
  912.          * the proper parameters. */
  913.         vlc_value_t val;
  914.         var_Get( p_this, "dshow-config", &val );
  915.         if( val.b_bool )
  916.         {
  917.             ShowDeviceProperties( p_this, p_sys->p_capture_graph_builder2,
  918.                                   p_device_filter, b_audio );
  919.         }
  920.         ConfigTuner( p_this, p_sys->p_capture_graph_builder2,
  921.                      p_device_filter );
  922.         var_Get( p_this, "dshow-tuner", &val );
  923.         if( val.b_bool && dshow_stream.mt.majortype != MEDIATYPE_Stream )
  924.         {
  925.             /* FIXME: we do MEDIATYPE_Stream later so we don't do it twice. */
  926.             ShowTunerProperties( p_this, p_sys->p_capture_graph_builder2,
  927.                                  p_device_filter, b_audio );
  928.         }
  929.         dshow_stream.mt =
  930.             p_capture_filter->CustomGetPin()->CustomGetMediaType();
  931.         dshow_stream.i_fourcc = GetFourCCFromMediaType( dshow_stream.mt );
  932.         if( dshow_stream.i_fourcc )
  933.         {
  934.             if( dshow_stream.mt.majortype == MEDIATYPE_Video )
  935.             {
  936.                 dshow_stream.header.video =
  937.                     *(VIDEOINFOHEADER *)dshow_stream.mt.pbFormat;
  938.                 msg_Dbg( p_this, "MEDIATYPE_Video" );
  939.                 msg_Dbg( p_this, "selected video pin accepts format: %4.4s",
  940.                          (char *)&dshow_stream.i_fourcc);
  941.             }
  942.             else if( dshow_stream.mt.majortype == MEDIATYPE_Audio )
  943.             {
  944.                 dshow_stream.header.audio =
  945.                     *(WAVEFORMATEX *)dshow_stream.mt.pbFormat;
  946.                 msg_Dbg( p_this, "MEDIATYPE_Audio" );
  947.                 msg_Dbg( p_this, "selected audio pin accepts format: %4.4s",
  948.                          (char *)&dshow_stream.i_fourcc);
  949.             }
  950.             else if( dshow_stream.mt.majortype == MEDIATYPE_Stream )
  951.             {
  952.                 msg_Dbg( p_this, "MEDIATYPE_Stream" );
  953.                 msg_Dbg( p_this, "selected stream pin accepts format: %4.4s",
  954.                          (char *)&dshow_stream.i_fourcc);
  955.             }
  956.             else
  957.             {
  958.                 msg_Dbg( p_this, "unknown stream majortype" );
  959.                 goto fail;
  960.             }
  961.             /* Add directshow elementary stream to our list */
  962.             dshow_stream.p_device_filter = p_device_filter;
  963.             dshow_stream.p_capture_filter = p_capture_filter;
  964.             p_sys->pp_streams = (dshow_stream_t **)realloc( p_sys->pp_streams,
  965.                 sizeof(dshow_stream_t *) * (p_sys->i_streams + 1) );
  966.             p_sys->pp_streams[p_sys->i_streams] = new dshow_stream_t;
  967.             *p_sys->pp_streams[p_sys->i_streams++] = dshow_stream;
  968.             return VLC_SUCCESS;
  969.         }
  970.     }
  971.  fail:
  972.     /* Remove filters from graph */
  973.     p_sys->p_graph->RemoveFilter( p_device_filter );
  974.     p_sys->p_graph->RemoveFilter( p_capture_filter );
  975.     /* Release objects */
  976.     p_device_filter->Release();
  977.     p_capture_filter->Release();
  978.     return VLC_EGENERIC;
  979. }
  980. /* FindCaptureDevices:: This Function had two purposes :
  981.     Returns the list of capture devices when p_listdevices != NULL
  982.     Creates an IBaseFilter when p_devicename corresponds to an existing devname
  983.    These actions *may* be requested whith a single call.
  984. */
  985. static IBaseFilter *
  986. FindCaptureDevice( vlc_object_t *p_this, string *p_devicename,
  987.                    list<string> *p_listdevices, bool b_audio )
  988. {
  989.     IBaseFilter *p_base_filter = NULL;
  990.     IMoniker *p_moniker = NULL;
  991.     ULONG i_fetched;
  992.     HRESULT hr;
  993.     list<string> devicelist;
  994.     /* Create the system device enumerator */
  995.     ICreateDevEnum *p_dev_enum = NULL;
  996.     hr = CoCreateInstance( CLSID_SystemDeviceEnum, NULL, CLSCTX_INPROC,
  997.                            IID_ICreateDevEnum, (void **)&p_dev_enum );
  998.     if( FAILED(hr) )
  999.     {
  1000.         msg_Err( p_this, "failed to create the device enumerator (0x%lx)", hr);
  1001.         return NULL;
  1002.     }
  1003.     /* Create an enumerator for the video capture devices */
  1004.     IEnumMoniker *p_class_enum = NULL;
  1005.     if( !b_audio )
  1006.         hr = p_dev_enum->CreateClassEnumerator( CLSID_VideoInputDeviceCategory,
  1007.                                                 &p_class_enum, 0 );
  1008.     else
  1009.         hr = p_dev_enum->CreateClassEnumerator( CLSID_AudioInputDeviceCategory,
  1010.                                                 &p_class_enum, 0 );
  1011.     p_dev_enum->Release();
  1012.     if( FAILED(hr) )
  1013.     {
  1014.         msg_Err( p_this, "failed to create the class enumerator (0x%lx)", hr );
  1015.         return NULL;
  1016.     }
  1017.     /* If there are no enumerators for the requested type, then
  1018.      * CreateClassEnumerator will succeed, but p_class_enum will be NULL */
  1019.     if( p_class_enum == NULL )
  1020.     {
  1021.         msg_Err( p_this, "no %s capture device was detected", ( b_audio ? "audio" : "video" ) );
  1022.         return NULL;
  1023.     }
  1024.     /* Enumerate the devices */
  1025.     /* Note that if the Next() call succeeds but there are no monikers,
  1026.      * it will return S_FALSE (which is not a failure). Therefore, we check
  1027.      * that the return code is S_OK instead of using SUCCEEDED() macro. */
  1028.     while( p_class_enum->Next( 1, &p_moniker, &i_fetched ) == S_OK )
  1029.     {
  1030.         /* Getting the property page to get the device name */
  1031.         IPropertyBag *p_bag;
  1032.         hr = p_moniker->BindToStorage( 0, 0, IID_IPropertyBag,
  1033.                                        (void **)&p_bag );
  1034.         if( SUCCEEDED(hr) )
  1035.         {
  1036.             VARIANT var;
  1037.             var.vt = VT_BSTR;
  1038.             hr = p_bag->Read( L"FriendlyName", &var, NULL );
  1039.             p_bag->Release();
  1040.             if( SUCCEEDED(hr) )
  1041.             {
  1042.                 char *p_buf = FromWide( var.bstrVal );
  1043.                 string devname = string(p_buf);
  1044.                 free( p_buf) ;
  1045.                 int dup = 0;
  1046.                 /* find out if this name is already used by a previously found device */
  1047.                 list<string>::const_iterator iter = devicelist.begin();
  1048.                 list<string>::const_iterator end = devicelist.end();
  1049.                 string ordevname = devname ;
  1050.                 while ( iter != end )
  1051.                 {
  1052.                     if( 0 == (*iter).compare( devname ) )
  1053.                     { /* devname is on the list. Try another name with sequence
  1054.                          number apended and then rescan until a unique entry is found*/
  1055.                          char seq[16];
  1056.                          snprintf(seq, 16, " #%d", ++dup);
  1057.                          devname = ordevname + seq;
  1058.                          iter = devicelist.begin();
  1059.                     }
  1060.                     else
  1061.                          ++iter;
  1062.                 }
  1063.                 devicelist.push_back( devname );
  1064.                 if( p_devicename && *p_devicename == devname )
  1065.                 {
  1066.                     msg_Dbg( p_this, "asked for %s, binding to %s", p_devicename->c_str() , devname.c_str() ) ;
  1067.                     /* NULL possibly means we don't need BindMoniker BindCtx ?? */
  1068.                     hr = p_moniker->BindToObject( NULL, 0, IID_IBaseFilter,
  1069.                                                   (void **)&p_base_filter );
  1070.                     if( FAILED(hr) )
  1071.                     {
  1072.                         msg_Err( p_this, "couldn't bind moniker to filter "
  1073.                                  "object (0x%lx)", hr );
  1074.                         p_moniker->Release();
  1075.                         p_class_enum->Release();
  1076.                         return NULL;
  1077.                     }
  1078.                     p_moniker->Release();
  1079.                     p_class_enum->Release();
  1080.                     return p_base_filter;
  1081.                 }
  1082.             }
  1083.         }
  1084.         p_moniker->Release();
  1085.     }
  1086.     p_class_enum->Release();
  1087.     if( p_listdevices ) {
  1088.     devicelist.sort();
  1089.     *p_listdevices = devicelist;
  1090.     }
  1091.     return NULL;
  1092. }
  1093. static size_t EnumDeviceCaps( vlc_object_t *p_this, IBaseFilter *p_filter,
  1094.                               int i_fourcc, int i_width, int i_height,
  1095.                               int i_channels, int i_samplespersec,
  1096.                               int i_bitspersample, AM_MEDIA_TYPE *mt,
  1097.                               size_t mt_max )
  1098. {
  1099.     IEnumPins *p_enumpins;
  1100.     IPin *p_output_pin;
  1101.     IEnumMediaTypes *p_enummt;
  1102.     size_t mt_count = 0;
  1103.     LONGLONG i_AvgTimePerFrame = 0;
  1104.     float r_fps = var_GetFloat( p_this, "dshow-fps" );
  1105.     if( r_fps )
  1106.         i_AvgTimePerFrame = 10000000000LL/(LONGLONG)(r_fps*1000.0f);
  1107.     if( FAILED(p_filter->EnumPins( &p_enumpins )) )
  1108.     {
  1109.         msg_Dbg( p_this, "EnumDeviceCaps failed: no pin enumeration !");
  1110.         return 0;
  1111.     }
  1112.     while( S_OK == p_enumpins->Next( 1, &p_output_pin, NULL ) )
  1113.     {
  1114.         PIN_INFO info;
  1115.         if( S_OK == p_output_pin->QueryPinInfo( &info ) )
  1116.         {
  1117.             msg_Dbg( p_this, "EnumDeviceCaps: %s pin: %S",
  1118.                      info.dir == PINDIR_INPUT ? "input" : "output",
  1119.                      info.achName );
  1120.             if( info.pFilter ) info.pFilter->Release();
  1121.         }
  1122.         p_output_pin->Release();
  1123.     }
  1124.     p_enumpins->Reset();
  1125.     while( !mt_count && p_enumpins->Next( 1, &p_output_pin, NULL ) == S_OK )
  1126.     {
  1127.         PIN_INFO info;
  1128.         if( S_OK == p_output_pin->QueryPinInfo( &info ) )
  1129.         {
  1130.             if( info.pFilter ) info.pFilter->Release();
  1131.             if( info.dir == PINDIR_INPUT )
  1132.             {
  1133.                 p_output_pin->Release();
  1134.                 continue;
  1135.             }
  1136.             msg_Dbg( p_this, "EnumDeviceCaps: trying pin %S", info.achName );
  1137.         }
  1138.         AM_MEDIA_TYPE *p_mt;
  1139.         /*
  1140.         ** Configure pin with a default compatible media if possible
  1141.         */
  1142.         IAMStreamConfig *pSC;
  1143.         if( SUCCEEDED(p_output_pin->QueryInterface( IID_IAMStreamConfig,
  1144.                                             (void **)&pSC )) )
  1145.         {
  1146.             int piCount, piSize;
  1147.             if( SUCCEEDED(pSC->GetNumberOfCapabilities(&piCount, &piSize)) )
  1148.             {
  1149.                 BYTE *pSCC= (BYTE *)CoTaskMemAlloc(piSize);
  1150.                 if( NULL != pSCC )
  1151.                 {
  1152.                     int i_priority = -1;
  1153.                     for( int i=0; i<piCount; ++i )
  1154.                     {
  1155.                         if( SUCCEEDED(pSC->GetStreamCaps(i, &p_mt, pSCC)) )
  1156.                         {
  1157.                             int i_current_fourcc = GetFourCCFromMediaType( *p_mt );
  1158.                             int i_current_priority = GetFourCCPriority(i_current_fourcc);
  1159.                             if( (i_fourcc && (i_current_fourcc != i_fourcc))
  1160.                              || (i_priority > i_current_priority) )
  1161.                             {
  1162.                                 // unwanted chroma, try next media type
  1163.                                 FreeMediaType( *p_mt );
  1164.                                 CoTaskMemFree( (PVOID)p_mt );
  1165.                                 continue;
  1166.                             }
  1167.                             if( MEDIATYPE_Video == p_mt->majortype
  1168.                                     && FORMAT_VideoInfo == p_mt->formattype )
  1169.                             {
  1170.                                 VIDEO_STREAM_CONFIG_CAPS *pVSCC = reinterpret_cast<VIDEO_STREAM_CONFIG_CAPS*>(pSCC);
  1171.                                 VIDEOINFOHEADER *pVih = reinterpret_cast<VIDEOINFOHEADER*>(p_mt->pbFormat);
  1172.                                 if( i_AvgTimePerFrame )
  1173.                                 {
  1174.                                     if( pVSCC->MinFrameInterval > i_AvgTimePerFrame
  1175.                                       || i_AvgTimePerFrame > pVSCC->MaxFrameInterval )
  1176.                                     {
  1177.                                         // required frame rate not compatible, try next media type
  1178.                                         FreeMediaType( *p_mt );
  1179.                                         CoTaskMemFree( (PVOID)p_mt );
  1180.                                         continue;
  1181.                                     }
  1182.                                     pVih->AvgTimePerFrame = i_AvgTimePerFrame;
  1183.                                 }
  1184.                                 if( i_width )
  1185.                                 {
  1186.                                     if((   !pVSCC->OutputGranularityX
  1187.                                            && i_width != pVSCC->MinOutputSize.cx
  1188.                                            && i_width != pVSCC->MaxOutputSize.cx)
  1189.                                        ||
  1190.                                        (   pVSCC->OutputGranularityX
  1191.                                            && ((i_width % pVSCC->OutputGranularityX)
  1192.                                                || pVSCC->MinOutputSize.cx > i_width
  1193.                                                || i_width > pVSCC->MaxOutputSize.cx )))
  1194.                                     {
  1195.                                         // required width not compatible, try next media type
  1196.                                         FreeMediaType( *p_mt );
  1197.                                         CoTaskMemFree( (PVOID)p_mt );
  1198.                                         continue;
  1199.                                     }
  1200.                                     pVih->bmiHeader.biWidth = i_width;
  1201.                                 }
  1202.                                 if( i_height )
  1203.                                 {
  1204.                                     if((   !pVSCC->OutputGranularityY
  1205.                                            && i_height != pVSCC->MinOutputSize.cy
  1206.                                            && i_height != pVSCC->MaxOutputSize.cy)
  1207.                                        ||
  1208.                                        (   pVSCC->OutputGranularityY
  1209.                                            && ((i_height % pVSCC->OutputGranularityY)
  1210.                                                || pVSCC->MinOutputSize.cy > i_height
  1211.                                                || i_height > pVSCC->MaxOutputSize.cy )))
  1212.                                     {
  1213.                                         // required height not compatible, try next media type
  1214.                                         FreeMediaType( *p_mt );
  1215.                                         CoTaskMemFree( (PVOID)p_mt );
  1216.                                         continue;
  1217.                                     }
  1218.                                     pVih->bmiHeader.biHeight = i_height;
  1219.                                 }
  1220.                                 // Set the sample size and image size.
  1221.                                 // (Round the image width up to a DWORD boundary.)
  1222.                                 p_mt->lSampleSize = pVih->bmiHeader.biSizeImage =
  1223.                                     ((pVih->bmiHeader.biWidth + 3) & ~3) *
  1224.                                     pVih->bmiHeader.biHeight * (pVih->bmiHeader.biBitCount>>3);
  1225.                                 // no cropping, use full video input buffer
  1226.                                 memset(&(pVih->rcSource), 0, sizeof(RECT));
  1227.                                 memset(&(pVih->rcTarget), 0, sizeof(RECT));
  1228.                                 // select this format as default
  1229.                                 if( SUCCEEDED( pSC->SetFormat(p_mt) ) )
  1230.                                 {
  1231.                                     i_priority = i_current_priority;
  1232.                                     if( i_fourcc )
  1233.                                         // no need to check any more media types
  1234.                                         i = piCount;
  1235.                                 }
  1236.                             }
  1237.                             else if( p_mt->majortype == MEDIATYPE_Audio
  1238.                                     && p_mt->formattype == FORMAT_WaveFormatEx )
  1239.                             {
  1240.                                 AUDIO_STREAM_CONFIG_CAPS *pASCC = reinterpret_cast<AUDIO_STREAM_CONFIG_CAPS*>(pSCC);
  1241.                                 WAVEFORMATEX *pWfx = reinterpret_cast<WAVEFORMATEX*>(p_mt->pbFormat);
  1242.                                 if( i_current_fourcc && (WAVE_FORMAT_PCM == pWfx->wFormatTag) )
  1243.                                 {
  1244.                                     int val = i_channels;
  1245.                                     if( ! val )
  1246.                                         val = 2;
  1247.                                     if( (   !pASCC->ChannelsGranularity
  1248.                                             && (unsigned int)val != pASCC->MinimumChannels
  1249.                                             && (unsigned int)val != pASCC->MaximumChannels)
  1250.                                         ||
  1251.                                         (   pASCC->ChannelsGranularity
  1252.                                             && ((val % pASCC->ChannelsGranularity)
  1253.                                                 || (unsigned int)val < pASCC->MinimumChannels
  1254.                                                 || (unsigned int)val > pASCC->MaximumChannels)))
  1255.                                     {
  1256.                                         // required number channels not available, try next media type
  1257.                                         FreeMediaType( *p_mt );
  1258.                                         CoTaskMemFree( (PVOID)p_mt );
  1259.                                         continue;
  1260.                                     }
  1261.                                     pWfx->nChannels = val;
  1262.                                     val = i_samplespersec;
  1263.                                     if( ! val )
  1264.                                         val = 44100;
  1265.                                     if( (   !pASCC->SampleFrequencyGranularity
  1266.                                             && (unsigned int)val != pASCC->MinimumSampleFrequency
  1267.                                             && (unsigned int)val != pASCC->MaximumSampleFrequency)
  1268.                                         ||
  1269.                                         (   pASCC->SampleFrequencyGranularity
  1270.                                             && ((val % pASCC->SampleFrequencyGranularity)
  1271.                                                 || (unsigned int)val < pASCC->MinimumSampleFrequency
  1272.                                                 || (unsigned int)val > pASCC->MaximumSampleFrequency )))
  1273.                                     {
  1274.                                         // required sampling rate not available, try next media type
  1275.                                         FreeMediaType( *p_mt );
  1276.                                         CoTaskMemFree( (PVOID)p_mt );
  1277.                                         continue;
  1278.                                     }
  1279.                                     pWfx->nSamplesPerSec = val;
  1280.  
  1281.                                     val = i_bitspersample;
  1282.                                     if( ! val )
  1283.                                     {
  1284.                                         if( VLC_FOURCC('f', 'l', '3', '2') == i_current_fourcc )
  1285.                                             val = 32;
  1286.                                         else
  1287.                                             val = 16;
  1288.                                     }
  1289.                                     if( (   !pASCC->BitsPerSampleGranularity
  1290.                                             && (unsigned int)val != pASCC->MinimumBitsPerSample
  1291.                                             && (unsigned int)val != pASCC->MaximumBitsPerSample )
  1292.                                         ||
  1293.                                         (   pASCC->BitsPerSampleGranularity
  1294.                                             && ((val % pASCC->BitsPerSampleGranularity)
  1295.                                                 || (unsigned int)val < pASCC->MinimumBitsPerSample
  1296.                                                 || (unsigned int)val > pASCC->MaximumBitsPerSample )))
  1297.                                     {
  1298.                                         // required sample size not available, try next media type
  1299.                                         FreeMediaType( *p_mt );
  1300.                                         CoTaskMemFree( (PVOID)p_mt );
  1301.                                         continue;
  1302.                                     }
  1303.                                     pWfx->wBitsPerSample = val;
  1304.                                     pWfx->nBlockAlign = (pWfx->wBitsPerSample * pWfx->nChannels)/8;
  1305.                                     pWfx->nAvgBytesPerSec = pWfx->nSamplesPerSec * pWfx->nBlockAlign;
  1306.                                     // select this format as default
  1307.                                     if( SUCCEEDED( pSC->SetFormat(p_mt) ) )
  1308.                                     {
  1309.                                         i_priority = i_current_priority;
  1310.                                     }
  1311.                                 }
  1312.                             }
  1313.                             FreeMediaType( *p_mt );
  1314.                             CoTaskMemFree( (PVOID)p_mt );
  1315.                         }
  1316.                     }
  1317.                     CoTaskMemFree( (LPVOID)pSCC );
  1318.                     if( i_priority >= 0 )
  1319.                         msg_Dbg( p_this, "EnumDeviceCaps: input pin default format configured");
  1320.                 }
  1321.             }
  1322.             pSC->Release();
  1323.         }
  1324.         /*
  1325.         ** Probe pin for available medias (may be a previously configured one)
  1326.         */
  1327.         if( FAILED( p_output_pin->EnumMediaTypes( &p_enummt ) ) )
  1328.         {
  1329.             p_output_pin->Release();
  1330.             continue;
  1331.         }
  1332.         while( p_enummt->Next( 1, &p_mt, NULL ) == S_OK )
  1333.         {
  1334.             int i_current_fourcc = GetFourCCFromMediaType( *p_mt );
  1335.             if( i_current_fourcc && p_mt->majortype == MEDIATYPE_Video
  1336.                 && p_mt->formattype == FORMAT_VideoInfo )
  1337.             {
  1338.                 int i_current_width = ((VIDEOINFOHEADER *)p_mt->pbFormat)->bmiHeader.biWidth;
  1339.                 int i_current_height = ((VIDEOINFOHEADER *)p_mt->pbFormat)->bmiHeader.biHeight;
  1340.                 LONGLONG i_current_atpf = ((VIDEOINFOHEADER *)p_mt->pbFormat)->AvgTimePerFrame;
  1341.                 if( i_current_height < 0 )
  1342.                     i_current_height = -i_current_height;
  1343.                 msg_Dbg( p_this, "EnumDeviceCaps: input pin "
  1344.                          "accepts chroma: %4.4s, width:%i, height:%i, fps:%f",
  1345.                          (char *)&i_current_fourcc, i_current_width,
  1346.                          i_current_height, (10000000.0f/((float)i_current_atpf)) );
  1347.                 if( ( !i_fourcc || i_fourcc == i_current_fourcc ) &&
  1348.                     ( !i_width || i_width == i_current_width ) &&
  1349.                     ( !i_height || i_height == i_current_height ) &&
  1350.                     ( !i_AvgTimePerFrame || i_AvgTimePerFrame == i_current_atpf ) &&
  1351.                     mt_count < mt_max )
  1352.                 {
  1353.                     /* Pick match */
  1354.                     mt[mt_count++] = *p_mt;
  1355.                 }
  1356.                 else FreeMediaType( *p_mt );
  1357.             }
  1358.             else if( i_current_fourcc && p_mt->majortype == MEDIATYPE_Audio
  1359.                     && p_mt->formattype == FORMAT_WaveFormatEx)
  1360.             {
  1361.                 int i_current_channels =
  1362.                     ((WAVEFORMATEX *)p_mt->pbFormat)->nChannels;
  1363.                 int i_current_samplespersec =
  1364.                     ((WAVEFORMATEX *)p_mt->pbFormat)->nSamplesPerSec;
  1365.                 int i_current_bitspersample =
  1366.                     ((WAVEFORMATEX *)p_mt->pbFormat)->wBitsPerSample;
  1367.                 msg_Dbg( p_this, "EnumDeviceCaps: input pin "
  1368.                          "accepts format: %4.4s, channels:%i, "
  1369.                          "samples/sec:%i bits/sample:%i",
  1370.                          (char *)&i_current_fourcc, i_current_channels,
  1371.                          i_current_samplespersec, i_current_bitspersample);
  1372.                 if( (!i_channels || i_channels == i_current_channels) &&
  1373.                     (!i_samplespersec ||
  1374.                      i_samplespersec == i_current_samplespersec) &&
  1375.                     (!i_bitspersample ||
  1376.                      i_bitspersample == i_current_bitspersample) &&
  1377.                     mt_count < mt_max )
  1378.                 {
  1379.                     /* Pick  match */
  1380.                     mt[mt_count++] = *p_mt;
  1381.                     /* Setup a few properties like the audio latency */
  1382.                     IAMBufferNegotiation *p_ambuf;
  1383.                     if( SUCCEEDED( p_output_pin->QueryInterface(
  1384.                           IID_IAMBufferNegotiation, (void **)&p_ambuf ) ) )
  1385.                     {
  1386.                         ALLOCATOR_PROPERTIES AllocProp;
  1387.                         AllocProp.cbAlign = -1;
  1388.                         /* 100 ms of latency */
  1389.                         AllocProp.cbBuffer = i_current_channels *
  1390.                           i_current_samplespersec *
  1391.                           i_current_bitspersample / 8 / 10;
  1392.                         AllocProp.cbPrefix = -1;
  1393.                         AllocProp.cBuffers = -1;
  1394.                         p_ambuf->SuggestAllocatorProperties( &AllocProp );
  1395.                         p_ambuf->Release();
  1396.                     }
  1397.                 }
  1398.                 else FreeMediaType( *p_mt );
  1399.             }
  1400.             else if( i_current_fourcc && p_mt->majortype == MEDIATYPE_Stream )
  1401.             {
  1402.                 msg_Dbg( p_this, "EnumDeviceCaps: input pin "
  1403.                          "accepts stream format: %4.4s",
  1404.                          (char *)&i_current_fourcc );
  1405.                 if( ( !i_fourcc || i_fourcc == i_current_fourcc ) &&
  1406.                     mt_count < mt_max )
  1407.                 {
  1408.                     /* Pick match */
  1409.                     mt[mt_count++] = *p_mt;
  1410.                     i_fourcc = i_current_fourcc;
  1411.                 }
  1412.                 else FreeMediaType( *p_mt );
  1413.             }
  1414.             else
  1415.             {
  1416.                 const char * psz_type = "unknown";
  1417.                 if( p_mt->majortype == MEDIATYPE_Video ) psz_type = "video";
  1418.                 if( p_mt->majortype == MEDIATYPE_Audio ) psz_type = "audio";
  1419.                 if( p_mt->majortype == MEDIATYPE_Stream ) psz_type = "stream";
  1420.                 msg_Dbg( p_this, "EnumDeviceCaps: input pin media: unsupported format "
  1421.                          "(%s %4.4s)", psz_type, (char *)&p_mt->subtype );
  1422.                 FreeMediaType( *p_mt );
  1423.             }
  1424.             CoTaskMemFree( (PVOID)p_mt );
  1425.         }
  1426.         if( !mt_count && p_enummt->Reset() == S_OK )
  1427.         {
  1428.             // VLC did not find any supported MEDIATYPE for this output pin.
  1429.             // However the graph builder might insert converter filters in
  1430.             // the graph if we use a different codec in VLC filter input pin.
  1431.             // however, in order to avoid nasty surprises, make use of this
  1432.             // facility only for known unsupported codecs.
  1433.             while( !mt_count && p_enummt->Next( 1, &p_mt, NULL ) == S_OK )
  1434.             {
  1435.                 // the first four bytes of subtype GUID contains the codec FOURCC
  1436.                 const char *pfcc = (char *)&p_mt->subtype;
  1437.                 int i_current_fourcc = VLC_FOURCC(pfcc[0], pfcc[1], pfcc[2], pfcc[3]);
  1438.                 if( VLC_FOURCC('H','C','W','2') == i_current_fourcc
  1439.                  && p_mt->majortype == MEDIATYPE_Video )
  1440.                 {
  1441.                     // output format for 'Hauppauge WinTV PVR PCI II Capture'
  1442.                     // try I420 as an input format
  1443.                     i_current_fourcc = VLC_FOURCC('I','4','2','0');
  1444.                     if( !i_fourcc || i_fourcc == i_current_fourcc )
  1445.                     {
  1446.                         // return alternative media type
  1447.                         AM_MEDIA_TYPE mtr;
  1448.                         VIDEOINFOHEADER vh;
  1449.  
  1450.                         mtr.majortype            = MEDIATYPE_Video;
  1451.                         mtr.subtype              = MEDIASUBTYPE_I420;
  1452.                         mtr.bFixedSizeSamples    = TRUE;
  1453.                         mtr.bTemporalCompression = FALSE;
  1454.                         mtr.pUnk                 = NULL;
  1455.                         mtr.formattype           = FORMAT_VideoInfo;
  1456.                         mtr.cbFormat             = sizeof(vh);
  1457.                         mtr.pbFormat             = (BYTE *)&vh;
  1458.  
  1459.                         memset(&vh, 0, sizeof(vh));
  1460.  
  1461.                         vh.bmiHeader.biSize   = sizeof(vh.bmiHeader);
  1462.                         vh.bmiHeader.biWidth  = i_width > 0 ? i_width :
  1463.                             ((VIDEOINFOHEADER *)p_mt->pbFormat)->bmiHeader.biWidth;
  1464.                         vh.bmiHeader.biHeight = i_height > 0 ? i_height :
  1465.                             ((VIDEOINFOHEADER *)p_mt->pbFormat)->bmiHeader.biHeight;
  1466.                         vh.bmiHeader.biPlanes      = 3;
  1467.                         vh.bmiHeader.biBitCount    = 12;
  1468.                         vh.bmiHeader.biCompression = VLC_FOURCC('I','4','2','0');
  1469.                         vh.bmiHeader.biSizeImage   = vh.bmiHeader.biWidth * 12 *
  1470.                             vh.bmiHeader.biHeight / 8;
  1471.                         mtr.lSampleSize            = vh.bmiHeader.biSizeImage;
  1472.  
  1473.                         msg_Dbg( p_this, "EnumDeviceCaps: input pin media: using 'I420' in place of unsupported format 'HCW2'");
  1474.                         if( SUCCEEDED(CopyMediaType(mt+mt_count, &mtr)) )
  1475.                             ++mt_count;
  1476.                     }
  1477.                 }
  1478.                 FreeMediaType( *p_mt );
  1479.             }
  1480.         }
  1481.         p_enummt->Release();
  1482.         p_output_pin->Release();
  1483.     }
  1484.     p_enumpins->Release();
  1485.     return mt_count;
  1486. }
  1487. /*****************************************************************************
  1488.  * ReadCompressed: reads compressed (MPEG/DV) data from the device.
  1489.  *****************************************************************************
  1490.  * Returns -1 in case of error, 0 in case of EOF, otherwise the number of
  1491.  * bytes.
  1492.  *****************************************************************************/
  1493. static block_t *ReadCompressed( access_t *p_access )
  1494. {
  1495.     access_sys_t   *p_sys = p_access->p_sys;
  1496.     dshow_stream_t *p_stream = NULL;
  1497.     VLCMediaSample sample;
  1498.     /* Read 1 DV/MPEG frame (they contain the video and audio data) */
  1499.     /* There must be only 1 elementary stream to produce a valid stream
  1500.      * of MPEG or DV data */
  1501.     p_stream = p_sys->pp_streams[0];
  1502.     while( 1 )
  1503.     {
  1504.         if( !vlc_object_alive (p_access) || p_access->b_error ) return 0;
  1505.         /* Get new sample/frame from the elementary stream (blocking). */
  1506.         vlc_mutex_lock( &p_sys->lock );
  1507.         if( p_stream->p_capture_filter->CustomGetPin()
  1508.               ->CustomGetSample( &sample ) != S_OK )
  1509.         {
  1510.             /* No data available. Wait until some data has arrived */
  1511.             vlc_cond_wait( &p_sys->wait, &p_sys->lock );
  1512.             vlc_mutex_unlock( &p_sys->lock );
  1513.             continue;
  1514.         }
  1515.         vlc_mutex_unlock( &p_sys->lock );
  1516.         /*
  1517.          * We got our sample
  1518.          */
  1519.         block_t *p_block;
  1520.         uint8_t *p_data;
  1521.         int i_data_size = sample.p_sample->GetActualDataLength();
  1522.         if( !i_data_size || !(p_block = block_New( p_access, i_data_size )) )
  1523.         {
  1524.             sample.p_sample->Release();
  1525.             continue;
  1526.         }
  1527.         sample.p_sample->GetPointer( &p_data );
  1528.         vlc_memcpy( p_block->p_buffer, p_data, i_data_size );
  1529.         sample.p_sample->Release();
  1530.         /* The caller got what he wanted */
  1531.         return p_block;
  1532.     }
  1533.     return NULL; /* never reached */
  1534. }
  1535. /****************************************************************************
  1536.  * Demux:
  1537.  ****************************************************************************/
  1538. static int Demux( demux_t *p_demux )
  1539. {
  1540.     access_sys_t *p_sys = (access_sys_t *)p_demux->p_sys;
  1541.     int i_stream;
  1542.     int i_found_samples;
  1543.     i_found_samples = 0;
  1544.     vlc_mutex_lock( &p_sys->lock );
  1545.     while ( !i_found_samples )
  1546.     {
  1547.         /* Try to grab samples from all streams */
  1548.         for( i_stream = 0; i_stream < p_sys->i_streams; i_stream++ )
  1549.         {
  1550.             dshow_stream_t *p_stream = p_sys->pp_streams[i_stream];
  1551.             if( p_stream->p_capture_filter &&
  1552.                 p_stream->p_capture_filter->CustomGetPin()
  1553.                 ->CustomGetSamples( p_stream->samples_queue ) == S_OK )
  1554.             {
  1555.                 i_found_samples = 1;
  1556.             }
  1557.         }
  1558.         if ( !i_found_samples)
  1559.         {
  1560.             /* Didn't find any audio nor video sample, just wait till the
  1561.              * dshow thread pushes some samples */
  1562.             vlc_cond_wait( &p_sys->wait, &p_sys->lock );
  1563.             /* Some DShow thread pushed data, or the OS broke the wait all
  1564.              * by itself. In all cases, it's *strongly* advised to test the
  1565.              * condition again, so let the loop do the test again */
  1566.         }
  1567.     }
  1568.     vlc_mutex_unlock( &p_sys->lock );
  1569.     for ( i_stream = 0; i_stream < p_sys->i_streams; i_stream++ )
  1570.     {
  1571.         int i_samples;
  1572.         dshow_stream_t *p_stream = p_sys->pp_streams[i_stream];
  1573.         i_samples = p_stream->samples_queue.size();
  1574.         while ( i_samples > 0 )
  1575.         {
  1576.             int i_data_size;
  1577.             uint8_t *p_data;
  1578.             block_t *p_block;
  1579.             VLCMediaSample sample;
  1580.             sample = p_stream->samples_queue.front();
  1581.             p_stream->samples_queue.pop_front();
  1582.             i_data_size = sample.p_sample->GetActualDataLength();
  1583.             sample.p_sample->GetPointer( &p_data );
  1584.             REFERENCE_TIME i_pts, i_end_date;
  1585.             HRESULT hr = sample.p_sample->GetTime( &i_pts, &i_end_date );
  1586.             if( hr != VFW_S_NO_STOP_TIME && hr != S_OK ) i_pts = 0;
  1587.             if( !i_pts )
  1588.             {
  1589.                 if( p_stream->mt.majortype == MEDIATYPE_Video || !p_stream->b_pts )
  1590.                 {
  1591.                     /* Use our data timestamp */
  1592.                     i_pts = sample.i_timestamp;
  1593.                     p_stream->b_pts = true;
  1594.                 }
  1595.             }
  1596.             i_pts /= 10; /* Dshow works with 100 nano-seconds resolution */
  1597. #if 0
  1598.             msg_Dbg( p_demux, "Read() stream: %i, size: %i, PTS: %"PRId64,
  1599.                      i_stream, i_data_size, i_pts );
  1600. #endif
  1601.             p_block = block_New( p_demux, i_data_size );
  1602.             vlc_memcpy( p_block->p_buffer, p_data, i_data_size );
  1603.             p_block->i_pts = p_block->i_dts = i_pts;
  1604.             sample.p_sample->Release();
  1605.             es_out_Control( p_demux->out, ES_OUT_SET_PCR, i_pts > 0 ? i_pts : 0 );
  1606.             es_out_Send( p_demux->out, p_stream->p_es, p_block );
  1607.             i_samples--;
  1608.         }
  1609.     }
  1610.     return 1;
  1611. }
  1612. /*****************************************************************************
  1613.  * AccessControl:
  1614.  *****************************************************************************/
  1615. static int AccessControl( access_t *p_access, int i_query, va_list args )
  1616. {
  1617.     bool   *pb_bool;
  1618.     int          *pi_int;
  1619.     int64_t      *pi_64;
  1620.     switch( i_query )
  1621.     {
  1622.     /* */
  1623.     case ACCESS_CAN_SEEK:
  1624.     case ACCESS_CAN_FASTSEEK:
  1625.     case ACCESS_CAN_PAUSE:
  1626.     case ACCESS_CAN_CONTROL_PACE:
  1627.         pb_bool = (bool*)va_arg( args, bool* );
  1628.         *pb_bool = false;
  1629.         break;
  1630.     /* */
  1631.     case ACCESS_GET_PTS_DELAY:
  1632.         pi_64 = (int64_t*)va_arg( args, int64_t * );
  1633.         *pi_64 = (int64_t)var_GetInteger( p_access, "dshow-caching" ) * 1000;
  1634.         break;
  1635.     /* */
  1636.     case ACCESS_SET_PAUSE_STATE:
  1637.     case ACCESS_GET_TITLE_INFO:
  1638.     case ACCESS_SET_TITLE:
  1639.     case ACCESS_SET_SEEKPOINT:
  1640.     case ACCESS_SET_PRIVATE_ID_STATE:
  1641.         return VLC_EGENERIC;
  1642.     default:
  1643.         msg_Warn( p_access, "unimplemented query in control" );
  1644.         return VLC_EGENERIC;
  1645.     }
  1646.     return VLC_SUCCESS;
  1647. }
  1648. /****************************************************************************
  1649.  * DemuxControl:
  1650.  ****************************************************************************/
  1651. static int DemuxControl( demux_t *p_demux, int i_query, va_list args )
  1652. {
  1653.     bool *pb;
  1654.     int64_t    *pi64;
  1655.     switch( i_query )
  1656.     {
  1657.     /* Special for access_demux */
  1658.     case DEMUX_CAN_PAUSE:
  1659.     case DEMUX_CAN_SEEK:
  1660.     case DEMUX_SET_PAUSE_STATE:
  1661.     case DEMUX_CAN_CONTROL_PACE:
  1662.         pb = (bool*)va_arg( args, bool * );
  1663.         *pb = false;
  1664.         return VLC_SUCCESS;
  1665.     case DEMUX_GET_PTS_DELAY:
  1666.         pi64 = (int64_t*)va_arg( args, int64_t * );
  1667.         *pi64 = (int64_t)var_GetInteger( p_demux, "dshow-caching" ) * 1000;
  1668.         return VLC_SUCCESS;
  1669.     case DEMUX_GET_TIME:
  1670.         pi64 = (int64_t*)va_arg( args, int64_t * );
  1671.         *pi64 = mdate();
  1672.         return VLC_SUCCESS;
  1673.     /* TODO implement others */
  1674.     default:
  1675.         return VLC_EGENERIC;
  1676.     }
  1677.     return VLC_EGENERIC;
  1678. }
  1679. /*****************************************************************************
  1680.  * config variable callback
  1681.  *****************************************************************************/
  1682. static int FindDevicesCallback( vlc_object_t *p_this, char const *psz_name,
  1683.                                vlc_value_t newval, vlc_value_t oldval, void * )
  1684. {
  1685.     module_config_t *p_item;
  1686.     bool b_audio = false;
  1687.     int i;
  1688.     p_item = config_FindConfig( p_this, psz_name );
  1689.     if( !p_item ) return VLC_SUCCESS;
  1690.     if( !strcmp( psz_name, "dshow-adev" ) ) b_audio = true;
  1691.     /* Clear-up the current list */
  1692.     if( p_item->i_list )
  1693.     {
  1694.         /* Keep the 2 first entries */
  1695.         for( i = 2; i < p_item->i_list; i++ )
  1696.         {
  1697.             free( const_cast<char *>(p_item->ppsz_list[i]) );
  1698.             free( const_cast<char *>(p_item->ppsz_list_text[i]) );
  1699.         }
  1700.         /* TODO: Remove when no more needed */
  1701.         p_item->ppsz_list[i] = NULL;
  1702.         p_item->ppsz_list_text[i] = NULL;
  1703.     }
  1704.     p_item->i_list = 2;
  1705.     /* Find list of devices */
  1706.     list<string> list_devices;
  1707.     /* Initialize OLE/COM */
  1708.     CoInitialize( 0 );
  1709.     FindCaptureDevice( p_this, NULL, &list_devices, b_audio );
  1710.     /* Uninitialize OLE/COM */
  1711.     CoUninitialize();
  1712.     if( !list_devices.size() ) return VLC_SUCCESS;
  1713.     p_item->ppsz_list =
  1714.         (char **)realloc( p_item->ppsz_list,
  1715.                           (list_devices.size()+3) * sizeof(char *) );
  1716.     p_item->ppsz_list_text =
  1717.         (char **)realloc( p_item->ppsz_list_text,
  1718.                           (list_devices.size()+3) * sizeof(char *) );
  1719.     list<string>::iterator iter;
  1720.     for( iter = list_devices.begin(), i = 2; iter != list_devices.end();
  1721.          iter++, i++ )
  1722.     {
  1723.         p_item->ppsz_list[i] = strdup( iter->c_str() );
  1724.         p_item->ppsz_list_text[i] = NULL;
  1725.         p_item->i_list++;
  1726.     }
  1727.     p_item->ppsz_list[i] = NULL;
  1728.     p_item->ppsz_list_text[i] = NULL;
  1729.     /* Signal change to the interface */
  1730.     p_item->b_dirty = true;
  1731.     return VLC_SUCCESS;
  1732. }
  1733. static int ConfigDevicesCallback( vlc_object_t *p_this, char const *psz_name,
  1734.                                vlc_value_t newval, vlc_value_t oldval, void * )
  1735. {
  1736.     module_config_t *p_item;
  1737.     bool b_audio = false;
  1738.     char *psz_device = NULL;
  1739.     if( !EMPTY_STR( newval.psz_string ) )
  1740.         psz_device = strdup( newval.psz_string );
  1741.     /* Initialize OLE/COM */
  1742.     CoInitialize( 0 );
  1743.     p_item = config_FindConfig( p_this, psz_name );
  1744.     if( !p_item )
  1745.     {
  1746.         free( psz_device );
  1747.         CoUninitialize();
  1748.         return VLC_SUCCESS;
  1749.     }
  1750.     if( !strcmp( psz_name, "dshow-adev" ) ) b_audio = true;
  1751.     string devicename;
  1752.     if( psz_device )
  1753.     {
  1754.         devicename = psz_device ;
  1755.     }
  1756.     else
  1757.     {
  1758.         /* If no device name was specified, pick the 1st one */
  1759.         list<string> list_devices;
  1760.         /* Enumerate devices */
  1761.         FindCaptureDevice( p_this, NULL, &list_devices, b_audio );
  1762.         if( !list_devices.size() )
  1763.         {
  1764.             CoUninitialize();
  1765.             return VLC_EGENERIC;
  1766.         }
  1767.         devicename = *list_devices.begin();
  1768.     }
  1769.     IBaseFilter *p_device_filter =
  1770.         FindCaptureDevice( p_this, &devicename, NULL, b_audio );
  1771.     if( p_device_filter )
  1772.     {
  1773.         ShowPropertyPage( p_device_filter );
  1774.         p_device_filter->Release();
  1775.     }
  1776.     else
  1777.     {
  1778.         /* Uninitialize OLE/COM */
  1779.         CoUninitialize();
  1780.         msg_Err( p_this, "didn't find device: %s", devicename.c_str() );
  1781.         free( psz_device );
  1782.         return VLC_EGENERIC;
  1783.     }
  1784.     /* Uninitialize OLE/COM */
  1785.     CoUninitialize();
  1786.     free( psz_device );
  1787.     return VLC_SUCCESS;
  1788. }
  1789. /*****************************************************************************
  1790.  * Properties
  1791.  *****************************************************************************/
  1792. static void ShowPropertyPage( IUnknown *obj )
  1793. {
  1794.     ISpecifyPropertyPages *p_spec;
  1795.     CAUUID cauuid;
  1796.     HRESULT hr = obj->QueryInterface( IID_ISpecifyPropertyPages,
  1797.                                       (void **)&p_spec );
  1798.     if( FAILED(hr) ) return;
  1799.     if( SUCCEEDED(p_spec->GetPages( &cauuid )) )
  1800.     {
  1801.         if( cauuid.cElems > 0 )
  1802.         {
  1803.             HWND hwnd_desktop = ::GetDesktopWindow();
  1804.             OleCreatePropertyFrame( hwnd_desktop, 30, 30, NULL, 1, &obj,
  1805.                                     cauuid.cElems, cauuid.pElems, 0, 0, NULL );
  1806.             CoTaskMemFree( cauuid.pElems );
  1807.         }
  1808.         p_spec->Release();
  1809.     }
  1810. }
  1811. static void ShowDeviceProperties( vlc_object_t *p_this,
  1812.                                   ICaptureGraphBuilder2 *p_graph,
  1813.                                   IBaseFilter *p_device_filter,
  1814.                                   bool b_audio )
  1815. {
  1816.     HRESULT hr;
  1817.     msg_Dbg( p_this, "configuring Device Properties" );
  1818.     /*
  1819.      * Video or audio capture filter page
  1820.      */
  1821.     ShowPropertyPage( p_device_filter );
  1822.     /*
  1823.      * Audio capture pin
  1824.      */
  1825.     if( p_graph && b_audio )
  1826.     {
  1827.         IAMStreamConfig *p_SC;
  1828.         msg_Dbg( p_this, "showing WDM Audio Configuration Pages" );
  1829.         hr = p_graph->FindInterface( &PIN_CATEGORY_CAPTURE,
  1830.                                      &MEDIATYPE_Audio, p_device_filter,
  1831.                                      IID_IAMStreamConfig, (void **)&p_SC );
  1832.         if( SUCCEEDED(hr) )
  1833.         {
  1834.             ShowPropertyPage(p_SC);
  1835.             p_SC->Release();
  1836.         }
  1837.         /*
  1838.          * TV Audio filter
  1839.          */
  1840.         IAMTVAudio *p_TVA;
  1841.         HRESULT hr = p_graph->FindInterface( &PIN_CATEGORY_CAPTURE,
  1842.                                              &MEDIATYPE_Audio, p_device_filter,
  1843.                                              IID_IAMTVAudio, (void **)&p_TVA );
  1844.         if( SUCCEEDED(hr) )
  1845.         {
  1846.             ShowPropertyPage(p_TVA);
  1847.             p_TVA->Release();
  1848.         }
  1849.     }
  1850.     /*
  1851.      * Video capture pin
  1852.      */
  1853.     if( p_graph && !b_audio )
  1854.     {
  1855.         IAMStreamConfig *p_SC;
  1856.         msg_Dbg( p_this, "showing WDM Video Configuration Pages" );
  1857.         hr = p_graph->FindInterface( &PIN_CATEGORY_CAPTURE,
  1858.                                      &MEDIATYPE_Interleaved, p_device_filter,
  1859.                                      IID_IAMStreamConfig, (void **)&p_SC );
  1860.         if( FAILED(hr) )
  1861.         {
  1862.             hr = p_graph->FindInterface( &PIN_CATEGORY_CAPTURE,
  1863.                                          &MEDIATYPE_Video, p_device_filter,
  1864.                                          IID_IAMStreamConfig, (void **)&p_SC );
  1865.         }
  1866.         if( FAILED(hr) )
  1867.         {
  1868.             hr = p_graph->FindInterface( &PIN_CATEGORY_CAPTURE,
  1869.                                          &MEDIATYPE_Stream, p_device_filter,
  1870.                                          IID_IAMStreamConfig, (void **)&p_SC );
  1871.         }
  1872.         if( SUCCEEDED(hr) )
  1873.         {
  1874.             ShowPropertyPage(p_SC);
  1875.             p_SC->Release();
  1876.         }
  1877.     }
  1878. }
  1879. static void ShowTunerProperties( vlc_object_t *p_this,
  1880.                                  ICaptureGraphBuilder2 *p_graph,
  1881.                                  IBaseFilter *p_device_filter,
  1882.                                  bool b_audio )
  1883. {
  1884.     HRESULT hr;
  1885.     msg_Dbg( p_this, "configuring Tuner Properties" );
  1886.     if( !p_graph || b_audio ) return;
  1887.     IAMTVTuner *p_TV;
  1888.     hr = p_graph->FindInterface( &PIN_CATEGORY_CAPTURE,
  1889.                                  &MEDIATYPE_Interleaved, p_device_filter,
  1890.                                  IID_IAMTVTuner, (void **)&p_TV );
  1891.     if( FAILED(hr) )
  1892.     {
  1893.         hr = p_graph->FindInterface( &PIN_CATEGORY_CAPTURE,
  1894.                                      &MEDIATYPE_Video, p_device_filter,
  1895.                                      IID_IAMTVTuner, (void **)&p_TV );
  1896.     }
  1897.     if( FAILED(hr) )
  1898.     {
  1899.         hr = p_graph->FindInterface( &PIN_CATEGORY_CAPTURE,
  1900.                                      &MEDIATYPE_Stream, p_device_filter,
  1901.                                      IID_IAMTVTuner, (void **)&p_TV );
  1902.     }
  1903.     if( SUCCEEDED(hr) )
  1904.     {
  1905.         ShowPropertyPage(p_TV);
  1906.         p_TV->Release();
  1907.     }
  1908. }
  1909. static void ConfigTuner( vlc_object_t *p_this, ICaptureGraphBuilder2 *p_graph,
  1910.                          IBaseFilter *p_device_filter )
  1911. {
  1912.     int i_channel, i_country, i_input, i_amtuner_mode;
  1913.     long l_modes = 0;
  1914.     IAMTVTuner *p_TV;
  1915.     HRESULT hr;
  1916.     if( !p_graph ) return;
  1917.     i_channel = var_GetInteger( p_this, "dshow-tuner-channel" );
  1918.     i_country = var_GetInteger( p_this, "dshow-tuner-country" );
  1919.     i_input = var_GetInteger( p_this, "dshow-tuner-input" );
  1920.     i_amtuner_mode = var_GetInteger( p_this, "dshow-amtuner-mode" );
  1921.     if( !i_channel && !i_country && !i_input ) return; /* Nothing to do */
  1922.     msg_Dbg( p_this, "tuner config: channel %i, country %i, input type %i",
  1923.              i_channel, i_country, i_input );
  1924.     hr = p_graph->FindInterface( &PIN_CATEGORY_CAPTURE, &MEDIATYPE_Interleaved,
  1925.                                  p_device_filter, IID_IAMTVTuner,
  1926.                                  (void **)&p_TV );
  1927.     if( FAILED(hr) )
  1928.     {
  1929.         hr = p_graph->FindInterface( &PIN_CATEGORY_CAPTURE, &MEDIATYPE_Video,
  1930.                                      p_device_filter, IID_IAMTVTuner,
  1931.                                      (void **)&p_TV );
  1932.     }
  1933.     if( FAILED(hr) )
  1934.     {
  1935.         hr = p_graph->FindInterface( &PIN_CATEGORY_CAPTURE, &MEDIATYPE_Stream,
  1936.                                      p_device_filter, IID_IAMTVTuner,
  1937.                                      (void **)&p_TV );
  1938.     }
  1939.     if( FAILED(hr) )
  1940.     {
  1941.         msg_Dbg( p_this, "couldn't find tuner interface" );
  1942.         return;
  1943.     }
  1944.     hr = p_TV->GetAvailableModes( &l_modes );
  1945.     if( SUCCEEDED(hr) && (l_modes & i_amtuner_mode) )
  1946.     {
  1947.         hr = p_TV->put_Mode( (AMTunerModeType)i_amtuner_mode );
  1948.     }
  1949.     if( i_input == 1 ) p_TV->put_InputType( 0, TunerInputCable );
  1950.     else if( i_input == 2 ) p_TV->put_InputType( 0, TunerInputAntenna );
  1951.     p_TV->put_CountryCode( i_country );
  1952.     p_TV->put_Channel( i_channel, AMTUNER_SUBCHAN_NO_TUNE,
  1953.                        AMTUNER_SUBCHAN_NO_TUNE );
  1954.     p_TV->Release();
  1955. }