/// <summary> /// Adds the TsReader filter to the graph. /// </summary> protected override void AddSourceFilter() { // Render the file _sourceFilter = FilterLoader.LoadFilterFromDll("TsReader.ax", typeof(TsReader).GUID, true); IFileSourceFilter fileSourceFilter = (IFileSourceFilter)_sourceFilter; ITsReader tsReader = (ITsReader)_sourceFilter; tsReader.SetRelaxedMode(1); tsReader.SetTsReaderCallback(this); tsReader.SetRequestAudioChangeCallback(this); _graphBuilder.AddFilter(_sourceFilter, TSREADER_FILTER_NAME); _subtitleRenderer = new SubtitleRenderer(OnTextureInvalidated); _subtitleFilter = _subtitleRenderer.AddSubtitleFilter(_graphBuilder); if (_subtitleFilter != null) { _subtitleRenderer.RenderSubtitles = true; _subtitleRenderer.SetPlayer(this); } if (_resourceLocator.NativeResourcePath.IsNetworkResource) { // _resourceAccessor points to an rtsp:// stream or network file var sourcePathOrUrl = SourcePathOrUrl; if (sourcePathOrUrl == null) { throw new IllegalCallException("The TsVideoPlayer can only play network resources of type INetworkResourceAccessor"); } ServiceRegistration.Get <ILogger>().Debug("{0}: Initializing for stream '{1}'", PlayerTitle, sourcePathOrUrl); int hr = fileSourceFilter.Load(SourcePathOrUrl, null); new HRESULT(hr).Throw(); } else { // _resourceAccessor points to a local or remote mapped .ts file _localFsRaHelper = new LocalFsResourceAccessorHelper(_resourceAccessor); var localFileSystemResourceAccessor = _localFsRaHelper.LocalFsResourceAccessor; if (localFileSystemResourceAccessor == null) { throw new IllegalCallException("The TsVideoPlayer can only play file resources of type ILocalFsResourceAccessor"); } ServiceRegistration.Get <ILogger>().Debug("{0}: Initializing for stream '{1}'", PlayerTitle, localFileSystemResourceAccessor.LocalFileSystemPath); int hr = fileSourceFilter.Load(localFileSystemResourceAccessor.LocalFileSystemPath, null); new HRESULT(hr).Throw(); } // Init GraphRebuilder _graphRebuilder = new GraphRebuilder(_graphBuilder, _sourceFilter, OnAfterGraphRebuild) { PlayerName = PlayerTitle }; }
private void ConfigSourceFilter(IFileSourceFilter filter) { int hr = 0; // Requiered to connect with the avi splitter hr = filter.Load("foo.avi", null); Marshal.ThrowExceptionForHR(hr); }
/// <summary>Initializes the editor.</summary> /// <param name="filepath">The path to the file.</param> public MCRecMetadataEditor(string filepath) : base(filepath) { _editor = (IStreamBufferRecordingAttribute) new StreamBufferRecordingAttributes();//ClassId.CoCreateInstance(ClassId.RecordingAttributes); IFileSourceFilter sourceFilter = (IFileSourceFilter)_editor; sourceFilter.Load(filepath, null); }
public string ChooseSrcFileName() { string ret = null; IFileSourceFilter fsrc = basefilter as IFileSourceFilter; if (fsrc != null) { using (var fd = new OpenFileDialog()) { fd.DefaultExt = "*.*"; if (fd.ShowDialog() == DialogResult.OK) { try { int hr = fsrc.Load(fd.FileName, null); DsError.ThrowExceptionForHR(hr); ret = fd.FileName; } catch (COMException e) { Graph.ShowCOMException(e, "Can't load file " + fd.FileName); } catch (Exception e) { MessageBox.Show(e.Message, "Exception caught while loading file " + fd.FileName); } } else if (Program.mainform.suggestURLs) { using (var rf = new RenderURLForm("Open URL")) { rf.ShowDialog(); if (rf.selectedURL != null) { try { int hr = fsrc.Load(rf.selectedURL, null); DsError.ThrowExceptionForHR(hr); ret = rf.selectedURL; } catch (COMException e) { Graph.ShowCOMException(e, "Can't open " + rf.selectedURL); } catch (Exception e) { MessageBox.Show(e.Message, "Exception caught while loading URL " + rf.selectedURL); } } } //using } }//using } return(ret); }
/// <summary>Get all of the attributes on a file.</summary> /// <returns>A collection of the attributes from the file.</returns> public static IDictionary <string, object> GetAttributes(string path) { IFileSourceFilter sourceFilter = (IFileSourceFilter)Activator.CreateInstance <StreamBufferRecordingAttributes>(); sourceFilter.Load(path, null); IStreamBufferRecordingAttribute editor = (IStreamBufferRecordingAttribute)sourceFilter; return(GetAttributes(editor)); }
private void BuildGraph(string sFileName, bool bLeft) { int hr; IBaseFilter ibfFile = null; IBaseFilter ibfFilter = null; IBaseFilter ibfRender = null; IDMOWrapperFilter dmoWrapperFilter = null; ICaptureGraphBuilder2 icgb = (ICaptureGraphBuilder2) new CaptureGraphBuilder2(); graphBuilder = (IFilterGraph2) new FilterGraph(); #if DEBUG m_rot = new DsROTEntry(graphBuilder); #endif hr = icgb.SetFiltergraph(graphBuilder); DsError.ThrowExceptionForHR(hr); // Add a DMO Wrapper Filter ibfFilter = (IBaseFilter) new DMOWrapperFilter(); dmoWrapperFilter = (IDMOWrapperFilter)ibfFilter; // Since I know the guid of the DMO I am looking for, I can do this. hr = dmoWrapperFilter.Init(new Guid("{EAB6CBA9-78DD-4ae4-9A69-1CE1C55369F6}"), DMOCategory.AudioEffect); DMOError.ThrowExceptionForHR(hr); // Add it to the Graph hr = graphBuilder.AddFilter(ibfFilter, "DMO Filter"); DsError.ThrowExceptionForHR(hr); ibfRender = (IBaseFilter) new AudioRender(); hr = graphBuilder.AddFilter(ibfRender, "Renderer"); DsError.ThrowExceptionForHR(hr); ibfFile = (IBaseFilter) new AsyncReader(); hr = graphBuilder.AddFilter(ibfFile, "Reader"); DsError.ThrowExceptionForHR(hr); IFileSourceFilter ifileSink = (IFileSourceFilter)ibfFile; hr = ifileSink.Load(sFileName, null); DsError.ThrowExceptionForHR(hr); hr = icgb.RenderStream(null, null, ibfFile, null, ibfFilter); DsError.ThrowExceptionForHR(hr); IPin iPin = DsFindPin.ByDirection(ibfFilter, PinDirection.Output, bLeft ? 0 : 1); hr = icgb.RenderStream(null, null, iPin, null, ibfRender); DsError.ThrowExceptionForHR(hr); Marshal.ReleaseComObject(ibfRender); Marshal.ReleaseComObject(dmoWrapperFilter); Marshal.ReleaseComObject(iPin); }
private IFilterGraph2 BuildGraph(string sFileName) { int hr; IBaseFilter ibfRenderer = null; IBaseFilter ibfAVISource = null; IPin IPinIn = null; IPin IPinOut = null; IFilterGraph2 graphBuilder = new FilterGraph() as IFilterGraph2; m_dsrot = new DsROTEntry(graphBuilder); try { // Get the file source filter ibfAVISource = new AsyncReader() as IBaseFilter; // Add it to the graph hr = graphBuilder.AddFilter(ibfAVISource, "Ds.NET AsyncReader"); Marshal.ThrowExceptionForHR(hr); // Set the file name IFileSourceFilter fsf = ibfAVISource as IFileSourceFilter; hr = fsf.Load(sFileName, null); Marshal.ThrowExceptionForHR(hr); IPinOut = DsFindPin.ByDirection(ibfAVISource, PinDirection.Output, 0); // Get the default video renderer ibfRenderer = (IBaseFilter) new VideoRendererDefault(); // Add it to the graph hr = graphBuilder.AddFilter(ibfRenderer, "Ds.NET VideoRendererDefault"); Marshal.ThrowExceptionForHR(hr); IPinIn = DsFindPin.ByDirection(ibfRenderer, PinDirection.Input, 0); hr = graphBuilder.Connect(IPinOut, IPinIn); Marshal.ThrowExceptionForHR(hr); } catch { Marshal.ReleaseComObject(graphBuilder); throw; } finally { Marshal.ReleaseComObject(ibfAVISource); Marshal.ReleaseComObject(ibfRenderer); Marshal.ReleaseComObject(IPinIn); Marshal.ReleaseComObject(IPinOut); } return(graphBuilder); }
private void Config() { m_fg = new FilterGraph() as IFilterGraph2; IBaseFilter streamBuffer = (IBaseFilter) new StreamBufferSource(); int hr; hr = m_fg.AddFilter(streamBuffer, "SBS"); IFileSourceFilter fs = streamBuffer as IFileSourceFilter; hr = fs.Load(@"C:\Users\Public\Recorded TV\Sample Media\win7_scenic-demoshort_raw.wtv", null); m_ISBE2Crossbar = streamBuffer as ISBE2Crossbar; }
/// <summary> /// Adds a source filter to the graph and sets the input. /// </summary> protected override void AddSourceFilter() { if (!_useTsReader) { base.AddSourceFilter(); return; } // Render the file _sourceFilter = FilterLoader.LoadFilterFromDll("TsReader.ax", typeof(TsReader).GUID, true); IFileSourceFilter fileSourceFilter = (IFileSourceFilter)_sourceFilter; ITsReader tsReader = (ITsReader)_sourceFilter; tsReader.SetRelaxedMode(1); tsReader.SetTsReaderCallback(this); tsReader.SetRequestAudioChangeCallback(this); _graphBuilder.AddFilter(_sourceFilter, TSREADER_FILTER_NAME); if (_resourceLocator.NativeResourcePath.IsNetworkResource) { // _resourceAccessor points to an rtsp:// stream or network file var sourcePathOrUrl = SourcePathOrUrl; if (sourcePathOrUrl == null) { throw new IllegalCallException("The LiveRadioPlayer can only play network resources of type INetworkResourceAccessor"); } ServiceRegistration.Get <ILogger>().Debug("{0}: Initializing for stream '{1}'", PlayerTitle, sourcePathOrUrl); int hr = fileSourceFilter.Load(SourcePathOrUrl, null); new HRESULT(hr).Throw(); } else { //_resourceAccessor points to a local .ts file var localFileSystemResourceAccessor = _resourceAccessor as ILocalFsResourceAccessor; if (localFileSystemResourceAccessor == null) { throw new IllegalCallException("The LiveRadioPlayer can only play file resources of type ILocalFsResourceAccessor"); } ServiceRegistration.Get <ILogger>().Debug("{0}: Initializing for stream '{1}'", PlayerTitle, localFileSystemResourceAccessor.LocalFileSystemPath); fileSourceFilter.Load(localFileSystemResourceAccessor.LocalFileSystemPath, null); } }
private void AddLeadNetSrc() { int hr; _netSrc = (IBaseFilter) new LMNetSrcClass(); hr = _graphBuilder.AddFilter(_netSrc, "LEAD Network Source (2.0)"); DsError.ThrowExceptionForHR(hr); _fileSource = (IFileSourceFilter)_netSrc; if (_fileSource == null) { throw new Exception("IFileSourceFilter not found on lmNetSrc"); } LoadNetSrcURL(); }
protected override void OnBeforeGraphRunning() { base.OnBeforeGraphRunning(); IFileSourceFilter fileSourceFilter = FilterGraphTools.FindFilterByInterface <IFileSourceFilter>(_graphBuilder); // First all automatically rendered pins FilterGraphTools.RenderOutputPins(_graphBuilder, (IBaseFilter)fileSourceFilter); Marshal.ReleaseComObject(fileSourceFilter); // MSDN: "During the connection process, the Filter Graph Manager ignores pins on intermediate filters if the pin name begins with a tilde (~)." // then connect the skipped "~" output pins FilterGraphTools.RenderAllManualConnectPins(_graphBuilder); }
private void BuildGraph() { int hr = 0; IBaseFilter filter = null; // Get a GraphBuilder this.graphBuilder = (IGraphBuilder) new FilterGraph(); // And add it a File Source (Async) Filter. filter = (IBaseFilter) new AsyncReader(); this.graphBuilder.AddFilter(filter, "Source"); DsError.ThrowExceptionForHR(hr); // Get a IFileSourceFilter from it this.sourceFilter = (IFileSourceFilter)filter; }
public DVRtoMPEG2TS(StreamSourceInfo sourceConfig, OpenGraphRequest openGraphRequest) : base(sourceConfig, openGraphRequest) { AppLogger.Message("In DVRtoMPEG2TS - CurrentProfile is " + CurrentProfile.Name); InitializeSink(); _captureFilter = AddFilterByName(FilterCategory.LegacyAmFilterCategory, "LEAD DVR Source"); IFileSourceFilter fileSource = (IFileSourceFilter)_captureFilter; String[] sourceNameParts = sourceConfig.SourceName.Split('-'); DVRSettings dvrSettings = DVRSettings.LoadFromFile(); int hr = fileSource.Load(dvrSettings.RootFolder + sourceNameParts[0] + @"/Stream.LBL", null); DsError.ThrowExceptionForHR(hr); ILMDVRSource sourceControl = (ILMDVRSource)_captureFilter; sourceControl.ResetToDefaultsEx(LMDVRSource_APILEVEL.LMDVRSource_APILEVEL_1); _demux = AddFilterByName(FilterCategory.LegacyAmFilterCategory, "LEAD MPEG2 Transport Demultiplexer"); _demuxControl = (ILMMpgDmx)_demux; _demuxControl.AutoLive = true; _demuxControl.AutoLiveTolerance = .5; // _currentVideoSettings = new VideoSettings(); // _currentVideoSettings.CodecType = CurrentProfile.Video.CodecType; ConnectFilters(_captureFilter, "Output", _demux, "Input 01"); if (CurrentProfile.Video != null) { VideoSettings settings = CurrentProfile.Video; _videoDecoder = AddFilterByName(FilterCategory.LegacyAmFilterCategory, "LEAD H264 Decoder (3.0)"); _videoEncoder = AddFilterByName(FilterCategory.LegacyAmFilterCategory, "LEAD H264 Encoder (4.0)"); ConnectFilters(_demux, "H.264 Video", _videoDecoder, "XForm In"); ConnectFilters(_videoDecoder, "XForm Out", _videoEncoder, "XForm In"); LMH264EncoderLib.ILMH264Encoder encoderConfig = (LMH264EncoderLib.ILMH264Encoder)_videoEncoder; encoderConfig.EnableRateControl = true; encoderConfig.BitRate = settings.ConstantBitRate * 1024; ConnectFilterToMux(_videoEncoder, "XForm Out", "Input 01"); } else { ConnectFilterToMux(_demux, "H.264 Video", "Input 01"); } ConnectMuxToSink(); }
private void AddLeadNetSrc(string url) { int hr; _netSrc = AddFilterByDevicePath(@"@device:sw:{083863F1-70DE-11D0-BD40-00A0C911CE86}\{E2B7DE03-38C5-11D5-91F6-00104BDB8FF9}", "LEAD Network Source (2.0"); LMNetSrc lmNetSrc = (LMNetSrc)_netSrc; IFileSourceFilter fileSource = (IFileSourceFilter)_netSrc; if (fileSource == null) { throw new Exception("IFileSourceFilter not found on lmNetSrc"); } AMMediaType mediaType = new AMMediaType(); mediaType.majorType = MediaType.Stream; mediaType.subType = new Guid("8256426B-28BF-4EBD-8EF4-306913875F34"); hr = fileSource.Load(url, mediaType); DsError.ThrowExceptionForHR(hr); }
/// <summary> /// Performs the actual connection to the sink, then connects the LTNetSource to the LTNetDmx /// </summary> /// <param name="ltsfUrl">fully qualified url in ltsf:// format</param> private void DoConnect(string ltsfUrl) { //do network connection at DirectShow level int hr; netFileSource = (IFileSourceFilter)netSource; if (netFileSource == null) { throw new Exception("IFileSourceFilter not found on netSource"); } AMMediaType mediaType = new AMMediaType(); mediaType.majorType = MediaType.Stream; mediaType.subType = MediaSubType.LeadToolsStreamFormat; hr = netFileSource.Load(ltsfUrl, mediaType); DsError.ThrowExceptionForHR(hr); DsUtils.FreeAMMediaType(mediaType); }
/// <summary> /// Add the LEAD DVR Source filter to a graph (builder) and /// load the fileSource using the associated input graph's /// source name (from sourceConfig). For example, if the output /// graph source name was "Vid1-RTSP" then the input graph /// source name will have a name of "Vid1". /// <DVRSourceName> --> <LeftOfSinkSourceName> /// Vid1-RTSP (the output graph source name) --> Vid1 (the input graph source name) /// </summary> public static IBaseFilter GetAndConfigureDVRSourceForSink(IGraphBuilder builder, StreamSourceInfo sourceConfig) { IBaseFilter result = FilterGraphTools.AddFilterByName(builder, FilterCategory.LegacyAmFilterCategory, "LEAD DVR Source"); if (result == null) { throw new Exception("The LEADTOOLS DVR Source filter is not registered"); } IFileSourceFilter fileSource = (IFileSourceFilter)result; String[] sourceNameParts = sourceConfig.SourceName.Split('-'); DVRSettings dvrSettings = DVRSettings.LoadFromFile(); int hr = fileSource.Load(dvrSettings.RootFolder + sourceNameParts[0] + @"/Stream.LBL", null); DsError.ThrowExceptionForHR(hr); ILMDVRSource sourceControl = (ILMDVRSource)result; sourceControl.ResetToDefaultsEx(LMDVRSource_APILEVEL.LMDVRSource_APILEVEL_1); return(result); }
private void Configure2() { int hr; IFilterGraph2 filterGraph = (IFilterGraph2) new FilterGraph(); URLReader u = new URLReader(); m_iop = (IAMOpenProgress)u; IFileSourceFilter fsf = (IFileSourceFilter)u; hr = filterGraph.AddFilter((IBaseFilter)m_iop, "url"); DsError.ThrowExceptionForHR(hr); ThreadStart o2 = new ThreadStart(this.ThreadProc2); Thread thread; thread = new Thread(o2); thread.Name = "cancellor2"; thread.Start(); hr = fsf.Load(@"http://www.LimeGreenSocks.com/test.avi", null); DsError.ThrowExceptionForHR(hr); // -2147467260 m_bLoaded = true; ICaptureGraphBuilder2 icgb = (ICaptureGraphBuilder2) new CaptureGraphBuilder2(); hr = icgb.SetFiltergraph(filterGraph); DsError.ThrowExceptionForHR(hr); hr = icgb.RenderStream(null, null, u, null, null); ((IMediaControl)filterGraph).Run(); while (!m_bQuery) { System.Windows.Forms.Application.DoEvents(); } }
private void SetupGraph2() { int hr; // Get a ICaptureGraphBuilder2 to help build the graph ICaptureGraphBuilder2 icgb2 = (ICaptureGraphBuilder2)new CaptureGraphBuilder2(); try { // Get the graphbuilder object IFilterGraph2 graphBuilder2 = (IFilterGraph2)new FilterGraph(); m_imc2 = graphBuilder2 as IMediaControl; // Link the ICaptureGraphBuilder2 to the IFilterGraph2 hr = icgb2.SetFiltergraph(graphBuilder2); DsError.ThrowExceptionForHR(hr); IBaseFilter streamBuffer = (IBaseFilter)new StreamBufferSource(); hr = graphBuilder2.AddFilter(streamBuffer, "Stream buffer sink"); DsError.ThrowExceptionForHR(hr); IFileSourceFilter sbfsf = (IFileSourceFilter)streamBuffer; hr = sbfsf.Load(Environment.ExpandEnvironmentVariables(FILENAME), null); DsError.ThrowExceptionForHR(hr); RenderPins(streamBuffer, icgb2); m_cb = streamBuffer as ISBE2Crossbar; ISBE2GlobalEvent2 ge2 = streamBuffer as ISBE2GlobalEvent2; } finally { if (icgb2 != null) { Marshal.ReleaseComObject(icgb2); } } }
/// <summary> /// Adds the file source filter to the graph. /// </summary> protected override void AddFileSource() { if (!_useTsReader) { base.AddFileSource(); return; } // Render the file _fileSource = (IBaseFilter) new TsReader(); ITsReader tsReader = (ITsReader)_fileSource; tsReader.SetRelaxedMode(1); tsReader.SetTsReaderCallback(this); tsReader.SetRequestAudioChangeCallback(this); _graphBuilder.AddFilter(_fileSource, TSREADER_FILTER_NAME); IFileSourceFilter f = (IFileSourceFilter)_fileSource; f.Load(SourcePathOrUrl, null); }
private void Config() { int hr; ISBE2Crossbar ISBE2Crossbar; IFilterGraph2 fg; fg = new FilterGraph() as IFilterGraph2; IBaseFilter streamBuffer = (IBaseFilter) new StreamBufferSource(); hr = fg.AddFilter(streamBuffer, "SBS"); IFileSourceFilter fs = streamBuffer as IFileSourceFilter; hr = fs.Load(@"C:\Users\Public\Recorded TV\Sample Media\win7_scenic-demoshort_raw.wtv", null); ISBE2Crossbar = streamBuffer as ISBE2Crossbar; hr = ISBE2Crossbar.EnableDefaultMode(CrossbarDefaultFlags.None); DsError.ThrowExceptionForHR(hr); hr = ISBE2Crossbar.GetInitialProfile(out m_pProfile); DsError.ThrowExceptionForHR(hr); }
/// <summary> /// Adds a source filter to the graph and sets the input. /// </summary> protected override void AddSourceFilter() { if (!IsLocalFilesystemResource) { throw new IllegalCallException("The BDPlayer can only play local file system resources"); } using (((ILocalFsResourceAccessor)_resourceAccessor).EnsureLocalFileSystemAccess()) { string strFile = ((ILocalFsResourceAccessor)_resourceAccessor).LocalFileSystemPath; // Render the file strFile = Path.Combine(strFile.ToLower(), @"BDMV\index.bdmv"); // only continue with playback if a feature was selected or the extension was m2ts. if (DoFeatureSelection(ref strFile)) { // find the SourceFilter CodecInfo sourceFilter = ServiceRegistration.Get <ISettingsManager>().Load <BDPlayerSettings>().BDSourceFilter; // load the SourceFilter if (TryAdd(sourceFilter)) { IFileSourceFilter fileSourceFilter = FilterGraphTools.FindFilterByInterface <IFileSourceFilter>(_graphBuilder); // load the file int hr = fileSourceFilter.Load(strFile, null); Marshal.ReleaseComObject(fileSourceFilter); new HRESULT(hr).Throw(); } else { BDPlayerBuilder.LogError("Unable to load DirectShowFilter: {0}", sourceFilter.Name); throw new Exception("Unable to load DirectShowFilter"); } } } }
public bool Transcode(TranscodeInfo info, VideoFormat format, Quality quality, Standard standard) { try { if (!Supports(format)) { return(false); } string ext = System.IO.Path.GetExtension(info.file); if (ext.ToLower() != ".dvr-ms" && ext.ToLower() != ".sbe") { Log.Info("DVRMS2WMV: wrong file format"); return(false); } Log.Info("DVRMS2WMV: create graph"); graphBuilder = (IGraphBuilder) new FilterGraph(); _rotEntry = new DsROTEntry((IFilterGraph)graphBuilder); Log.Info("DVRMS2WMV: add streambuffersource"); bufferSource = (IStreamBufferSource) new StreamBufferSource(); IBaseFilter filter = (IBaseFilter)bufferSource; graphBuilder.AddFilter(filter, "SBE SOURCE"); Log.Info("DVRMS2WMV: load file:{0}", info.file); IFileSourceFilter fileSource = (IFileSourceFilter)bufferSource; int hr = fileSource.Load(info.file, null); //add mpeg2 audio/video codecs string strVideoCodec = ""; string strAudioCodec = ""; using (MediaPortal.Profile.Settings xmlreader = new MediaPortal.Profile.MPSettings()) { strVideoCodec = xmlreader.GetValueAsString("mytv", "videocodec", "MPC - MPEG-2 Video Decoder (Gabest)"); strAudioCodec = xmlreader.GetValueAsString("mytv", "audiocodec", "MPC - MPA Decoder Filter"); } Log.Info("DVRMS2WMV: add mpeg2 video codec:{0}", strVideoCodec); Mpeg2VideoCodec = DirectShowUtil.AddFilterToGraph(graphBuilder, strVideoCodec); if (hr != 0) { Log.Error("DVRMS2WMV:FAILED:Add mpeg2 video to filtergraph :0x{0:X}", hr); Cleanup(); return(false); } Log.Info("DVRMS2WMV: add mpeg2 audio codec:{0}", strAudioCodec); Mpeg2AudioCodec = DirectShowUtil.AddFilterToGraph(graphBuilder, strAudioCodec); if (Mpeg2AudioCodec == null) { Log.Error("DVRMS2WMV:FAILED:unable to add mpeg2 audio codec"); Cleanup(); return(false); } Log.Info("DVRMS2WMV: connect streambufer source->mpeg audio/video decoders"); //connect output #0 of streambuffer source->mpeg2 audio codec pin 1 //connect output #1 of streambuffer source->mpeg2 video codec pin 1 IPin pinOut0, pinOut1; IPin pinIn0, pinIn1; pinOut0 = DsFindPin.ByDirection((IBaseFilter)bufferSource, PinDirection.Output, 0); //audio pinOut1 = DsFindPin.ByDirection((IBaseFilter)bufferSource, PinDirection.Output, 1); //video if (pinOut0 == null || pinOut1 == null) { Log.Error("DVRMS2WMV:FAILED:unable to get pins of source"); Cleanup(); return(false); } pinIn0 = DsFindPin.ByDirection(Mpeg2VideoCodec, PinDirection.Input, 0); //video pinIn1 = DsFindPin.ByDirection(Mpeg2AudioCodec, PinDirection.Input, 0); //audio if (pinIn0 == null || pinIn1 == null) { Log.Error("DVRMS2WMV:FAILED:unable to get pins of mpeg2 video/audio codec"); Cleanup(); return(false); } hr = graphBuilder.Connect(pinOut0, pinIn1); if (hr != 0) { Log.Error("DVRMS2WMV:FAILED:unable to connect audio pins :0x{0:X}", hr); Cleanup(); return(false); } hr = graphBuilder.Connect(pinOut1, pinIn0); if (hr != 0) { Log.Error("DVRMS2WMV:FAILED:unable to connect video pins :0x{0:X}", hr); Cleanup(); return(false); } string outputFilename = System.IO.Path.ChangeExtension(info.file, ".wmv"); if (!AddWmAsfWriter(outputFilename, quality, standard)) { return(false); } Log.Info("DVRMS2WMV: start pre-run"); mediaControl = graphBuilder as IMediaControl; mediaSeeking = bufferSource as IStreamBufferMediaSeeking; mediaEvt = graphBuilder as IMediaEventEx; mediaPos = graphBuilder as IMediaPosition; //get file duration long lTime = 5 * 60 * 60; lTime *= 10000000; long pStop = 0; hr = mediaSeeking.SetPositions(new DsLong(lTime), AMSeekingSeekingFlags.AbsolutePositioning, new DsLong(pStop), AMSeekingSeekingFlags.NoPositioning); if (hr == 0) { long lStreamPos; mediaSeeking.GetCurrentPosition(out lStreamPos); // stream position m_dDuration = lStreamPos; lTime = 0; mediaSeeking.SetPositions(new DsLong(lTime), AMSeekingSeekingFlags.AbsolutePositioning, new DsLong(pStop), AMSeekingSeekingFlags.NoPositioning); } double duration = m_dDuration / 10000000d; Log.Info("DVRMS2WMV: movie duration:{0}", Util.Utils.SecondsToHMSString((int)duration)); hr = mediaControl.Run(); if (hr != 0) { Log.Error("DVRMS2WMV:FAILED:unable to start graph :0x{0:X}", hr); Cleanup(); return(false); } int maxCount = 20; while (true) { long lCurrent; mediaSeeking.GetCurrentPosition(out lCurrent); double dpos = (double)lCurrent; dpos /= 10000000d; System.Threading.Thread.Sleep(100); if (dpos >= 2.0d) { break; } maxCount--; if (maxCount <= 0) { break; } } Log.Info("DVRMS2WMV: pre-run done"); Log.Info("DVRMS2WMV: Get duration of movie"); mediaControl.Stop(); FilterState state; mediaControl.GetState(500, out state); GC.Collect(); GC.Collect(); GC.Collect(); GC.WaitForPendingFinalizers(); Log.Info("DVRMS2WMV: reconnect mpeg2 video codec->ASF WM Writer"); graphBuilder.RemoveFilter(fileWriterbase); if (!AddWmAsfWriter(outputFilename, quality, standard)) { return(false); } Log.Info("DVRMS2WMV: Start transcoding"); hr = mediaControl.Run(); if (hr != 0) { Log.Error("DVRMS2WMV:FAILED:unable to start graph :0x{0:X}", hr); Cleanup(); return(false); } } catch (Exception e) { // TODO: Handle exceptions. Log.Error("unable to transcode file:{0} message:{1}", info.file, e.Message); return(false); } return(true); }
public bool Transcode(TranscodeInfo info, MediaPortal.Core.Transcoding.VideoFormat format, MediaPortal.Core.Transcoding.Quality quality, Standard standard) { if (!Supports(format)) { return(false); } string ext = System.IO.Path.GetExtension(info.file); if (ext.ToLower() != ".ts" && ext.ToLower() != ".mpg") { Log.Info("TSReader2MP4: wrong file format"); return(false); } try { graphBuilder = (IGraphBuilder) new FilterGraph(); _rotEntry = new DsROTEntry((IFilterGraph)graphBuilder); Log.Info("TSReader2MP4: add filesource"); TsReader reader = new TsReader(); tsreaderSource = (IBaseFilter)reader; IBaseFilter filter = (IBaseFilter)tsreaderSource; graphBuilder.AddFilter(filter, "TSReader Source"); IFileSourceFilter fileSource = (IFileSourceFilter)tsreaderSource; Log.Info("TSReader2MP4: load file:{0}", info.file); int hr = fileSource.Load(info.file, null); //add audio/video codecs string strVideoCodec = ""; string strH264VideoCodec = ""; string strAudioCodec = ""; string strAACAudioCodec = ""; using (MediaPortal.Profile.Settings xmlreader = new MediaPortal.Profile.MPSettings()) { strVideoCodec = xmlreader.GetValueAsString("mytv", "videocodec", ""); strAudioCodec = xmlreader.GetValueAsString("mytv", "audiocodec", ""); strAACAudioCodec = xmlreader.GetValueAsString("mytv", "aacaudiocodec", ""); strH264VideoCodec = xmlreader.GetValueAsString("mytv", "h264videocodec", ""); } //Find the type of decoder required for the output video & audio pins on TSReader. Log.Info("TSReader2MP4: find tsreader compatible audio/video decoders"); IPin pinOut0, pinOut1; IPin pinIn0, pinIn1; pinOut0 = DsFindPin.ByDirection((IBaseFilter)tsreaderSource, PinDirection.Output, 0); //audio pinOut1 = DsFindPin.ByDirection((IBaseFilter)tsreaderSource, PinDirection.Output, 1); //video if (pinOut0 == null || pinOut1 == null) { Log.Error("TSReader2MP4: FAILED: unable to get output pins of tsreader"); Cleanup(); return(false); } bool usingAAC = false; IEnumMediaTypes enumMediaTypes; hr = pinOut0.EnumMediaTypes(out enumMediaTypes); while (true) { AMMediaType[] mediaTypes = new AMMediaType[1]; int typesFetched; hr = enumMediaTypes.Next(1, mediaTypes, out typesFetched); if (hr != 0 || typesFetched == 0) { break; } if (mediaTypes[0].majorType == MediaType.Audio && mediaTypes[0].subType == MediaSubType.LATMAAC) { Log.Info("TSReader2MP4: found LATM AAC audio out pin on tsreader"); usingAAC = true; } } bool usingH264 = false; hr = pinOut1.EnumMediaTypes(out enumMediaTypes); while (true) { AMMediaType[] mediaTypes = new AMMediaType[1]; int typesFetched; hr = enumMediaTypes.Next(1, mediaTypes, out typesFetched); if (hr != 0 || typesFetched == 0) { break; } if (mediaTypes[0].majorType == MediaType.Video && mediaTypes[0].subType == AVC1) { Log.Info("TSReader2MP4: found H.264 video out pin on tsreader"); usingH264 = true; } } //Add the type of decoder required for the output video & audio pins on TSReader. Log.Info("TSReader2MP4: add audio/video decoders to graph"); if (usingH264 == false) { Log.Info("TSReader2MP4: add mpeg2 video decoder:{0}", strVideoCodec); VideoCodec = DirectShowUtil.AddFilterToGraph(graphBuilder, strVideoCodec); if (VideoCodec == null) { Log.Error("TSReader2MP4: unable to add mpeg2 video decoder"); Cleanup(); return(false); } } else { Log.Info("TSReader2MP4: add h264 video codec:{0}", strH264VideoCodec); VideoCodec = DirectShowUtil.AddFilterToGraph(graphBuilder, strH264VideoCodec); if (VideoCodec == null) { Log.Error("TSReader2MP4: FAILED:unable to add h264 video codec"); Cleanup(); return(false); } } if (usingAAC == false) { Log.Info("TSReader2MP4: add mpeg2 audio codec:{0}", strAudioCodec); AudioCodec = DirectShowUtil.AddFilterToGraph(graphBuilder, strAudioCodec); if (AudioCodec == null) { Log.Error("TSReader2MP4: FAILED:unable to add mpeg2 audio codec"); Cleanup(); return(false); } } else { Log.Info("TSReader2MP4: add aac audio codec:{0}", strAACAudioCodec); AudioCodec = DirectShowUtil.AddFilterToGraph(graphBuilder, strAACAudioCodec); if (AudioCodec == null) { Log.Error("TSReader2MP4: FAILED:unable to add aac audio codec"); Cleanup(); return(false); } } Log.Info("TSReader2MP4: connect tsreader->audio/video decoders"); //connect output #0 (audio) of tsreader->audio decoder input pin 0 //connect output #1 (video) of tsreader->video decoder input pin 0 pinIn0 = DsFindPin.ByDirection(AudioCodec, PinDirection.Input, 0); //audio pinIn1 = DsFindPin.ByDirection(VideoCodec, PinDirection.Input, 0); //video if (pinIn0 == null || pinIn1 == null) { Log.Error("TSReader2MP4: FAILED: unable to get pins of video/audio codecs"); Cleanup(); return(false); } hr = graphBuilder.Connect(pinOut0, pinIn0); if (hr != 0) { Log.Error("TSReader2MP4: FAILED: unable to connect audio pins :0x{0:X}", hr); Cleanup(); return(false); } hr = graphBuilder.Connect(pinOut1, pinIn1); if (hr != 0) { Log.Error("TSReader2MP4: FAILED: unable to connect video pins :0x{0:X}", hr); Cleanup(); return(false); } //add encoders, muxer & filewriter if (!AddCodecs(graphBuilder, info)) { return(false); } //setup graph controls mediaControl = graphBuilder as IMediaControl; mediaSeeking = tsreaderSource as IMediaSeeking; mediaEvt = graphBuilder as IMediaEventEx; mediaPos = graphBuilder as IMediaPosition; //get file duration Log.Info("TSReader2MP4: Get duration of recording"); long lTime = 5 * 60 * 60; lTime *= 10000000; long pStop = 0; hr = mediaSeeking.SetPositions(new DsLong(lTime), AMSeekingSeekingFlags.AbsolutePositioning, new DsLong(pStop), AMSeekingSeekingFlags.NoPositioning); if (hr == 0) { long lStreamPos; mediaSeeking.GetCurrentPosition(out lStreamPos); // stream position m_dDuration = lStreamPos; lTime = 0; mediaSeeking.SetPositions(new DsLong(lTime), AMSeekingSeekingFlags.AbsolutePositioning, new DsLong(pStop), AMSeekingSeekingFlags.NoPositioning); } double duration = m_dDuration / 10000000d; Log.Info("TSReader2MP4: recording duration: {0}", MediaPortal.Util.Utils.SecondsToHMSString((int)duration)); //run the graph to initialize the filters to be sure hr = mediaControl.Run(); if (hr != 0) { Log.Error("TSReader2MP4: FAILED: unable to start graph :0x{0:X}", hr); Cleanup(); return(false); } int maxCount = 20; while (true) { long lCurrent; mediaSeeking.GetCurrentPosition(out lCurrent); double dpos = (double)lCurrent; dpos /= 10000000d; System.Threading.Thread.Sleep(100); if (dpos >= 2.0d) { break; } maxCount--; if (maxCount <= 0) { break; } } mediaControl.Stop(); FilterState state; mediaControl.GetState(500, out state); GC.Collect(); GC.Collect(); GC.Collect(); GC.WaitForPendingFinalizers(); graphBuilder.RemoveFilter(mp4Muxer); graphBuilder.RemoveFilter(h264Encoder); graphBuilder.RemoveFilter(aacEncoder); graphBuilder.RemoveFilter((IBaseFilter)fileWriterFilter); if (!AddCodecs(graphBuilder, info)) { return(false); } //Set Encoder quality & Muxer settings if (!EncoderSet(graphBuilder, info)) { return(false); } //start transcoding - run the graph Log.Info("TSReader2MP4: start transcoding"); //setup flow control //need to leverage CBAsePin, CPullPin & IAsyncReader methods. IAsyncReader synchVideo = null; mediaSample = VideoCodec as IMediaSample; hr = synchVideo.SyncReadAligned(mediaSample); //So we only parse decoder output whent the encoders are ready. hr = mediaControl.Run(); if (hr != 0) { Log.Error("TSReader2MP4: FAILED:unable to start graph :0x{0:X}", hr); Cleanup(); return(false); } } catch (Exception ex) { Log.Error("TSReader2MP4: Unable create graph: {0}", ex.Message); Cleanup(); return(false); } return(true); }
/// <summary> /// Adds a source filter to the graph and sets the input. /// </summary> protected override void AddSourceFilter() { if (!_useTsReader) { base.AddSourceFilter(); return; } // Render the file // Notes Morpheus_xx, 2017-04-19: // In contrast to TV we need to use a relative path here, as the method is located inside the SlimTV assembly. // For TV part, the base class inside VideoPlayers is used and thus the correct path to TsReader.ax // The problem with different paths appears only inside RELEASE builds, but not DEBUG. Why this happens I don't know. var platform = IntPtr.Size > 4 ? "x64" : "x86"; _sourceFilter = FilterLoader.LoadFilterFromDll($"..\\VideoPlayers\\{platform}\\TsReader.ax", typeof(TsReader).GUID, true); var baseFilter = _sourceFilter.GetFilter(); IFileSourceFilter fileSourceFilter = (IFileSourceFilter)baseFilter; _tsReader = (ITsReader)baseFilter; _tsReader.SetRelaxedMode(1); _tsReader.SetTsReaderCallback(this); _tsReader.SetRequestAudioChangeCallback(this); _graphBuilder.AddFilter(baseFilter, TSREADER_FILTER_NAME); if (_resourceLocator.NativeResourcePath.IsNetworkResource) { // _resourceAccessor points to an rtsp:// stream or network file var sourcePathOrUrl = SourcePathOrUrl; if (sourcePathOrUrl == null) { throw new IllegalCallException("The LiveRadioPlayer can only play network resources of type INetworkResourceAccessor"); } ServiceRegistration.Get <ILogger>().Debug("{0}: Initializing for stream '{1}'", PlayerTitle, sourcePathOrUrl); IDisposable accessEnsurer = null; if (IsLocalFilesystemResource) { accessEnsurer = ((ILocalFsResourceAccessor)_resourceAccessor).EnsureLocalFileSystemAccess(); } using (accessEnsurer) { int hr = fileSourceFilter.Load(SourcePathOrUrl, null); new HRESULT(hr).Throw(); } } else { //_resourceAccessor points to a local .ts file var localFileSystemResourceAccessor = _resourceAccessor as ILocalFsResourceAccessor; if (localFileSystemResourceAccessor == null) { throw new IllegalCallException("The LiveRadioPlayer can only play file resources of type ILocalFsResourceAccessor"); } using (localFileSystemResourceAccessor.EnsureLocalFileSystemAccess()) { ServiceRegistration.Get <ILogger>().Debug("{0}: Initializing for stream '{1}'", PlayerTitle, localFileSystemResourceAccessor.LocalFileSystemPath); fileSourceFilter.Load(localFileSystemResourceAccessor.LocalFileSystemPath, null); } } }
internal Filter(Graph graph, IBaseFilter filter) { _graph = graph; _filter = filter; _fileSourceFilter = filter as IFileSourceFilter; }
/// <summary> /// Opens the media by initializing the DirectShow graph /// </summary> protected virtual void OpenSource() { /* Make sure we clean up any remaining mess */ FreeResources(); if (m_sourceUri == null) { return; } string fileSource = m_sourceUri.OriginalString; if (string.IsNullOrEmpty(fileSource)) { return; } try { /* Creates the GraphBuilder COM object */ m_graph = new FilterGraphNoThread() as IGraphBuilder; if (m_graph == null) { throw new Exception("Could not create a graph"); } var filterGraph = m_graph as IFilterGraph2; if (filterGraph == null) { throw new Exception("Could not QueryInterface for the IFilterGraph2"); } IBaseFilter sourceFilter; int hr; //var file = System.IO.File.CreateText(@"M:\DirectShowLog.txt"); //filterGraph.SetLogFile((file.BaseStream as System.IO.FileStream).SafeFileHandle.DangerousGetHandle()); // Set LAV Splitter LAVSplitterSource reader = new LAVSplitterSource(); sourceFilter = reader as IBaseFilter; var objectWithSite = reader as IObjectWithSite; if (objectWithSite != null) { objectWithSite.SetSite(this); } hr = m_graph.AddFilter(sourceFilter, SplitterSource); DsError.ThrowExceptionForHR(hr); IFileSourceFilter interfaceFile = (IFileSourceFilter)sourceFilter; hr = interfaceFile.Load(fileSource, null); DsError.ThrowExceptionForHR(hr); // Set Video Codec // Remove Pin var videoPinFrom = DirectShowLib.DsFindPin.ByName(sourceFilter, "Video"); IPin videoPinTo; if (videoPinFrom != null) { hr = videoPinFrom.ConnectedTo(out videoPinTo); if (hr >= 0 && videoPinTo != null) { PinInfo pInfo; videoPinTo.QueryPinInfo(out pInfo); FilterInfo fInfo; pInfo.filter.QueryFilterInfo(out fInfo); DirectShowUtil.DisconnectAllPins(m_graph, pInfo.filter); m_graph.RemoveFilter(pInfo.filter); DsUtils.FreePinInfo(pInfo); Marshal.ReleaseComObject(fInfo.pGraph); Marshal.ReleaseComObject(videoPinTo); videoPinTo = null; } Marshal.ReleaseComObject(videoPinFrom); videoPinFrom = null; } DirectShowUtil.AddFilterToGraph(m_graph, VideoDecoder, Guid.Empty); // Set Audio Codec // Remove Pin var audioPinFrom = DirectShowLib.DsFindPin.ByName(sourceFilter, "Audio"); IPin audioPinTo; if (audioPinFrom != null) { hr = audioPinFrom.ConnectedTo(out audioPinTo); if (hr >= 0 && audioPinTo != null) { PinInfo pInfo; audioPinTo.QueryPinInfo(out pInfo); FilterInfo fInfo; pInfo.filter.QueryFilterInfo(out fInfo); DirectShowUtil.DisconnectAllPins(m_graph, pInfo.filter); m_graph.RemoveFilter(pInfo.filter); DsUtils.FreePinInfo(pInfo); Marshal.ReleaseComObject(fInfo.pGraph); Marshal.ReleaseComObject(audioPinTo); audioPinTo = null; } Marshal.ReleaseComObject(audioPinFrom); audioPinFrom = null; } DirectShowUtil.AddFilterToGraph(m_graph, AudioDecoder, Guid.Empty); /* Add our prefered audio renderer */ InsertAudioRenderer(AudioRenderer); IBaseFilter renderer = CreateVideoRenderer(VideoRenderer, m_graph, 2); /* We will want to enum all the pins on the source filter */ IEnumPins pinEnum; hr = sourceFilter.EnumPins(out pinEnum); DsError.ThrowExceptionForHR(hr); IntPtr fetched = IntPtr.Zero; IPin[] pins = { null }; /* Counter for how many pins successfully rendered */ int pinsRendered = 0; if (VideoRenderer == VideoRendererType.VideoMixingRenderer9) { var mixer = renderer as IVMRMixerControl9; if (mixer != null) { VMR9MixerPrefs dwPrefs; mixer.GetMixingPrefs(out dwPrefs); dwPrefs &= ~VMR9MixerPrefs.RenderTargetMask; dwPrefs |= VMR9MixerPrefs.RenderTargetRGB; //mixer.SetMixingPrefs(dwPrefs); } } /* Test using FFDShow Video Decoder Filter * var ffdshow = new FFDShow() as IBaseFilter; * * if (ffdshow != null) * m_graph.AddFilter(ffdshow, "ffdshow"); */ /* Loop over each pin of the source filter */ while (pinEnum.Next(pins.Length, pins, fetched) == 0) { if (filterGraph.RenderEx(pins[0], AMRenderExFlags.RenderToExistingRenderers, IntPtr.Zero) >= 0) { pinsRendered++; } Marshal.ReleaseComObject(pins[0]); } Marshal.ReleaseComObject(pinEnum); Marshal.ReleaseComObject(sourceFilter); if (pinsRendered == 0) { throw new Exception("Could not render any streams from the source Uri"); } #if DEBUG /* Adds the GB to the ROT so we can view * it in graphedit */ m_dsRotEntry = new DsROTEntry(m_graph); #endif /* Configure the graph in the base class */ SetupFilterGraph(m_graph); HasVideo = true; /* Sets the NaturalVideoWidth/Height */ //SetNativePixelSizes(renderer); } catch (Exception ex) { /* This exection will happen usually if the media does * not exist or could not open due to not having the * proper filters installed */ FreeResources(); /* Fire our failed event */ InvokeMediaFailed(new MediaFailedEventArgs(ex.Message, ex)); } InvokeMediaOpened(); }
// Thread entry point public void WorkerThread() { bool failed = false; // grabber Grabber grabber = new Grabber(this); // objects object graphObj = null; object sourceObj = null; object grabberObj = null; // interfaces IGraphBuilder graph = null; IBaseFilter sourceBase = null; IBaseFilter grabberBase = null; ISampleGrabber sg = null; IFileSourceFilter fileSource = null; IMediaControl mc = null; IMediaEventEx mediaEvent = null; int code, param1, param2; while ((!failed) && (!stopEvent.WaitOne(0, true))) { try { // Get type for filter graph Type srvType = Type.GetTypeFromCLSID(Clsid.FilterGraph); if (srvType == null) { throw new ApplicationException("Failed creating filter graph"); } // create filter graph graphObj = Activator.CreateInstance(srvType); graph = (IGraphBuilder)graphObj; // Get type for windows media source filter srvType = Type.GetTypeFromCLSID(Clsid.WindowsMediaSource); if (srvType == null) { throw new ApplicationException("Failed creating WM source"); } // create windows media source filter sourceObj = Activator.CreateInstance(srvType); sourceBase = (IBaseFilter)sourceObj; // Get type for sample grabber srvType = Type.GetTypeFromCLSID(Clsid.SampleGrabber); if (srvType == null) { throw new ApplicationException("Failed creating sample grabber"); } // create sample grabber grabberObj = Activator.CreateInstance(srvType); sg = (ISampleGrabber)grabberObj; grabberBase = (IBaseFilter)grabberObj; // add source filter to graph graph.AddFilter(sourceBase, "source"); graph.AddFilter(grabberBase, "grabber"); // set media type AMMediaType mt = new AMMediaType(); mt.majorType = MediaType.Video; mt.subType = MediaSubType.RGB24; sg.SetMediaType(mt); // load file fileSource = (IFileSourceFilter)sourceObj; fileSource.Load(this.source, null); // connect pins if (graph.Connect(DSTools.GetOutPin(sourceBase, 0), DSTools.GetInPin(grabberBase, 0)) < 0) { throw new ApplicationException("Failed connecting filters"); } // get media type if (sg.GetConnectedMediaType(mt) == 0) { VideoInfoHeader vih = (VideoInfoHeader)Marshal.PtrToStructure(mt.formatPtr, typeof(VideoInfoHeader)); grabber.Width = vih.BmiHeader.Width; grabber.Height = vih.BmiHeader.Height; mt.Dispose(); } // render graph.Render(DSTools.GetOutPin(grabberBase, 0)); // sg.SetBufferSamples(false); sg.SetOneShot(false); sg.SetCallback(grabber, 1); // window IVideoWindow win = (IVideoWindow)graphObj; win.put_AutoShow(false); win = null; // get events interface mediaEvent = (IMediaEventEx)graphObj; // get media control mc = (IMediaControl)graphObj; // run mc.Run(); while (!stopEvent.WaitOne(0, true)) { Thread.Sleep(100); // get an event if (mediaEvent.GetEvent(out code, out param1, out param2, 0) == 0) { // release params mediaEvent.FreeEventParams(code, param1, param2); // if (code == (int)EventCode.Complete) { break; } } } mc.StopWhenReady(); } // catch any exceptions catch (Exception e) { System.Diagnostics.Debug.WriteLine("----: " + e.Message); failed = true; } // finalization block finally { // release all objects mediaEvent = null; mc = null; fileSource = null; graph = null; sourceBase = null; grabberBase = null; sg = null; if (graphObj != null) { Marshal.ReleaseComObject(graphObj); graphObj = null; } if (sourceObj != null) { Marshal.ReleaseComObject(sourceObj); sourceObj = null; } if (grabberObj != null) { Marshal.ReleaseComObject(grabberObj); grabberObj = null; } } } }
/// <summary> create the used COM components and get the interfaces. </summary> protected bool GetInterfaces() { VMR9Util.g_vmr9 = null; if (IsRadio == false) { Vmr9 = VMR9Util.g_vmr9 = new VMR9Util(); // switch back to directx fullscreen mode Log.Info("RTSPPlayer: Enabling DX9 exclusive mode"); GUIMessage msg = new GUIMessage(GUIMessage.MessageType.GUI_MSG_SWITCH_FULL_WINDOWED, 0, 0, 0, 1, 0, null); GUIWindowManager.SendMessage(msg); } //Type comtype = null; //object comobj = null; DsRect rect = new DsRect(); rect.top = 0; rect.bottom = GUIGraphicsContext.form.Height; rect.left = 0; rect.right = GUIGraphicsContext.form.Width; try { graphBuilder = (IGraphBuilder) new FilterGraph(); Log.Info("RTSPPlayer: add source filter"); if (IsRadio == false) { bool AddVMR9 = VMR9Util.g_vmr9 != null && VMR9Util.g_vmr9.AddVMR9(graphBuilder); if (!AddVMR9) { Log.Error("RTSPPlayer:Failed to add VMR9 to graph"); return(false); } VMR9Util.g_vmr9.Enable(false); } _mpegDemux = (IBaseFilter) new MPEG2Demultiplexer(); graphBuilder.AddFilter(_mpegDemux, "MPEG-2 Demultiplexer"); _rtspSource = (IBaseFilter) new RtpSourceFilter(); int hr = graphBuilder.AddFilter((IBaseFilter)_rtspSource, "RTSP Source Filter"); if (hr != 0) { Log.Error("RTSPPlayer:unable to add RTSP source filter:{0:X}", hr); return(false); } // add preferred video & audio codecs Log.Info("RTSPPlayer: add video/audio codecs"); string strVideoCodec = ""; string strAudioCodec = ""; string strAudiorenderer = ""; int intFilters = 0; // FlipGer: count custom filters string strFilters = ""; // FlipGer: collect custom filters string postProcessingFilterSection = "mytv"; using (Settings xmlreader = new MPSettings()) { if (_mediaType == g_Player.MediaType.Video) { strVideoCodec = xmlreader.GetValueAsString("movieplayer", "mpeg2videocodec", ""); strAudioCodec = xmlreader.GetValueAsString("movieplayer", "mpeg2audiocodec", ""); strAudiorenderer = xmlreader.GetValueAsString("movieplayer", "audiorenderer", "Default DirectSound Device"); postProcessingFilterSection = "movieplayer"; } else { strVideoCodec = xmlreader.GetValueAsString("mytv", "videocodec", ""); strAudioCodec = xmlreader.GetValueAsString("mytv", "audiocodec", ""); strAudiorenderer = xmlreader.GetValueAsString("mytv", "audiorenderer", "Default DirectSound Device"); postProcessingFilterSection = "mytv"; } enableDvbSubtitles = xmlreader.GetValueAsBool("tvservice", "dvbsubtitles", false); // FlipGer: load infos for custom filters int intCount = 0; while (xmlreader.GetValueAsString(postProcessingFilterSection, "filter" + intCount.ToString(), "undefined") != "undefined") { if (xmlreader.GetValueAsBool(postProcessingFilterSection, "usefilter" + intCount.ToString(), false)) { strFilters += xmlreader.GetValueAsString(postProcessingFilterSection, "filter" + intCount.ToString(), "undefined") + ";"; intFilters++; } intCount++; } } string extension = Path.GetExtension(m_strCurrentFile).ToLowerInvariant(); if (IsRadio == false) { if (strVideoCodec.Length > 0) { DirectShowUtil.AddFilterToGraph(graphBuilder, strVideoCodec); } } if (strAudioCodec.Length > 0) { DirectShowUtil.AddFilterToGraph(graphBuilder, strAudioCodec); } if (enableDvbSubtitles == true) { try { _subtitleFilter = SubtitleRenderer.GetInstance().AddSubtitleFilter(graphBuilder); SubtitleRenderer.GetInstance().SetPlayer(this); dvbSubRenderer = SubtitleRenderer.GetInstance(); } catch (Exception e) { Log.Error(e); } } Log.Debug("Is subtitle fitler null? {0}", (_subtitleFilter == null)); // FlipGer: add custom filters to graph string[] arrFilters = strFilters.Split(';'); for (int i = 0; i < intFilters; i++) { DirectShowUtil.AddFilterToGraph(graphBuilder, arrFilters[i]); } if (strAudiorenderer.Length > 0) { audioRendererFilter = DirectShowUtil.AddAudioRendererToGraph(graphBuilder, strAudiorenderer, false); } Log.Info("RTSPPlayer: load:{0}", m_strCurrentFile); IFileSourceFilter interfaceFile = (IFileSourceFilter)_rtspSource; if (interfaceFile == null) { Log.Error("RTSPPlayer:Failed to get IFileSourceFilter"); return(false); } //Log.Info("RTSPPlayer: open file:{0}",filename); hr = interfaceFile.Load(m_strCurrentFile, null); if (hr != 0) { Log.Error("RTSPPlayer:Failed to open file:{0} :0x{1:x}", m_strCurrentFile, hr); return(false); } #region connect rtspsource->demux Log.Info("RTSPPlayer:connect rtspsource->mpeg2 demux"); IPin pinTsOut = DsFindPin.ByDirection((IBaseFilter)_rtspSource, PinDirection.Output, 0); if (pinTsOut == null) { Log.Info("RTSPPlayer:failed to find output pin of tsfilesource"); return(false); } IPin pinDemuxIn = DsFindPin.ByDirection(_mpegDemux, PinDirection.Input, 0); if (pinDemuxIn == null) { Log.Info("RTSPPlayer:failed to find output pin of tsfilesource"); return(false); } hr = graphBuilder.Connect(pinTsOut, pinDemuxIn); if (hr != 0) { Log.Info("RTSPPlayer:failed to connect rtspsource->mpeg2 demux:{0:X}", hr); return(false); } DirectShowUtil.ReleaseComObject(pinTsOut); DirectShowUtil.ReleaseComObject(pinDemuxIn); #endregion #region render demux output pins if (IsRadio) { Log.Info("RTSPPlayer:render audio demux outputs"); IEnumPins enumPins; _mpegDemux.EnumPins(out enumPins); IPin[] pins = new IPin[2]; int fetched = 0; while (enumPins.Next(1, pins, out fetched) == 0) { if (fetched != 1) { break; } PinDirection direction; pins[0].QueryDirection(out direction); if (direction == PinDirection.Input) { continue; } IEnumMediaTypes enumMediaTypes; pins[0].EnumMediaTypes(out enumMediaTypes); AMMediaType[] mediaTypes = new AMMediaType[20]; int fetchedTypes; enumMediaTypes.Next(20, mediaTypes, out fetchedTypes); for (int i = 0; i < fetchedTypes; ++i) { if (mediaTypes[i].majorType == MediaType.Audio) { graphBuilder.Render(pins[0]); break; } } } } else { Log.Info("RTSPPlayer:render audio/video demux outputs"); IEnumPins enumPins; _mpegDemux.EnumPins(out enumPins); IPin[] pins = new IPin[2]; int fetched = 0; while (enumPins.Next(1, pins, out fetched) == 0) { if (fetched != 1) { break; } PinDirection direction; pins[0].QueryDirection(out direction); if (direction == PinDirection.Input) { continue; } graphBuilder.Render(pins[0]); } } #endregion // Connect DVB subtitle filter pins in the graph if (_mpegDemux != null && enableDvbSubtitles == true) { IMpeg2Demultiplexer demuxer = _mpegDemux as IMpeg2Demultiplexer; hr = demuxer.CreateOutputPin(GetTSMedia(), "Pcr", out _pinPcr); if (hr == 0) { Log.Info("RTSPPlayer:_pinPcr OK"); IPin pDemuxerPcr = DsFindPin.ByName(_mpegDemux, "Pcr"); IPin pSubtitlePcr = DsFindPin.ByName(_subtitleFilter, "Pcr"); hr = graphBuilder.Connect(pDemuxerPcr, pSubtitlePcr); } else { Log.Info("RTSPPlayer:Failed to create _pinPcr in demuxer:{0:X}", hr); } hr = demuxer.CreateOutputPin(GetTSMedia(), "Subtitle", out _pinSubtitle); if (hr == 0) { Log.Info("RTSPPlayer:_pinSubtitle OK"); IPin pDemuxerSubtitle = DsFindPin.ByName(_mpegDemux, "Subtitle"); IPin pSubtitle = DsFindPin.ByName(_subtitleFilter, "In"); hr = graphBuilder.Connect(pDemuxerSubtitle, pSubtitle); } else { Log.Info("RTSPPlayer:Failed to create _pinSubtitle in demuxer:{0:X}", hr); } hr = demuxer.CreateOutputPin(GetTSMedia(), "PMT", out _pinPMT); if (hr == 0) { Log.Info("RTSPPlayer:_pinPMT OK"); IPin pDemuxerSubtitle = DsFindPin.ByName(_mpegDemux, "PMT"); IPin pSubtitle = DsFindPin.ByName(_subtitleFilter, "PMT"); hr = graphBuilder.Connect(pDemuxerSubtitle, pSubtitle); } else { Log.Info("RTSPPlayer:Failed to create _pinPMT in demuxer:{0:X}", hr); } } if (IsRadio == false) { if (!VMR9Util.g_vmr9.IsVMR9Connected) { //VMR9 is not supported, switch to overlay Log.Info("RTSPPlayer: vmr9 not connected"); _mediaCtrl = null; Cleanup(); return(false); } VMR9Util.g_vmr9.SetDeinterlaceMode(); } _mediaCtrl = (IMediaControl)graphBuilder; mediaEvt = (IMediaEventEx)graphBuilder; _mediaSeeking = (IMediaSeeking)graphBuilder; mediaPos = (IMediaPosition)graphBuilder; basicAudio = graphBuilder as IBasicAudio; //DirectShowUtil.SetARMode(graphBuilder,AspectRatioMode.Stretched); DirectShowUtil.EnableDeInterlace(graphBuilder); if (VMR9Util.g_vmr9 != null) { m_iVideoWidth = VMR9Util.g_vmr9.VideoWidth; m_iVideoHeight = VMR9Util.g_vmr9.VideoHeight; } if (audioRendererFilter != null) { Log.Info("RTSPPlayer9:set reference clock"); IMediaFilter mp = graphBuilder as IMediaFilter; IReferenceClock clock = audioRendererFilter as IReferenceClock; hr = mp.SetSyncSource(null); hr = mp.SetSyncSource(clock); Log.Info("RTSPPlayer9:set reference clock:{0:X}", hr); } Log.Info("RTSPPlayer: graph build successfull"); return(true); } catch (Exception ex) { Error.SetError("Unable to play movie", "Unable build graph for VMR9"); Log.Error("RTSPPlayer:exception while creating DShow graph {0} {1}", ex.Message, ex.StackTrace); CloseInterfaces(); return(false); } }
static void BuildGraph(IGraphBuilder pGraph, string srcFile1) { int hr = 0; //graph builder ICaptureGraphBuilder2 pBuilder = (ICaptureGraphBuilder2) new CaptureGraphBuilder2(); hr = pBuilder.SetFiltergraph(pGraph); checkHR(hr, "Can't SetFiltergraph"); Guid CLSID_LAVSplitterSource = new Guid("{B98D13E7-55DB-4385-A33D-09FD1BA26338}"); //LAVSplitter.ax Guid CLSID_LAVAudioDecoder = new Guid("{E8E73B6B-4CB3-44A4-BE99-4F7BCB96E491}"); //LAVAudio.ax Guid CLSID_LAVVideoDecoder = new Guid("{EE30215D-164F-4A92-A4EB-9D4C13390F9F}"); //LAVVideo.ax Guid CLSID_VideoRenderer = new Guid("{B87BEB7B-8D29-423F-AE4D-6582C10175AC}"); //quartz.dll //add LAV Splitter Source IBaseFilter pLAVSplitterSource = (IBaseFilter)Activator.CreateInstance(Type.GetTypeFromCLSID(CLSID_LAVSplitterSource)); hr = pGraph.AddFilter(pLAVSplitterSource, "LAV Splitter Source"); checkHR(hr, "Can't add LAV Splitter Source to graph"); //set source filename IFileSourceFilter pLAVSplitterSource_src = pLAVSplitterSource as IFileSourceFilter; if (pLAVSplitterSource_src == null) { checkHR(unchecked ((int)0x80004002), "Can't get IFileSourceFilter"); } hr = pLAVSplitterSource_src.Load(srcFile1, null); checkHR(hr, "Can't load file"); //add LAV Audio Decoder IBaseFilter pLAVAudioDecoder = (IBaseFilter)Activator.CreateInstance(Type.GetTypeFromCLSID(CLSID_LAVAudioDecoder)); hr = pGraph.AddFilter(pLAVAudioDecoder, "LAV Audio Decoder"); checkHR(hr, "Can't add LAV Audio Decoder to graph"); //add LAV Video Decoder IBaseFilter pLAVVideoDecoder = (IBaseFilter)Activator.CreateInstance(Type.GetTypeFromCLSID(CLSID_LAVVideoDecoder)); hr = pGraph.AddFilter(pLAVVideoDecoder, "LAV Video Decoder"); checkHR(hr, "Can't add LAV Video Decoder to graph"); //connect LAV Splitter Source and LAV Video Decoder hr = pGraph.ConnectDirect(GetPin(pLAVSplitterSource, "Video"), GetPin(pLAVVideoDecoder, "Input"), null); checkHR(hr, "Can't connect LAV Splitter Source and LAV Video Decoder"); //connect LAV Splitter Source and LAV Audio Decoder hr = pGraph.ConnectDirect(GetPin(pLAVSplitterSource, "Audio"), GetPin(pLAVAudioDecoder, "Input"), null); checkHR(hr, "Can't connect LAV Splitter Source and LAV Audio Decoder"); //add Video Renderer IBaseFilter pVideoRenderer = (IBaseFilter)Activator.CreateInstance(Type.GetTypeFromCLSID(CLSID_VideoRenderer)); hr = pGraph.AddFilter(pVideoRenderer, "Video Renderer"); checkHR(hr, "Can't add Video Renderer to graph"); //add Default DirectSound Device IBaseFilter pDefaultDirectSoundDevice = (IBaseFilter) new DSoundRender(); hr = pGraph.AddFilter(pDefaultDirectSoundDevice, "Default DirectSound Device"); checkHR(hr, "Can't add Default DirectSound Device to graph"); //connect LAV Video Decoder and Video Renderer hr = pGraph.ConnectDirect(GetPin(pLAVVideoDecoder, "Output"), GetPin(pVideoRenderer, "VMR Input0"), null); checkHR(hr, "Can't connect LAV Video Decoder and Video Renderer"); //connect LAV Audio Decoder and Default DirectSound Device hr = pGraph.ConnectDirect(GetPin(pLAVAudioDecoder, "Output"), GetPin(pDefaultDirectSoundDevice, "Audio Input pin (rendered)"), null); checkHR(hr, "Can't connect LAV Audio Decoder and Default DirectSound Device"); }
public static string DumpFilterInfo(IBaseFilter filter) { StringBuilder sb = new StringBuilder(); int hr; sb.AppendLine(">>>>>>> BaseFilter info dump BEGIN"); { Guid guid; hr = filter.GetClassID(out guid); if (0 == hr) { sb.AppendLine("ClassID: " + guid.ToString()); } else { sb.AppendLine("ClassID: " + GetErrorText(hr)); } } { string vendorInfo = null; hr = filter.QueryVendorInfo(out vendorInfo); if (0 == hr) { sb.AppendLine(string.Format("VendorInfo: {0}", vendorInfo)); } else { sb.AppendLine("VendorInfo: " + GetErrorText(hr)); } } { FilterInfo fi; hr = filter.QueryFilterInfo(out fi); if (0 == hr) { sb.AppendLine(string.Format("FilterInfo achName: {0}", fi.achName)); } else { sb.AppendLine("FilterInfo achName: " + GetErrorText(hr)); } } IFileSourceFilter fileSourceFilter = filter as IFileSourceFilter; if (fileSourceFilter != null) { string fileName; AMMediaType mt = new AMMediaType(); fileSourceFilter.GetCurFile(out fileName, mt); DsUtils.FreeAMMediaType(mt); sb.AppendLine("IFileSourceFilter CurFile: " + fileName); } // Pins info { IEnumPins enumPins = null; IPin[] pins = new IPin[1] { null }; try { hr = filter.EnumPins(out enumPins); DsError.ThrowExceptionForHR(hr); while (enumPins.Next(1, pins, IntPtr.Zero) == 0) { sb.AppendLine(DumpPinInfo(pins[0])); Util.ReleaseComObject(ref pins[0]); } } finally { Marshal.ReleaseComObject(enumPins); } } sb.AppendLine(">>>>>>> BaseFilter info dump END"); return(sb.ToString()); }
/// <summary> /// Adds the file source filter to the graph. /// </summary> protected override void AddSourceFilter() { if (!IsLocalFilesystemResource) { throw new IllegalCallException("The BluRayPlayer can only play local file system resources"); } // Load source filter, assembly location must be determined here, otherwise LoadFilterFromDll would try to lookup the file relative to VideoPlayer! string filterPath = FilterLoader.BuildAssemblyRelativePath("BDReader.ax"); _fileSource = FilterLoader.LoadFilterFromDll(filterPath, typeof(BDReader).GUID); var baseFilter = _fileSource.GetFilter(); // Init BD Reader _bdReader = (IBDReader)baseFilter; LoadSettings(); _bdReader.SetD3DDevice(_device.NativePointer); _bdReader.SetBDReaderCallback(this); _graphBuilder.AddFilter(baseFilter, BluRayAPI.BDREADER_FILTER_NAME); // TODO: add the correct subtitle filter /* _subtitleRenderer = new SubtitleRenderer(OnTextureInvalidated); * _subtitleFilter = _subtitleRenderer.AddSubtitleFilter(_graphBuilder); * if (_subtitleFilter != null) * { * _subtitleRenderer.RenderSubtitles = true; * _subtitleRenderer.SetPlayer(this); * } */ // Prepare event handling _eventThread = new Thread(HandleBDEvent); _eventThread.Start(); // Render the file IFileSourceFilter f = (IFileSourceFilter)_fileSource; using (((ILocalFsResourceAccessor)_resourceAccessor).EnsureLocalFileSystemAccess()) { string strFile = Path.Combine(((ILocalFsResourceAccessor)_resourceAccessor).LocalFileSystemPath, @"BDMV\index.bdmv"); f.Load(strFile, null); // Init GraphRebuilder _graphRebuilder = new GraphRebuilder(_graphBuilder, baseFilter, OnAfterGraphRebuild) { PlayerName = PlayerTitle }; // Get the complete BD title information (including all streams, chapters...) _titleInfos = GetTitleInfoCollection(_bdReader); ulong duration = 0; uint maxIdx = 0; foreach (BluRayAPI.BDTitleInfo bdTitleInfo in _titleInfos) { if (bdTitleInfo.Duration > duration) { duration = bdTitleInfo.Duration; maxIdx = bdTitleInfo.Index; } } // TEST: play the longest title _forceTitle = false; if (_forceTitle) { _bdReader.ForceTitleBasedPlayback(true, maxIdx); _currentTitle = (int)maxIdx; } else { _bdReader.ForceTitleBasedPlayback(false, 0); } _bdReader.Start(); SetVideoDecoder(); } }