dshow.cpp
上传用户:riyaled888
上传日期:2009-03-27
资源大小:7338k
文件大小:58k
源码类别:

多媒体

开发平台:

MultiPlatform

  1. /*****************************************************************************
  2.  * dshow.cpp : DirectShow access module for vlc
  3.  *****************************************************************************
  4.  * Copyright (C) 2002, 2003 VideoLAN
  5.  * $Id: dshow.cpp 9244 2004-11-08 12:24:32Z gbazin $
  6.  *
  7.  * Author: Gildas Bazin <gbazin@videolan.org>
  8.  *
  9.  * This program is free software; you can redistribute it and/or modify
  10.  * it under the terms of the GNU General Public License as published by
  11.  * the Free Software Foundation; either version 2 of the License, or
  12.  * (at your option) any later version.
  13.  *
  14.  * This program is distributed in the hope that it will be useful,
  15.  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  16.  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  17.  * GNU General Public License for more details.
  18.  *
  19.  * You should have received a copy of the GNU General Public License
  20.  * along with this program; if not, write to the Free Software
  21.  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111, USA.
  22.  *****************************************************************************/
  23. /*****************************************************************************
  24.  * Preamble
  25.  *****************************************************************************/
  26. #include <stdlib.h>
  27. #include <stdio.h>
  28. #include <string.h>
  29. #include <vlc/vlc.h>
  30. #include <vlc/input.h>
  31. #include <vlc/vout.h>
  32. #include "common.h"
  33. #include "filter.h"
  34. /*****************************************************************************
  35.  * Access: local prototypes
  36.  *****************************************************************************/
  37. static int ReadCompressed( access_t *, byte_t *, int );
  38. static int AccessControl ( access_t *, int, va_list );
  39. static int Demux       ( demux_t * );
  40. static int DemuxControl( demux_t *, int, va_list );
  41. static int OpenDevice( vlc_object_t *, access_sys_t *, string, vlc_bool_t );
  42. static IBaseFilter *FindCaptureDevice( vlc_object_t *, string *,
  43.                                        list<string> *, vlc_bool_t );
  44. static size_t EnumDeviceCaps( vlc_object_t *, IBaseFilter *,
  45.                               int, int, int, int, int, int,
  46.                               AM_MEDIA_TYPE *mt, size_t );
  47. static bool ConnectFilters( vlc_object_t *, access_sys_t *,
  48.                             IBaseFilter *, CaptureFilter * );
  49. static int FindDevicesCallback( vlc_object_t *, char const *,
  50.                                 vlc_value_t, vlc_value_t, void * );
  51. static int ConfigDevicesCallback( vlc_object_t *, char const *,
  52.                                   vlc_value_t, vlc_value_t, void * );
  53. static void ShowPropertyPage( IUnknown * );
  54. static void ShowDeviceProperties( vlc_object_t *, ICaptureGraphBuilder2 *, 
  55.                                   IBaseFilter *, vlc_bool_t );
  56. static void ShowTunerProperties( vlc_object_t *, ICaptureGraphBuilder2 *, 
  57.                                  IBaseFilter *, vlc_bool_t );
  58. /*****************************************************************************
  59.  * Module descriptor
  60.  *****************************************************************************/
  61. static char *ppsz_vdev[] = { "", "none" };
  62. static char *ppsz_vdev_text[] = { N_("Default"), N_("None") };
  63. static char *ppsz_adev[] = { "", "none" };
  64. static char *ppsz_adev_text[] = { N_("Default"), N_("None") };
  65. #define CACHING_TEXT N_("Caching value in ms")
  66. #define CACHING_LONGTEXT N_( 
  67.     "Allows you to modify the default caching value for DirectShow streams. " 
  68.     "This value should be set in milliseconds units." )
  69. #define VDEV_TEXT N_("Video device name")
  70. #define VDEV_LONGTEXT N_( 
  71.     "You can specify the name of the video device that will be used by the " 
  72.     "DirectShow plugin. If you don't specify anything, the default device " 
  73.     "will be used.")
  74. #define ADEV_TEXT N_("Audio device name")
  75. #define ADEV_LONGTEXT N_( 
  76.     "You can specify the name of the audio device that will be used by the " 
  77.     "DirectShow plugin. If you don't specify anything, the default device " 
  78.     "will be used.")
  79. #define SIZE_TEXT N_("Video size")
  80. #define SIZE_LONGTEXT N_( 
  81.     "You can specify the size of the video that will be displayed by the " 
  82.     "DirectShow plugin. If you don't specify anything the default size for " 
  83.     "your device will be used.")
  84. #define CHROMA_TEXT N_("Video input chroma format")
  85. #define CHROMA_LONGTEXT N_( 
  86.     "Force the DirectShow video input to use a specific chroma format " 
  87.     "(eg. I420 (default), RV24, etc.)")
  88. #define CONFIG_TEXT N_("Device properties")
  89. #define CONFIG_LONGTEXT N_( 
  90.     "Show the properties dialog of the selected device before starting the " 
  91.     "stream.")
  92. #define TUNER_TEXT N_("Tuner properties")
  93. #define TUNER_LONGTEXT N_( 
  94.     "Show the tuner properties [channel selection] page." )
  95. static int  CommonOpen ( vlc_object_t *, access_sys_t *, vlc_bool_t );
  96. static void CommonClose( vlc_object_t *, access_sys_t * );
  97. static int  AccessOpen ( vlc_object_t * );
  98. static void AccessClose( vlc_object_t * );
  99. static int  DemuxOpen  ( vlc_object_t * );
  100. static void DemuxClose ( vlc_object_t * );
  101. vlc_module_begin();
  102.     set_shortname( _("DirectShow") );
  103.     set_description( _("DirectShow input") );
  104.     add_integer( "dshow-caching", (mtime_t)(0.2*CLOCK_FREQ) / 1000, NULL,
  105.                  CACHING_TEXT, CACHING_LONGTEXT, VLC_TRUE );
  106.     add_string( "dshow-vdev", NULL, NULL, VDEV_TEXT, VDEV_LONGTEXT, VLC_FALSE);
  107.         change_string_list( ppsz_vdev, ppsz_vdev_text, FindDevicesCallback );
  108.         change_action_add( FindDevicesCallback, N_("Refresh list") );
  109.         change_action_add( ConfigDevicesCallback, N_("Configure") );
  110.     add_string( "dshow-adev", NULL, NULL, ADEV_TEXT, ADEV_LONGTEXT, VLC_FALSE);
  111.         change_string_list( ppsz_adev, ppsz_adev_text, FindDevicesCallback );
  112.         change_action_add( FindDevicesCallback, N_("Refresh list") );
  113.         change_action_add( ConfigDevicesCallback, N_("Configure") );
  114.     add_string( "dshow-size", NULL, NULL, SIZE_TEXT, SIZE_LONGTEXT, VLC_FALSE);
  115.     add_string( "dshow-chroma", NULL, NULL, CHROMA_TEXT, CHROMA_LONGTEXT,
  116.                 VLC_TRUE );
  117.     add_bool( "dshow-config", VLC_FALSE, NULL, CONFIG_TEXT, CONFIG_LONGTEXT,
  118.               VLC_FALSE );
  119.     add_bool( "dshow-tuner", VLC_FALSE, NULL, TUNER_TEXT, TUNER_LONGTEXT,
  120.               VLC_FALSE );
  121.     add_shortcut( "dshow" );
  122.     set_capability( "access_demux", 0 );
  123.     set_callbacks( DemuxOpen, DemuxClose );
  124.     add_submodule();
  125.     set_description( _("DirectShow input") );
  126.     add_shortcut( "dshow" );
  127.     set_capability( "access2", 0 );
  128.     set_callbacks( AccessOpen, AccessClose );
  129. vlc_module_end();
  130. /*****************************************************************************
  131.  * DirectShow elementary stream descriptor
  132.  *****************************************************************************/
  133. typedef struct dshow_stream_t
  134. {
  135.     string          devicename;
  136.     IBaseFilter     *p_device_filter;
  137.     CaptureFilter   *p_capture_filter;
  138.     AM_MEDIA_TYPE   mt;
  139.     union
  140.     {
  141.       VIDEOINFOHEADER video;
  142.       WAVEFORMATEX    audio;
  143.     } header;
  144.     int             i_fourcc;
  145.     es_out_id_t     *p_es;
  146.     vlc_bool_t      b_pts;
  147. } dshow_stream_t;
  148. /*****************************************************************************
  149.  * DirectShow utility functions
  150.  *****************************************************************************/
  151. static void CreateDirectShowGraph( access_sys_t *p_sys )
  152. {
  153.     p_sys->i_crossbar_route_depth = 0;
  154.     /* Create directshow filter graph */
  155.     if( SUCCEEDED( CoCreateInstance( CLSID_FilterGraph, 0, CLSCTX_INPROC,
  156.                        (REFIID)IID_IFilterGraph, (void **)&p_sys->p_graph) ) )
  157.     {
  158.         /* Create directshow capture graph builder if available */
  159.         if( SUCCEEDED( CoCreateInstance( CLSID_CaptureGraphBuilder2, 0,
  160.                          CLSCTX_INPROC, (REFIID)IID_ICaptureGraphBuilder2,
  161.                          (void **)&p_sys->p_capture_graph_builder2 ) ) )
  162.         {
  163.             p_sys->p_capture_graph_builder2->
  164.                 SetFiltergraph((IGraphBuilder *)p_sys->p_graph);
  165.         }
  166.         p_sys->p_graph->QueryInterface( IID_IMediaControl,
  167.                                         (void **)&p_sys->p_control );
  168.     }
  169. }
  170. static void DeleteDirectShowGraph( access_sys_t *p_sys )
  171. {
  172.     DeleteCrossbarRoutes( p_sys );
  173.     /* Remove filters from graph */
  174.     for( int i = 0; i < p_sys->i_streams; i++ )
  175.     {
  176.         p_sys->p_graph->RemoveFilter( p_sys->pp_streams[i]->p_capture_filter );
  177.         p_sys->p_graph->RemoveFilter( p_sys->pp_streams[i]->p_device_filter );
  178.         p_sys->pp_streams[i]->p_capture_filter->Release();
  179.         p_sys->pp_streams[i]->p_device_filter->Release();
  180.     }
  181.     /* Release directshow objects */
  182.     if( p_sys->p_control )
  183.     {
  184.         p_sys->p_control->Release();
  185.         p_sys->p_control = NULL;
  186.     }
  187.     if( p_sys->p_capture_graph_builder2 )
  188.     {
  189.         p_sys->p_capture_graph_builder2->Release();
  190.         p_sys->p_capture_graph_builder2 = NULL;
  191.     }
  192.     if( p_sys->p_graph )
  193.     {
  194.         p_sys->p_graph->Release();
  195.         p_sys->p_graph = NULL;
  196.     }
  197. }
  198. /*****************************************************************************
  199.  * CommonOpen: open direct show device
  200.  *****************************************************************************/
  201. static int CommonOpen( vlc_object_t *p_this, access_sys_t *p_sys,
  202.                        vlc_bool_t b_access_demux )
  203. {
  204.     vlc_value_t  val;
  205.     int i;
  206.     /* Get/parse options and open device(s) */
  207.     string vdevname, adevname;
  208.     int i_width = 0, i_height = 0, i_chroma = 0;
  209.     vlc_bool_t b_audio = VLC_TRUE;
  210.     var_Create( p_this, "dshow-config", VLC_VAR_BOOL | VLC_VAR_DOINHERIT );
  211.     var_Create( p_this, "dshow-tuner", VLC_VAR_BOOL | VLC_VAR_DOINHERIT );
  212.     var_Create( p_this, "dshow-vdev", VLC_VAR_STRING | VLC_VAR_DOINHERIT );
  213.     var_Get( p_this, "dshow-vdev", &val );
  214.     if( val.psz_string ) vdevname = string( val.psz_string );
  215.     if( val.psz_string ) free( val.psz_string );
  216.     var_Create( p_this, "dshow-adev", VLC_VAR_STRING | VLC_VAR_DOINHERIT );
  217.     var_Get( p_this, "dshow-adev", &val );
  218.     if( val.psz_string ) adevname = string( val.psz_string );
  219.     if( val.psz_string ) free( val.psz_string );
  220.     static struct {char *psz_size; int  i_width; int  i_height;} size_table[] =
  221.     { { "subqcif", 128, 96 }, { "qsif", 160, 120 }, { "qcif", 176, 144 },
  222.       { "sif", 320, 240 }, { "cif", 352, 288 }, { "cif", 640, 480 },
  223.       { 0, 0, 0 },
  224.     };
  225.     var_Create( p_this, "dshow-size", VLC_VAR_STRING | VLC_VAR_DOINHERIT );
  226.     var_Get( p_this, "dshow-size", &val );
  227.     if( val.psz_string && *val.psz_string )
  228.     {
  229.         for( i = 0; size_table[i].psz_size; i++ )
  230.         {
  231.             if( !strcmp( val.psz_string, size_table[i].psz_size ) )
  232.             {
  233.                 i_width = size_table[i].i_width;
  234.                 i_height = size_table[i].i_height;
  235.                 break;
  236.             }
  237.         }
  238.         if( !size_table[i].psz_size ) /* Try to parse "WidthxHeight" */
  239.         {
  240.             char *psz_parser;
  241.             i_width = strtol( val.psz_string, &psz_parser, 0 );
  242.             if( *psz_parser == 'x' || *psz_parser == 'X')
  243.             {
  244.                 i_height = strtol( psz_parser + 1, &psz_parser, 0 );
  245.             }
  246.             msg_Dbg( p_this, "Width x Height %dx%d", i_width, i_height );
  247.         }
  248.     }
  249.     if( val.psz_string ) free( val.psz_string );
  250.     var_Create( p_this, "dshow-chroma", VLC_VAR_STRING | VLC_VAR_DOINHERIT );
  251.     var_Get( p_this, "dshow-chroma", &val );
  252.     if( val.psz_string && strlen( val.psz_string ) >= 4 )
  253.     {
  254.         i_chroma = VLC_FOURCC( val.psz_string[0], val.psz_string[1],
  255.                                val.psz_string[2], val.psz_string[3] );
  256.     }
  257.     if( val.psz_string ) free( val.psz_string );
  258.     var_Create( p_this, "dshow-caching", VLC_VAR_INTEGER | VLC_VAR_DOINHERIT );
  259.     /* Initialize OLE/COM */
  260.     CoInitialize( 0 );
  261.     /* Initialize some data */
  262.     p_sys->i_streams = 0;
  263.     p_sys->pp_streams = 0;
  264.     p_sys->i_width = i_width;
  265.     p_sys->i_height = i_height;
  266.     p_sys->i_chroma = i_chroma;
  267.     p_sys->p_graph = NULL;
  268.     p_sys->p_capture_graph_builder2 = NULL;
  269.     p_sys->p_control = NULL;
  270.     vlc_mutex_init( p_this, &p_sys->lock );
  271.     vlc_cond_init( p_this, &p_sys->wait );
  272.     /* Build directshow graph */
  273.     CreateDirectShowGraph( p_sys );
  274.     if( OpenDevice( p_this, p_sys, vdevname, 0 ) != VLC_SUCCESS )
  275.     {
  276.         msg_Err( p_this, "can't open video");
  277.     }
  278.     else
  279.     {
  280.         /* Check if we can handle the demuxing ourselves or need to spawn
  281.          * a demuxer module */
  282.         dshow_stream_t *p_stream = p_sys->pp_streams[p_sys->i_streams-1];
  283.         if( p_stream->mt.majortype == MEDIATYPE_Video )
  284.         {
  285.             if( /* Raw DV stream */
  286.                 p_stream->i_fourcc == VLC_FOURCC('d','v','s','l') ||
  287.                 p_stream->i_fourcc == VLC_FOURCC('d','v','s','d') ||
  288.                 p_stream->i_fourcc == VLC_FOURCC('d','v','h','d') ||
  289.                 /* Raw MPEG video stream */
  290.                 p_stream->i_fourcc == VLC_FOURCC('m','p','2','v') )
  291.             {
  292.                 b_audio = VLC_FALSE;
  293.                 if( b_access_demux )
  294.                 {
  295.                     /* Let the access (only) take care of that */
  296.                   return VLC_EGENERIC;
  297.                 }
  298.             }
  299.         }
  300.         if( p_stream->mt.majortype == MEDIATYPE_Stream )
  301.         {
  302.             b_audio = VLC_FALSE;
  303.             if( b_access_demux )
  304.             {
  305.                 /* Let the access (only) take care of that */
  306.                 return VLC_EGENERIC;
  307.             }
  308.         }
  309.     }
  310.     if( b_audio && OpenDevice( p_this, p_sys, adevname, 1 ) != VLC_SUCCESS )
  311.     {
  312.         msg_Err( p_this, "can't open audio");
  313.     }
  314.     for( i = p_sys->i_crossbar_route_depth-1; i >= 0 ; --i )
  315.     {
  316.         IAMCrossbar *pXbar = p_sys->crossbar_routes[i].pXbar;
  317.         LONG VideoInputIndex = p_sys->crossbar_routes[i].VideoInputIndex;
  318.         LONG VideoOutputIndex = p_sys->crossbar_routes[i].VideoOutputIndex;
  319.         LONG AudioInputIndex = p_sys->crossbar_routes[i].AudioInputIndex;
  320.         LONG AudioOutputIndex = p_sys->crossbar_routes[i].AudioOutputIndex;
  321.         if( SUCCEEDED(pXbar->Route(VideoOutputIndex, VideoInputIndex)) )
  322.         {
  323.             msg_Dbg( p_this, "Crossbar at depth %d, Routed video "
  324.                      "ouput %ld to video input %ld", i, VideoOutputIndex,
  325.                      VideoInputIndex );
  326.             if( AudioOutputIndex != -1 && AudioInputIndex != -1 )
  327.             {
  328.                 if( SUCCEEDED( pXbar->Route(AudioOutputIndex,
  329.                                             AudioInputIndex)) )
  330.                 {
  331.                     msg_Dbg(p_this, "Crossbar at depth %d, Routed audio "
  332.                             "ouput %ld to audio input %ld", i,
  333.                             AudioOutputIndex, AudioInputIndex );
  334.                 }
  335.             }
  336.         }
  337.     }
  338.     /*
  339.     ** Show properties pages from other filters in graph
  340.     */
  341.     var_Get( p_this, "dshow-config", &val );
  342.     if( val.b_bool )
  343.     {
  344.         for( i = p_sys->i_crossbar_route_depth-1; i >= 0 ; --i )
  345.         {
  346.             IAMCrossbar *pXbar = p_sys->crossbar_routes[i].pXbar;
  347.             IBaseFilter *p_XF;
  348.             if( SUCCEEDED( pXbar->QueryInterface( IID_IBaseFilter,
  349.                                                   (void **)&p_XF ) ) )
  350.             {
  351.                 ShowPropertyPage( p_XF );
  352.                 p_XF->Release();
  353.             }
  354.         }
  355.     }
  356.     /* Initialize some data */
  357.     p_sys->i_current_stream = 0;
  358.     if( !p_sys->i_streams ) return VLC_EGENERIC;
  359.     return VLC_SUCCESS;
  360. }
  361. /*****************************************************************************
  362.  * DemuxOpen: open direct show device as an access_demux module
  363.  *****************************************************************************/
  364. static int DemuxOpen( vlc_object_t *p_this )
  365. {
  366.     demux_t      *p_demux = (demux_t *)p_this;
  367.     access_sys_t *p_sys;
  368.     int i;
  369.     p_sys = (access_sys_t *)malloc( sizeof( access_sys_t ) );
  370.     memset( p_sys, 0, sizeof( access_sys_t ) );
  371.     p_demux->p_sys = (demux_sys_t *)p_sys;
  372.     if( CommonOpen( p_this, p_sys, VLC_TRUE ) != VLC_SUCCESS )
  373.     {
  374.         CommonClose( p_this, p_sys );
  375.         return VLC_EGENERIC;
  376.     }
  377.     /* Everything is ready. Let's rock baby */
  378.     msg_Dbg( p_this, "Playing...");
  379.     p_sys->p_control->Run();
  380.     p_demux->pf_demux   = Demux;
  381.     p_demux->pf_control = DemuxControl;
  382.     p_demux->info.i_update = 0;
  383.     p_demux->info.i_title = 0;
  384.     p_demux->info.i_seekpoint = 0;
  385.     for( i = 0; i < p_sys->i_streams; i++ )
  386.     {
  387.         dshow_stream_t *p_stream = p_sys->pp_streams[i];
  388.         es_format_t fmt;
  389.         if( p_stream->mt.majortype == MEDIATYPE_Video )
  390.         {
  391.             es_format_Init( &fmt, VIDEO_ES, p_stream->i_fourcc );
  392.             fmt.video.i_width  = p_stream->header.video.bmiHeader.biWidth;
  393.             fmt.video.i_height = p_stream->header.video.bmiHeader.biHeight;
  394.             fmt.video.i_aspect = 4 * VOUT_ASPECT_FACTOR / 3;
  395.             if( !p_stream->header.video.bmiHeader.biCompression )
  396.             {
  397.                 /* RGB DIB are coded from bottom to top */
  398.                 fmt.video.i_height = (unsigned int)(-(int)fmt.video.i_height);
  399.             }
  400.             /* Setup rgb mask for RGB formats */
  401.             if( p_stream->i_fourcc == VLC_FOURCC('R','V','2','4') )
  402.             {
  403.                 /* This is in BGR format */
  404.                 fmt.video.i_bmask = 0x00ff0000;
  405.                 fmt.video.i_gmask = 0x0000ff00;
  406.                 fmt.video.i_rmask = 0x000000ff;
  407.             }
  408.         }
  409.         else if( p_stream->mt.majortype == MEDIATYPE_Audio )
  410.         {
  411.             es_format_Init( &fmt, AUDIO_ES, p_stream->i_fourcc );
  412.             fmt.audio.i_channels = p_stream->header.audio.nChannels;
  413.             fmt.audio.i_rate = p_stream->header.audio.nSamplesPerSec;
  414.             fmt.audio.i_bitspersample = p_stream->header.audio.wBitsPerSample;
  415.             fmt.audio.i_blockalign = fmt.audio.i_channels *
  416.                 fmt.audio.i_bitspersample / 8;
  417.             fmt.i_bitrate = fmt.audio.i_channels * fmt.audio.i_rate *
  418.                 fmt.audio.i_bitspersample;
  419.         }
  420.         p_stream->p_es = es_out_Add( p_demux->out, &fmt );
  421.     }
  422.     return VLC_SUCCESS;
  423. }
  424. /*****************************************************************************
  425.  * AccessOpen: open direct show device as an access module
  426.  *****************************************************************************/
  427. static int AccessOpen( vlc_object_t *p_this )
  428. {
  429.     access_t     *p_access = (access_t*)p_this;
  430.     access_sys_t *p_sys;
  431.     p_access->p_sys = p_sys = (access_sys_t *)malloc( sizeof( access_sys_t ) );
  432.     memset( p_sys, 0, sizeof( access_sys_t ) );
  433.     if( CommonOpen( p_this, p_sys, VLC_FALSE ) != VLC_SUCCESS )
  434.     {
  435.         CommonClose( p_this, p_sys );
  436.         return VLC_EGENERIC;
  437.     }
  438.     dshow_stream_t *p_stream = p_sys->pp_streams[0];
  439.     /* Check if we need to force demuxers */
  440.     if( !p_access->psz_demux || !*p_access->psz_demux )
  441.     {
  442.         if( p_stream->i_fourcc == VLC_FOURCC('d','v','s','l') ||
  443.             p_stream->i_fourcc == VLC_FOURCC('d','v','s','d') ||
  444.             p_stream->i_fourcc == VLC_FOURCC('d','v','h','d') )
  445.         {
  446.             p_access->psz_demux = strdup( "rawdv" );
  447.         }
  448.         else if( p_stream->i_fourcc == VLC_FOURCC('m','p','2','v') )
  449.         {
  450.             p_access->psz_demux = "mpgv";
  451.         }
  452.     }
  453.     /* Setup Access */
  454.     p_access->pf_read = ReadCompressed;
  455.     p_access->pf_block = NULL;
  456.     p_access->pf_control = AccessControl;
  457.     p_access->pf_seek = NULL;
  458.     p_access->info.i_update = 0;
  459.     p_access->info.i_size = 0;
  460.     p_access->info.i_pos = 0;
  461.     p_access->info.b_eof = VLC_FALSE;
  462.     p_access->info.i_title = 0;
  463.     p_access->info.i_seekpoint = 0;
  464.     p_access->p_sys = p_sys;
  465.     /* Everything is ready. Let's rock baby */
  466.     msg_Dbg( p_this, "Playing...");
  467.     p_sys->p_control->Run();
  468.     return VLC_SUCCESS;
  469. }
  470. /*****************************************************************************
  471.  * CommonClose: close device
  472.  *****************************************************************************/
  473. static void CommonClose( vlc_object_t *p_this, access_sys_t *p_sys )
  474. {
  475.     msg_Dbg( p_this, "Releasing DirectShow");
  476.     DeleteDirectShowGraph( p_sys );
  477.     /* Uninitialize OLE/COM */
  478.     CoUninitialize();
  479.     /* Remove filters from graph */
  480.     for( int i = 0; i < p_sys->i_streams; i++ ) delete p_sys->pp_streams[i];
  481.     if( p_sys->i_streams ) free( p_sys->pp_streams );
  482.     vlc_mutex_destroy( &p_sys->lock );
  483.     vlc_cond_destroy( &p_sys->wait );
  484.     free( p_sys );
  485. }
  486. /*****************************************************************************
  487.  * AccessClose: close device
  488.  *****************************************************************************/
  489. static void AccessClose( vlc_object_t *p_this )
  490. {
  491.     access_t     *p_access = (access_t *)p_this;
  492.     access_sys_t *p_sys    = p_access->p_sys;
  493.     /* Stop capturing stuff */
  494.     p_sys->p_control->Stop();
  495.     CommonClose( p_this, p_sys );
  496. }
  497. /*****************************************************************************
  498.  * DemuxClose: close device
  499.  *****************************************************************************/
  500. static void DemuxClose( vlc_object_t *p_this )
  501. {
  502.     demux_t      *p_demux = (demux_t *)p_this;
  503.     access_sys_t *p_sys   = (access_sys_t *)p_demux->p_sys;
  504.     /* Stop capturing stuff */
  505.     p_sys->p_control->Stop();
  506.     CommonClose( p_this, p_sys );
  507. }
  508. /****************************************************************************
  509.  * ConnectFilters
  510.  ****************************************************************************/
  511. static bool ConnectFilters( vlc_object_t *p_this, access_sys_t *p_sys,
  512.                             IBaseFilter *p_filter,
  513.                             CaptureFilter *p_capture_filter )
  514. {
  515.     CapturePin *p_input_pin = p_capture_filter->CustomGetPin();
  516.     AM_MEDIA_TYPE mediaType = p_input_pin->CustomGetMediaType();
  517.     if( p_sys->p_capture_graph_builder2 )
  518.     {
  519.         if( FAILED(p_sys->p_capture_graph_builder2->
  520.                 RenderStream( &PIN_CATEGORY_CAPTURE, &mediaType.majortype,
  521.                               p_filter, 0, (IBaseFilter *)p_capture_filter )) )
  522.         {
  523.             return false;
  524.         }
  525.         // Sort out all the possible video inputs
  526.         // The class needs to be given the capture filters ANALOGVIDEO input pin
  527.         IEnumPins *pins = 0;
  528.         if( ( mediaType.majortype == MEDIATYPE_Video ||
  529.               mediaType.majortype == MEDIATYPE_Stream ) &&
  530.             SUCCEEDED(p_filter->EnumPins(&pins)) )
  531.         {
  532.             IPin        *pP = 0;
  533.             ULONG        n;
  534.             PIN_INFO     pinInfo;
  535.             BOOL         Found = FALSE;
  536.             IKsPropertySet *pKs=0;
  537.             GUID guid;
  538.             DWORD dw;
  539.             while( !Found && ( S_OK == pins->Next(1, &pP, &n) ) )
  540.             {
  541.                 if( S_OK == pP->QueryPinInfo(&pinInfo) )
  542.                 {
  543.                     // is this pin an ANALOGVIDEOIN input pin?
  544.                     if( pinInfo.dir == PINDIR_INPUT &&
  545.                         pP->QueryInterface( IID_IKsPropertySet,
  546.                                             (void **)&pKs ) == S_OK )
  547.                     {
  548.                         if( pKs->Get( AMPROPSETID_Pin,
  549.                                       AMPROPERTY_PIN_CATEGORY, NULL, 0,
  550.                                       &guid, sizeof(GUID), &dw ) == S_OK )
  551.                         {
  552.                             if( guid == PIN_CATEGORY_ANALOGVIDEOIN )
  553.                             {
  554.                                 // recursively search crossbar routes
  555.                                 FindCrossbarRoutes( p_this, p_sys, pP, 0 );
  556.                                 // found it
  557.                                 Found = TRUE;
  558.                             }
  559.                         }
  560.                         pKs->Release();
  561.                     }
  562.                     pinInfo.pFilter->Release();
  563.                 }
  564.                 pP->Release();
  565.             }
  566.             pins->Release();
  567.         }
  568.         return true;
  569.     }
  570.     else
  571.     {
  572.         IEnumPins *p_enumpins;
  573.         IPin *p_pin;
  574.         if( S_OK != p_filter->EnumPins( &p_enumpins ) ) return false;
  575.         while( S_OK == p_enumpins->Next( 1, &p_pin, NULL ) )
  576.         {
  577.             PIN_DIRECTION pin_dir;
  578.             p_pin->QueryDirection( &pin_dir );
  579.             if( pin_dir == PINDIR_OUTPUT &&
  580.                 p_sys->p_graph->ConnectDirect( p_pin, (IPin *)p_input_pin,
  581.                                                0 ) == S_OK )
  582.             {
  583.                 p_pin->Release();
  584.                 p_enumpins->Release();
  585.                 return true;
  586.             }
  587.             p_pin->Release();
  588.         }
  589.         p_enumpins->Release();
  590.         return false;
  591.     }
  592. }
  593. /*
  594.  * get fourcc priority from arbritary preference, the higher the better
  595.  */
  596. static int GetFourCCPriority( int i_fourcc )
  597. {
  598.     switch( i_fourcc )
  599.     {
  600.     case VLC_FOURCC('I','4','2','0'):
  601.     case VLC_FOURCC('f','l','3','2'):
  602.         return 9;
  603.     case VLC_FOURCC('Y','V','1','2'):
  604.     case VLC_FOURCC('a','r','a','w'):
  605.         return 8;
  606.     case VLC_FOURCC('R','V','2','4'):
  607.         return 7;
  608.     case VLC_FOURCC('Y','U','Y','2'):
  609.     case VLC_FOURCC('R','V','3','2'):
  610.     case VLC_FOURCC('R','G','B','A'):
  611.         return 6;
  612.     }
  613.     return 0;
  614. }
  615. #define MAX_MEDIA_TYPES 32
  616. static int OpenDevice( vlc_object_t *p_this, access_sys_t *p_sys,
  617.                        string devicename, vlc_bool_t b_audio )
  618. {
  619.     /* See if device is already opened */
  620.     for( int i = 0; i < p_sys->i_streams; i++ )
  621.     {
  622.         if( devicename.size() &&
  623.             p_sys->pp_streams[i]->devicename == devicename )
  624.         {
  625.             /* Already opened */
  626.             return VLC_SUCCESS;
  627.         }
  628.     }
  629.     list<string> list_devices;
  630.     /* Enumerate devices and display their names */
  631.     FindCaptureDevice( p_this, NULL, &list_devices, b_audio );
  632.     if( !list_devices.size() )
  633.         return VLC_EGENERIC;
  634.     list<string>::iterator iter;
  635.     for( iter = list_devices.begin(); iter != list_devices.end(); iter++ )
  636.         msg_Dbg( p_this, "found device: %s", iter->c_str() );
  637.     /* If no device name was specified, pick the 1st one */
  638.     if( devicename.size() == 0 )
  639.     {
  640.         devicename = *list_devices.begin();
  641.     }
  642.     // Use the system device enumerator and class enumerator to find
  643.     // a capture/preview device, such as a desktop USB video camera.
  644.     IBaseFilter *p_device_filter =
  645.         FindCaptureDevice( p_this, &devicename, 0, b_audio );
  646.     if( p_device_filter )
  647.         msg_Dbg( p_this, "using device: %s", devicename.c_str() );
  648.     else
  649.     {
  650.         msg_Err( p_this, "can't use device: %s, unsupported device type",
  651.                  devicename.c_str() );
  652.         return VLC_EGENERIC;
  653.     }
  654.     // Retreive acceptable media types supported by device
  655.     AM_MEDIA_TYPE media_types[MAX_MEDIA_TYPES];
  656.     size_t media_count =
  657.         EnumDeviceCaps( p_this, p_device_filter, p_sys->i_chroma,
  658.                         p_sys->i_width, p_sys->i_height,
  659.                         0, 0, 0, media_types, MAX_MEDIA_TYPES );
  660.     /* Find out if the pin handles MEDIATYPE_Stream, in which case we
  661.      * won't add a prefered media type as this doesn't seem to work well
  662.      * -- to investigate. */
  663.     vlc_bool_t b_stream_type = VLC_FALSE;
  664.     for( size_t i = 0; i < media_count; i++ )
  665.     {
  666.         if( media_types[i].majortype == MEDIATYPE_Stream )
  667.         {
  668.             b_stream_type = VLC_TRUE;
  669.             break;
  670.         }
  671.     }
  672.     size_t mt_count = 0;
  673.     AM_MEDIA_TYPE *mt = NULL;
  674.     if( !b_stream_type && !b_audio )
  675.     {
  676.         // Insert prefered video media type
  677.         AM_MEDIA_TYPE mtr;
  678.         VIDEOINFOHEADER vh;
  679.         mtr.majortype            = MEDIATYPE_Video;
  680.         mtr.subtype              = MEDIASUBTYPE_I420;
  681.         mtr.bFixedSizeSamples    = TRUE;
  682.         mtr.bTemporalCompression = FALSE;
  683.         mtr.pUnk                 = NULL;
  684.         mtr.formattype           = FORMAT_VideoInfo;
  685.         mtr.cbFormat             = sizeof(vh);
  686.         mtr.pbFormat             = (BYTE *)&vh;
  687.         memset(&vh, 0, sizeof(vh));
  688.         vh.bmiHeader.biSize   = sizeof(vh.bmiHeader);
  689.         vh.bmiHeader.biWidth  = p_sys->i_width > 0 ? p_sys->i_width : 320;
  690.         vh.bmiHeader.biHeight = p_sys->i_height > 0 ? p_sys->i_height : 240;
  691.         vh.bmiHeader.biPlanes      = 3;
  692.         vh.bmiHeader.biBitCount    = 12;
  693.         vh.bmiHeader.biCompression = VLC_FOURCC('I','4','2','0');
  694.         vh.bmiHeader.biSizeImage   = vh.bmiHeader.biWidth * 12 *
  695.             vh.bmiHeader.biHeight / 8;
  696.         mtr.lSampleSize            = vh.bmiHeader.biSizeImage;
  697.         mt_count = 1;
  698.         mt = (AM_MEDIA_TYPE *)malloc( sizeof(AM_MEDIA_TYPE)*mt_count );
  699.         CopyMediaType(mt, &mtr);
  700.     }
  701.     else if( !b_stream_type )
  702.     {
  703.         // Insert prefered audio media type
  704.         AM_MEDIA_TYPE mtr;
  705.         WAVEFORMATEX wf;
  706.         mtr.majortype            = MEDIATYPE_Audio;
  707.         mtr.subtype              = MEDIASUBTYPE_PCM;
  708.         mtr.bFixedSizeSamples    = TRUE;
  709.         mtr.bTemporalCompression = FALSE;
  710.         mtr.lSampleSize          = 0;
  711.         mtr.pUnk                 = NULL;
  712.         mtr.formattype           = FORMAT_WaveFormatEx;
  713.         mtr.cbFormat             = sizeof(wf);
  714.         mtr.pbFormat             = (BYTE *)&wf;
  715.         memset(&wf, 0, sizeof(wf));
  716.         wf.wFormatTag = WAVE_FORMAT_PCM;
  717.         wf.nChannels = 2;
  718.         wf.nSamplesPerSec = 44100;
  719.         wf.wBitsPerSample = 16;
  720.         wf.nBlockAlign = wf.nSamplesPerSec * wf.wBitsPerSample / 8;
  721.         wf.nAvgBytesPerSec = wf.nSamplesPerSec * wf.nBlockAlign;
  722.         wf.cbSize = 0;
  723.         mt_count = 1;
  724.         mt = (AM_MEDIA_TYPE *)malloc( sizeof(AM_MEDIA_TYPE)*mt_count );
  725.         CopyMediaType(mt, &mtr);
  726.     }
  727.     if( media_count > 0 )
  728.     {
  729.         mt = (AM_MEDIA_TYPE *)realloc( mt, sizeof(AM_MEDIA_TYPE) *
  730.                                        (mt_count + media_count) );
  731.         // Order and copy returned media types according to arbitrary
  732.         // fourcc priority
  733.         for( size_t c = 0; c < media_count; c++ )
  734.         {
  735.             int slot_priority =
  736.                 GetFourCCPriority(GetFourCCFromMediaType(media_types[c]));
  737.             size_t slot_copy = c;
  738.             for( size_t d = c+1; d < media_count; d++ )
  739.             {
  740.                 int priority =
  741.                     GetFourCCPriority(GetFourCCFromMediaType(media_types[d]));
  742.                 if( priority > slot_priority )
  743.                 {
  744.                     slot_priority = priority;
  745.                     slot_copy = d;
  746.                 }
  747.             }
  748.             if( slot_copy != c )
  749.             {
  750.                 mt[c+mt_count] = media_types[slot_copy];
  751.                 media_types[slot_copy] = media_types[c];
  752.             }
  753.             else
  754.             {
  755.                 mt[c+mt_count] = media_types[c];
  756.             }
  757.         }
  758.         mt_count += media_count;
  759.     }
  760.     /* Create and add our capture filter */
  761.     CaptureFilter *p_capture_filter =
  762.         new CaptureFilter( p_this, p_sys, mt, mt_count );
  763.     p_sys->p_graph->AddFilter( p_capture_filter, 0 );
  764.     /* Add the device filter to the graph (seems necessary with VfW before
  765.      * accessing pin attributes). */
  766.     p_sys->p_graph->AddFilter( p_device_filter, 0 );
  767.     /* Attempt to connect one of this device's capture output pins */
  768.     msg_Dbg( p_this, "connecting filters" );
  769.     if( ConnectFilters( p_this, p_sys, p_device_filter, p_capture_filter ) )
  770.     {
  771.         /* Success */
  772.         msg_Dbg( p_this, "filters connected successfully !" );
  773.         dshow_stream_t dshow_stream;
  774.         dshow_stream.b_pts = VLC_FALSE;
  775.         dshow_stream.p_es = 0;
  776.         dshow_stream.mt =
  777.             p_capture_filter->CustomGetPin()->CustomGetMediaType();
  778.         /* Show Device properties. Done here so the VLC stream is setup with
  779.          * the proper parameters. */
  780.         vlc_value_t val;
  781.         var_Get( p_this, "dshow-config", &val );
  782.         if( val.b_bool )
  783.         {
  784.             ShowDeviceProperties( p_this, p_sys->p_capture_graph_builder2,
  785.                                   p_device_filter, b_audio );
  786.         }
  787.         var_Get( p_this, "dshow-tuner", &val );
  788.         if( val.b_bool )
  789.         {
  790.             ShowTunerProperties( p_this, p_sys->p_capture_graph_builder2,
  791.                                  p_device_filter, b_audio );
  792.         }
  793.         dshow_stream.mt =
  794.             p_capture_filter->CustomGetPin()->CustomGetMediaType();
  795.         dshow_stream.i_fourcc = GetFourCCFromMediaType( dshow_stream.mt );
  796.         if( dshow_stream.i_fourcc )
  797.         {
  798.             if( dshow_stream.mt.majortype == MEDIATYPE_Video )
  799.             {
  800.                 dshow_stream.header.video =
  801.                     *(VIDEOINFOHEADER *)dshow_stream.mt.pbFormat;
  802.                 msg_Dbg( p_this, "MEDIATYPE_Video" );
  803.                 msg_Dbg( p_this, "selected video pin accepts format: %4.4s",
  804.                          (char *)&dshow_stream.i_fourcc);
  805.             }
  806.             else if( dshow_stream.mt.majortype == MEDIATYPE_Audio )
  807.             {
  808.                 dshow_stream.header.audio =
  809.                     *(WAVEFORMATEX *)dshow_stream.mt.pbFormat;
  810.                 msg_Dbg( p_this, "MEDIATYPE_Audio" );
  811.                 msg_Dbg( p_this, "selected audio pin accepts format: %4.4s",
  812.                          (char *)&dshow_stream.i_fourcc);
  813.             }
  814.             else if( dshow_stream.mt.majortype == MEDIATYPE_Stream )
  815.             {
  816.                 msg_Dbg( p_this, "MEDIATYPE_Stream" );
  817.                 msg_Dbg( p_this, "selected stream pin accepts format: %4.4s",
  818.                          (char *)&dshow_stream.i_fourcc);
  819.             }
  820.             else
  821.             {
  822.                 msg_Dbg( p_this, "unknown stream majortype" );
  823.                 goto fail;
  824.             }
  825.             /* Add directshow elementary stream to our list */
  826.             dshow_stream.p_device_filter = p_device_filter;
  827.             dshow_stream.p_capture_filter = p_capture_filter;
  828.             p_sys->pp_streams = (dshow_stream_t **)realloc( p_sys->pp_streams,
  829.                 sizeof(dshow_stream_t *) * (p_sys->i_streams + 1) );
  830.             p_sys->pp_streams[p_sys->i_streams] = new dshow_stream_t;
  831.             *p_sys->pp_streams[p_sys->i_streams++] = dshow_stream;
  832.             return VLC_SUCCESS;
  833.         }
  834.     }
  835.  fail:
  836.     /* Remove filters from graph */
  837.     p_sys->p_graph->RemoveFilter( p_device_filter );
  838.     p_sys->p_graph->RemoveFilter( p_capture_filter );
  839.     /* Release objects */
  840.     p_device_filter->Release();
  841.     p_capture_filter->Release();
  842.     return VLC_EGENERIC;
  843. }
  844. static IBaseFilter *
  845. FindCaptureDevice( vlc_object_t *p_this, string *p_devicename,
  846.                    list<string> *p_listdevices, vlc_bool_t b_audio )
  847. {
  848.     IBaseFilter *p_base_filter = NULL;
  849.     IMoniker *p_moniker = NULL;
  850.     ULONG i_fetched;
  851.     HRESULT hr;
  852.     /* Create the system device enumerator */
  853.     ICreateDevEnum *p_dev_enum = NULL;
  854.     hr = CoCreateInstance( CLSID_SystemDeviceEnum, NULL, CLSCTX_INPROC,
  855.                            IID_ICreateDevEnum, (void **)&p_dev_enum );
  856.     if( FAILED(hr) )
  857.     {
  858.         msg_Err( p_this, "failed to create the device enumerator (0x%lx)", hr);
  859.         return NULL;
  860.     }
  861.     /* Create an enumerator for the video capture devices */
  862.     IEnumMoniker *p_class_enum = NULL;
  863.     if( !b_audio )
  864.         hr = p_dev_enum->CreateClassEnumerator( CLSID_VideoInputDeviceCategory,
  865.                                                 &p_class_enum, 0 );
  866.     else
  867.         hr = p_dev_enum->CreateClassEnumerator( CLSID_AudioInputDeviceCategory,
  868.                                                 &p_class_enum, 0 );
  869.     p_dev_enum->Release();
  870.     if( FAILED(hr) )
  871.     {
  872.         msg_Err( p_this, "failed to create the class enumerator (0x%lx)", hr );
  873.         return NULL;
  874.     }
  875.     /* If there are no enumerators for the requested type, then
  876.      * CreateClassEnumerator will succeed, but p_class_enum will be NULL */
  877.     if( p_class_enum == NULL )
  878.     {
  879.         msg_Err( p_this, "no capture device was detected" );
  880.         return NULL;
  881.     }
  882.     /* Enumerate the devices */
  883.     /* Note that if the Next() call succeeds but there are no monikers,
  884.      * it will return S_FALSE (which is not a failure). Therefore, we check
  885.      * that the return code is S_OK instead of using SUCCEEDED() macro. */
  886.     while( p_class_enum->Next( 1, &p_moniker, &i_fetched ) == S_OK )
  887.     {
  888.         /* Getting the property page to get the device name */
  889.         IPropertyBag *p_bag;
  890.         hr = p_moniker->BindToStorage( 0, 0, IID_IPropertyBag,
  891.                                        (void **)&p_bag );
  892.         if( SUCCEEDED(hr) )
  893.         {
  894.             VARIANT var;
  895.             var.vt = VT_BSTR;
  896.             hr = p_bag->Read( L"FriendlyName", &var, NULL );
  897.             p_bag->Release();
  898.             if( SUCCEEDED(hr) )
  899.             {
  900.                 int i_convert = ( lstrlenW( var.bstrVal ) + 1 ) * 2;
  901.                 char *p_buf = (char *)alloca( i_convert ); p_buf[0] = 0;
  902.                 WideCharToMultiByte( CP_ACP, 0, var.bstrVal, -1, p_buf,
  903.                                      i_convert, NULL, NULL );
  904.                 SysFreeString(var.bstrVal);
  905.                 if( p_listdevices ) p_listdevices->push_back( p_buf );
  906.                 if( p_devicename && *p_devicename == string(p_buf) )
  907.                 {
  908.                     /* Bind Moniker to a filter object */
  909.                     hr = p_moniker->BindToObject( 0, 0, IID_IBaseFilter,
  910.                                                   (void **)&p_base_filter );
  911.                     if( FAILED(hr) )
  912.                     {
  913.                         msg_Err( p_this, "couldn't bind moniker to filter "
  914.                                  "object (0x%lx)", hr );
  915.                         p_moniker->Release();
  916.                         p_class_enum->Release();
  917.                         return NULL;
  918.                     }
  919.                     p_moniker->Release();
  920.                     p_class_enum->Release();
  921.                     return p_base_filter;
  922.                 }
  923.             }
  924.         }
  925.         p_moniker->Release();
  926.     }
  927.     p_class_enum->Release();
  928.     return NULL;
  929. }
  930. static size_t EnumDeviceCaps( vlc_object_t *p_this, IBaseFilter *p_filter,
  931.                               int i_fourcc, int i_width, int i_height,
  932.                               int i_channels, int i_samplespersec,
  933.                               int i_bitspersample, AM_MEDIA_TYPE *mt,
  934.                               size_t mt_max )
  935. {
  936.     IEnumPins *p_enumpins;
  937.     IPin *p_output_pin;
  938.     IEnumMediaTypes *p_enummt;
  939.     size_t mt_count = 0;
  940.     if( FAILED(p_filter->EnumPins( &p_enumpins )) )
  941.     {
  942.         msg_Dbg( p_this, "EnumDeviceCaps failed: no pin enumeration !");
  943.         return 0;
  944.     }
  945.     while( S_OK == p_enumpins->Next( 1, &p_output_pin, NULL ) )
  946.     {
  947.         PIN_INFO info;
  948.         if( S_OK == p_output_pin->QueryPinInfo( &info ) )
  949.         {
  950.             msg_Dbg( p_this, "EnumDeviceCaps: %s pin: %S",
  951.                      info.dir == PINDIR_INPUT ? "input" : "output",
  952.                      info.achName );
  953.             if( info.pFilter ) info.pFilter->Release();
  954.         }
  955.         p_output_pin->Release();
  956.     }
  957.     p_enumpins->Reset();
  958.     while( !mt_count && p_enumpins->Next( 1, &p_output_pin, NULL ) == S_OK )
  959.     {
  960.         PIN_INFO info;
  961.         if( S_OK == p_output_pin->QueryPinInfo( &info ) )
  962.         {
  963.             if( info.pFilter ) info.pFilter->Release();
  964.             if( info.dir == PINDIR_INPUT )
  965.             {
  966.                 p_output_pin->Release();
  967.                 continue;
  968.             }
  969.             msg_Dbg( p_this, "EnumDeviceCaps: trying pin %S", info.achName );
  970.         }
  971.         /* Probe pin */
  972.         if( !SUCCEEDED( p_output_pin->EnumMediaTypes( &p_enummt ) ) )
  973.         {
  974.             p_output_pin->Release();
  975.             continue;
  976.         }
  977.         AM_MEDIA_TYPE *p_mt;
  978.         while( p_enummt->Next( 1, &p_mt, NULL ) == S_OK )
  979.         {
  980.             int i_current_fourcc = GetFourCCFromMediaType( *p_mt );
  981.             if( i_current_fourcc && p_mt->majortype == MEDIATYPE_Video )
  982.             {
  983.                 int i_current_width = p_mt->pbFormat ?
  984.                     ((VIDEOINFOHEADER *)p_mt->pbFormat)->bmiHeader.biWidth :0;
  985.                 int i_current_height = p_mt->pbFormat ?
  986.                     ((VIDEOINFOHEADER *)p_mt->pbFormat)->bmiHeader.biHeight :0;
  987.                 if( i_current_height < 0 )
  988.                     i_current_height = -i_current_height; 
  989.                 msg_Dbg( p_this, "EnumDeviceCaps: input pin "
  990.                          "accepts chroma: %4.4s, width:%i, height:%i",
  991.                          (char *)&i_current_fourcc, i_current_width,
  992.                          i_current_height );
  993.                 if( ( !i_fourcc || i_fourcc == i_current_fourcc ) &&
  994.                     ( !i_width || i_width == i_current_width ) &&
  995.                     ( !i_height || i_height == i_current_height ) &&
  996.                     mt_count < mt_max )
  997.                 {
  998.                     /* Pick match */
  999.                     mt[mt_count++] = *p_mt;
  1000.                 }
  1001.                 else FreeMediaType( *p_mt );
  1002.             }
  1003.             else if( i_current_fourcc && p_mt->majortype == MEDIATYPE_Audio )
  1004.             {
  1005.                 int i_current_channels =
  1006.                     ((WAVEFORMATEX *)p_mt->pbFormat)->nChannels;
  1007.                 int i_current_samplespersec =
  1008.                     ((WAVEFORMATEX *)p_mt->pbFormat)->nSamplesPerSec;
  1009.                 int i_current_bitspersample =
  1010.                     ((WAVEFORMATEX *)p_mt->pbFormat)->wBitsPerSample;
  1011.                 msg_Dbg( p_this, "EnumDeviceCaps: input pin "
  1012.                          "accepts format: %4.4s, channels:%i, "
  1013.                          "samples/sec:%i bits/sample:%i",
  1014.                          (char *)&i_current_fourcc, i_current_channels,
  1015.                          i_current_samplespersec, i_current_bitspersample);
  1016.                 if( (!i_channels || i_channels == i_current_channels) &&
  1017.                     (!i_samplespersec ||
  1018.                      i_samplespersec == i_current_samplespersec) &&
  1019.                     (!i_bitspersample ||
  1020.                      i_bitspersample == i_current_bitspersample) &&
  1021.                     mt_count < mt_max )
  1022.                 {
  1023.                     /* Pick  match */
  1024.                     mt[mt_count++] = *p_mt;
  1025.                     /* Setup a few properties like the audio latency */
  1026.                     IAMBufferNegotiation *p_ambuf;
  1027.                     if( SUCCEEDED( p_output_pin->QueryInterface(
  1028.                           IID_IAMBufferNegotiation, (void **)&p_ambuf ) ) )
  1029.                     {
  1030.                         ALLOCATOR_PROPERTIES AllocProp;
  1031.                         AllocProp.cbAlign = -1;
  1032.                         /* 100 ms of latency */
  1033.                         AllocProp.cbBuffer = i_current_channels *
  1034.                           i_current_samplespersec *
  1035.                           i_current_bitspersample / 8 / 10;
  1036.                         AllocProp.cbPrefix = -1;
  1037.                         AllocProp.cBuffers = -1;
  1038.                         p_ambuf->SuggestAllocatorProperties( &AllocProp );
  1039.                         p_ambuf->Release();
  1040.                     }
  1041.                 }
  1042.                 else FreeMediaType( *p_mt );
  1043.             }
  1044.             else if( i_current_fourcc && p_mt->majortype == MEDIATYPE_Stream )
  1045.             {
  1046.                 msg_Dbg( p_this, "EnumDeviceCaps: input pin "
  1047.                          "accepts stream format: %4.4s",
  1048.                          (char *)&i_current_fourcc );
  1049.                 if( ( !i_fourcc || i_fourcc == i_current_fourcc ) &&
  1050.                     mt_count < mt_max )
  1051.                 {
  1052.                     /* Pick match */
  1053.                     mt[mt_count++] = *p_mt;
  1054.                     i_fourcc = i_current_fourcc;
  1055.                 }
  1056.                 else FreeMediaType( *p_mt );
  1057.             }
  1058.             else
  1059.             {
  1060.                 char *psz_type = "unknown";
  1061.                 if( p_mt->majortype == MEDIATYPE_Video ) psz_type = "video";
  1062.                 if( p_mt->majortype == MEDIATYPE_Audio ) psz_type = "audio";
  1063.                 if( p_mt->majortype == MEDIATYPE_Stream ) psz_type = "stream";
  1064.                 msg_Dbg( p_this, "EnumDeviceCaps: input pin: unknown format "
  1065.                          "(%s %4.4s)", psz_type, (char *)&p_mt->subtype );
  1066.                 FreeMediaType( *p_mt );
  1067.             }
  1068.             CoTaskMemFree( (PVOID)p_mt );
  1069.         }
  1070.         p_enummt->Release();
  1071.         p_output_pin->Release();
  1072.     }
  1073.     p_enumpins->Release();
  1074.     return mt_count;
  1075. }
  1076. /*****************************************************************************
  1077.  * ReadCompressed: reads compressed (MPEG/DV) data from the device.
  1078.  *****************************************************************************
  1079.  * Returns -1 in case of error, 0 in case of EOF, otherwise the number of
  1080.  * bytes.
  1081.  *****************************************************************************/
  1082. static int ReadCompressed( access_t *p_access, uint8_t *p_buffer, int i_len )
  1083. {
  1084.     access_sys_t   *p_sys = p_access->p_sys;
  1085.     dshow_stream_t *p_stream = NULL;
  1086.     VLCMediaSample  sample;
  1087.     int             i_data_size;
  1088.     uint8_t         *p_data;
  1089.     /* Read 1 DV/MPEG frame (they contain the video and audio data) */
  1090.     /* There must be only 1 elementary stream to produce a valid stream
  1091.      * of MPEG or DV data */
  1092.     p_stream = p_sys->pp_streams[0];
  1093.     while( 1 )
  1094.     {
  1095.         if( p_access->b_die || p_access->b_error ) return 0;
  1096.         /* Get new sample/frame from the elementary stream (blocking). */
  1097.         vlc_mutex_lock( &p_sys->lock );
  1098.         if( p_stream->p_capture_filter->CustomGetPin()
  1099.               ->CustomGetSample( &sample ) != S_OK )
  1100.         {
  1101.             /* No data available. Wait until some data has arrived */
  1102.             vlc_cond_wait( &p_sys->wait, &p_sys->lock );
  1103.             vlc_mutex_unlock( &p_sys->lock );
  1104.             continue;
  1105.         }
  1106.         vlc_mutex_unlock( &p_sys->lock );
  1107.         /*
  1108.          * We got our sample
  1109.          */
  1110.         i_data_size = sample.p_sample->GetActualDataLength();
  1111.         sample.p_sample->GetPointer( &p_data );
  1112. #if 0
  1113.         msg_Info( p_access, "access read %i data_size %i", i_len, i_data_size );
  1114. #endif
  1115.         i_data_size = __MIN( i_data_size, (int)i_len );
  1116.         p_access->p_vlc->pf_memcpy( p_buffer, p_data, i_data_size );
  1117.         sample.p_sample->Release();
  1118.         /* The caller got what he wanted */
  1119.         return i_data_size;
  1120.     }
  1121.     return 0; /* never reached */
  1122. }
  1123. /****************************************************************************
  1124.  * Demux:
  1125.  ****************************************************************************/
  1126. static int Demux( demux_t *p_demux )
  1127. {
  1128.     access_sys_t *p_sys = (access_sys_t *)p_demux->p_sys;
  1129.     dshow_stream_t *p_stream = NULL;
  1130.     VLCMediaSample sample;
  1131.     int i_data_size, i_stream;
  1132.     uint8_t *p_data;
  1133.     block_t *p_block;
  1134.     vlc_mutex_lock( &p_sys->lock );
  1135.     /* Try to grab an audio sample (audio has a higher priority) */
  1136.     for( i_stream = 0; i_stream < p_sys->i_streams; i_stream++ )
  1137.     {
  1138.         p_stream = p_sys->pp_streams[i_stream];
  1139.         if( p_stream->mt.majortype == MEDIATYPE_Audio &&
  1140.             p_stream->p_capture_filter &&
  1141.             p_stream->p_capture_filter->CustomGetPin()
  1142.               ->CustomGetSample( &sample ) == S_OK )
  1143.         {
  1144.             break;
  1145.         }
  1146.     }
  1147.     /* Try to grab a video sample */
  1148.     if( i_stream == p_sys->i_streams )
  1149.     for( i_stream = 0; i_stream < p_sys->i_streams; i_stream++ )
  1150.     {
  1151.         p_stream = p_sys->pp_streams[i_stream];
  1152.         if( p_stream->p_capture_filter &&
  1153.             p_stream->p_capture_filter->CustomGetPin()
  1154.                 ->CustomGetSample( &sample ) == S_OK )
  1155.         {
  1156.             break;
  1157.         }
  1158.     }
  1159.     vlc_mutex_unlock( &p_sys->lock );
  1160.     if( i_stream == p_sys->i_streams )
  1161.     {
  1162.         /* Sleep so we do not consume all the cpu, 10ms seems
  1163.          * like a good value (100fps) */
  1164.         msleep( 10000 );
  1165.         return 1;
  1166.     }
  1167.     /*
  1168.      * We got our sample
  1169.      */
  1170.     i_data_size = sample.p_sample->GetActualDataLength();
  1171.     sample.p_sample->GetPointer( &p_data );
  1172.     REFERENCE_TIME i_pts, i_end_date;
  1173.     HRESULT hr = sample.p_sample->GetTime( &i_pts, &i_end_date );
  1174.     if( hr != VFW_S_NO_STOP_TIME && hr != S_OK ) i_pts = 0;
  1175.     if( !i_pts )
  1176.     {
  1177.         if( p_stream->mt.majortype == MEDIATYPE_Video || !p_stream->b_pts )
  1178.         {
  1179.             /* Use our data timestamp */
  1180.             i_pts = sample.i_timestamp;
  1181.             p_stream->b_pts = VLC_TRUE;
  1182.         }
  1183.     }
  1184.     i_pts /= 10; /* Dshow works with 100 nano-seconds resolution */
  1185. #if 0
  1186.     msg_Dbg( p_demux, "Read() stream: %i, size: %i, PTS: "I64Fd,
  1187.              i_stream, i_data_size, i_pts );
  1188. #endif
  1189.     p_block = block_New( p_demux, i_data_size );
  1190.     p_demux->p_vlc->pf_memcpy( p_block->p_buffer, p_data, i_data_size );
  1191.     p_block->i_pts = p_block->i_dts = i_pts;
  1192.     sample.p_sample->Release();
  1193.     es_out_Control( p_demux->out, ES_OUT_SET_PCR, i_pts > 0 ? i_pts : 0 );
  1194.     es_out_Send( p_demux->out, p_stream->p_es, p_block );
  1195.     return 1;
  1196. }
  1197. /*****************************************************************************
  1198.  * AccessControl:
  1199.  *****************************************************************************/
  1200. static int AccessControl( access_t *p_access, int i_query, va_list args )
  1201. {
  1202.     vlc_bool_t   *pb_bool;
  1203.     int          *pi_int;
  1204.     int64_t      *pi_64;
  1205.     switch( i_query )
  1206.     {
  1207.     /* */
  1208.     case ACCESS_CAN_SEEK:
  1209.     case ACCESS_CAN_FASTSEEK:
  1210.     case ACCESS_CAN_PAUSE:
  1211.     case ACCESS_CAN_CONTROL_PACE:
  1212.         pb_bool = (vlc_bool_t*)va_arg( args, vlc_bool_t* );
  1213.         *pb_bool = VLC_FALSE;
  1214.         break;
  1215.     /* */
  1216.     case ACCESS_GET_MTU:
  1217.         pi_int = (int*)va_arg( args, int * );
  1218.         *pi_int = 0;
  1219.         break;
  1220.     case ACCESS_GET_PTS_DELAY:
  1221.         pi_64 = (int64_t*)va_arg( args, int64_t * );
  1222.         *pi_64 = (int64_t)var_GetInteger( p_access, "dshow-caching" ) * 1000;
  1223.         break;
  1224.     /* */
  1225.     case ACCESS_SET_PAUSE_STATE:
  1226.     case ACCESS_GET_TITLE_INFO:
  1227.     case ACCESS_SET_TITLE:
  1228.     case ACCESS_SET_SEEKPOINT:
  1229.     case ACCESS_SET_PRIVATE_ID_STATE:
  1230.         return VLC_EGENERIC;
  1231.     default:
  1232.         msg_Warn( p_access, "unimplemented query in control" );
  1233.         return VLC_EGENERIC;
  1234.     }
  1235.     return VLC_SUCCESS;
  1236. }
  1237. /****************************************************************************
  1238.  * DemuxControl:
  1239.  ****************************************************************************/
  1240. static int DemuxControl( demux_t *p_demux, int i_query, va_list args )
  1241. {
  1242.     vlc_bool_t *pb;
  1243.     int64_t    *pi64;
  1244.     switch( i_query )
  1245.     {
  1246.     /* Special for access_demux */
  1247.     case DEMUX_CAN_PAUSE:
  1248.     case DEMUX_SET_PAUSE_STATE:
  1249.     case DEMUX_CAN_CONTROL_PACE:
  1250.         pb = (vlc_bool_t*)va_arg( args, vlc_bool_t * );
  1251.         *pb = VLC_FALSE;
  1252.         return VLC_SUCCESS;
  1253.     case DEMUX_GET_PTS_DELAY:
  1254.         pi64 = (int64_t*)va_arg( args, int64_t * );
  1255.         *pi64 = (int64_t)var_GetInteger( p_demux, "dshow-caching" ) * 1000;
  1256.         return VLC_SUCCESS;
  1257.     case DEMUX_GET_TIME:
  1258.         pi64 = (int64_t*)va_arg( args, int64_t * );
  1259.         *pi64 = mdate();
  1260.         return VLC_SUCCESS;
  1261.     /* TODO implement others */
  1262.     default:
  1263.         return VLC_EGENERIC;
  1264.     }
  1265.     return VLC_EGENERIC;
  1266. }
  1267. /*****************************************************************************
  1268.  * config variable callback
  1269.  *****************************************************************************/
  1270. static int FindDevicesCallback( vlc_object_t *p_this, char const *psz_name,
  1271.                                vlc_value_t newval, vlc_value_t oldval, void * )
  1272. {
  1273.     module_config_t *p_item;
  1274.     vlc_bool_t b_audio = VLC_FALSE;
  1275.     int i;
  1276.     p_item = config_FindConfig( p_this, psz_name );
  1277.     if( !p_item ) return VLC_SUCCESS;
  1278.     if( !strcmp( psz_name, "dshow-adev" ) ) b_audio = VLC_TRUE;
  1279.     /* Clear-up the current list */
  1280.     if( p_item->i_list )
  1281.     {
  1282.         /* Keep the 2 first entries */
  1283.         for( i = 2; i < p_item->i_list; i++ )
  1284.         {
  1285.             free( p_item->ppsz_list[i] );
  1286.             free( p_item->ppsz_list_text[i] );
  1287.         }
  1288.         /* TODO: Remove when no more needed */
  1289.         p_item->ppsz_list[i] = NULL;
  1290.         p_item->ppsz_list_text[i] = NULL;
  1291.     }
  1292.     p_item->i_list = 2;
  1293.     /* Find list of devices */
  1294.     list<string> list_devices;
  1295.     /* Initialize OLE/COM */
  1296.     CoInitialize( 0 );
  1297.     FindCaptureDevice( p_this, NULL, &list_devices, b_audio );
  1298.     /* Uninitialize OLE/COM */
  1299.     CoUninitialize();
  1300.     if( !list_devices.size() ) return VLC_SUCCESS;
  1301.     p_item->ppsz_list =
  1302.         (char **)realloc( p_item->ppsz_list,
  1303.                           (list_devices.size()+3) * sizeof(char *) );
  1304.     p_item->ppsz_list_text =
  1305.         (char **)realloc( p_item->ppsz_list_text,
  1306.                           (list_devices.size()+3) * sizeof(char *) );
  1307.     list<string>::iterator iter;
  1308.     for( iter = list_devices.begin(), i = 2; iter != list_devices.end();
  1309.          iter++, i++ )
  1310.     {
  1311.         p_item->ppsz_list[i] = strdup( iter->c_str() );
  1312.         p_item->ppsz_list_text[i] = NULL;
  1313.         p_item->i_list++;
  1314.     }
  1315.     p_item->ppsz_list[i] = NULL;
  1316.     p_item->ppsz_list_text[i] = NULL;
  1317.     /* Signal change to the interface */
  1318.     p_item->b_dirty = VLC_TRUE;
  1319.     return VLC_SUCCESS;
  1320. }
  1321. static int ConfigDevicesCallback( vlc_object_t *p_this, char const *psz_name,
  1322.                                vlc_value_t newval, vlc_value_t oldval, void * )
  1323. {
  1324.     module_config_t *p_item;
  1325.     vlc_bool_t b_audio = VLC_FALSE;
  1326.     /* Initialize OLE/COM */
  1327.     CoInitialize( 0 );
  1328.     p_item = config_FindConfig( p_this, psz_name );
  1329.     if( !p_item ) return VLC_SUCCESS;
  1330.     if( !strcmp( psz_name, "dshow-adev" ) ) b_audio = VLC_TRUE;
  1331.     string devicename;
  1332.     if( newval.psz_string && *newval.psz_string )
  1333.     {
  1334.         devicename = newval.psz_string;
  1335.     }
  1336.     else
  1337.     {
  1338.         /* If no device name was specified, pick the 1st one */
  1339.         list<string> list_devices;
  1340.         /* Enumerate devices */
  1341.         FindCaptureDevice( p_this, NULL, &list_devices, b_audio );
  1342.         if( !list_devices.size() ) return VLC_EGENERIC;
  1343.         devicename = *list_devices.begin();
  1344.     }
  1345.     IBaseFilter *p_device_filter =
  1346.         FindCaptureDevice( p_this, &devicename, NULL, b_audio );
  1347.     if( p_device_filter )
  1348.     {
  1349.         ShowPropertyPage( p_device_filter );
  1350.     }
  1351.     else
  1352.     {
  1353.         /* Uninitialize OLE/COM */
  1354.         CoUninitialize();
  1355.         msg_Err( p_this, "didn't find device: %s", devicename.c_str() );
  1356.         return VLC_EGENERIC;
  1357.     }
  1358.     /* Uninitialize OLE/COM */
  1359.     CoUninitialize();
  1360.     return VLC_SUCCESS;
  1361. }
  1362. /*****************************************************************************
  1363.  * Properties
  1364.  *****************************************************************************/
  1365. static void ShowPropertyPage( IUnknown *obj )
  1366. {
  1367.     ISpecifyPropertyPages *p_spec;
  1368.     CAUUID cauuid;
  1369.     HRESULT hr = obj->QueryInterface( IID_ISpecifyPropertyPages,
  1370.                                       (void **)&p_spec );
  1371.     if( FAILED(hr) ) return;
  1372.     if( SUCCEEDED(p_spec->GetPages( &cauuid )) )
  1373.     {
  1374.         if( cauuid.cElems > 0 )
  1375.         {
  1376.             HWND hwnd_desktop = ::GetDesktopWindow();
  1377.             OleCreatePropertyFrame( hwnd_desktop, 30, 30, NULL, 1, &obj,
  1378.                                     cauuid.cElems, cauuid.pElems, 0, 0, NULL );
  1379.             CoTaskMemFree( cauuid.pElems );
  1380.         }
  1381.         p_spec->Release();
  1382.     }
  1383. }
  1384. static void ShowDeviceProperties( vlc_object_t *p_this,
  1385.                                   ICaptureGraphBuilder2 *p_capture_graph,
  1386.                                   IBaseFilter *p_device_filter,
  1387.                                   vlc_bool_t b_audio )
  1388. {
  1389.     HRESULT hr;
  1390.     msg_Dbg( p_this, "Configuring Device Properties" );
  1391.     /*
  1392.      * Video or audio capture filter page
  1393.      */
  1394.     ShowPropertyPage( p_device_filter );
  1395.     /*
  1396.      * Audio capture pin
  1397.      */
  1398.     if( p_capture_graph && b_audio )
  1399.     {
  1400.         IAMStreamConfig *p_SC;
  1401.         msg_Dbg( p_this, "Showing WDM Audio Configuration Pages" );
  1402.         hr = p_capture_graph->FindInterface( &PIN_CATEGORY_CAPTURE,
  1403.                                              &MEDIATYPE_Audio, p_device_filter,
  1404.                                              IID_IAMStreamConfig,
  1405.                                              (void **)&p_SC );
  1406.         if( SUCCEEDED(hr) )
  1407.         {
  1408.             ShowPropertyPage(p_SC);
  1409.             p_SC->Release();
  1410.         }
  1411.         /*
  1412.          * TV Audio filter
  1413.          */
  1414.         IAMTVAudio *p_TVA;
  1415.         HRESULT hr = p_capture_graph->FindInterface( &PIN_CATEGORY_CAPTURE,
  1416.                                              &MEDIATYPE_Audio, p_device_filter,
  1417.                                              IID_IAMTVAudio, (void **)&p_TVA );
  1418.         if( SUCCEEDED(hr) )
  1419.         {
  1420.             ShowPropertyPage(p_TVA);
  1421.             p_TVA->Release();
  1422.         }
  1423.     }
  1424.     /*
  1425.      * Video capture pin
  1426.      */
  1427.     if( p_capture_graph && !b_audio )
  1428.     {
  1429.         IAMStreamConfig *p_SC;
  1430.         msg_Dbg( p_this, "Showing WDM Video Configuration Pages" );
  1431.         hr = p_capture_graph->FindInterface( &PIN_CATEGORY_CAPTURE,
  1432.                                              &MEDIATYPE_Interleaved,
  1433.                                              p_device_filter,
  1434.                                              IID_IAMStreamConfig,
  1435.                                              (void **)&p_SC );
  1436.         if( FAILED(hr) )
  1437.         {
  1438.             hr = p_capture_graph->FindInterface( &PIN_CATEGORY_CAPTURE,
  1439.                                                  &MEDIATYPE_Video,
  1440.                                                  p_device_filter,
  1441.                                                  IID_IAMStreamConfig,
  1442.                                                  (void **)&p_SC );
  1443.         }
  1444.         if( SUCCEEDED(hr) )
  1445.         {
  1446.             ShowPropertyPage(p_SC);
  1447.             p_SC->Release();
  1448.         }
  1449.     }
  1450. }
  1451. static void ShowTunerProperties( vlc_object_t *p_this,
  1452.                                  ICaptureGraphBuilder2 *p_capture_graph,
  1453.                                  IBaseFilter *p_device_filter,
  1454.                                  vlc_bool_t b_audio )
  1455. {
  1456.     HRESULT hr;
  1457.     msg_Dbg( p_this, "Configuring Tuner Properties" );
  1458.     if( p_capture_graph && !b_audio )
  1459.     {
  1460.         IAMTVTuner *p_TV;
  1461.         hr = p_capture_graph->FindInterface( &PIN_CATEGORY_CAPTURE,
  1462.                                              &MEDIATYPE_Interleaved,
  1463.                                              p_device_filter,
  1464.                                              IID_IAMTVTuner, (void **)&p_TV );
  1465.         if( FAILED(hr) )
  1466.         {
  1467.             hr = p_capture_graph->FindInterface( &PIN_CATEGORY_CAPTURE,
  1468.                                                  &MEDIATYPE_Video,
  1469.                                                  p_device_filter,
  1470.                                                  IID_IAMTVTuner,
  1471.                                                  (void **)&p_TV );
  1472.         }
  1473.         if( SUCCEEDED(hr) )
  1474.         {
  1475.             ShowPropertyPage(p_TV);
  1476.             p_TV->Release();
  1477.         }
  1478.     }
  1479. }