private void Cleanup() { Log.Info("TSReader2WMV: cleanup"); if (mediaControl != null) { mediaControl.Stop(); mediaControl = null; } mediaSeeking = null; mediaEvt = null; mediaPos = null; mediaControl = null; if (AudioCodec != null) { DirectShowUtil.ReleaseComObject(AudioCodec); } AudioCodec = null; if (VideoCodec != null) { DirectShowUtil.ReleaseComObject(VideoCodec); } VideoCodec = null; if (tsreaderSource != null) { DirectShowUtil.ReleaseComObject(tsreaderSource); } tsreaderSource = null; DirectShowUtil.RemoveFilters(graphBuilder); if (_rotEntry != null) { _rotEntry.SafeDispose(); } _rotEntry = null; if (graphBuilder != null) { DirectShowUtil.ReleaseComObject(graphBuilder); } graphBuilder = null; GC.Collect(); GC.Collect(); GC.Collect(); GC.WaitForPendingFinalizers(); }
public override void Process() { if ((DateTime.Now - lastProgressCheck).TotalMilliseconds > 100) // check progress at maximum 10 times per second { lastProgressCheck = DateTime.Now; if (percentageBuffered >= 100.0f) // already buffered 100%, simply set the Property { GUIPropertyManager.SetProperty("#TV.Record.percent3", percentageBuffered.ToString()); } else { if (graphBuilder != null && GetSourceFilterName(m_strCurrentFile) == OnlineVideos.MPUrlSourceFilter.Downloader.FilterName) // only when progress reporting is possible { IBaseFilter sourceFilter = null; try { int result = graphBuilder.FindFilterByName(OnlineVideos.MPUrlSourceFilter.Downloader.FilterName, out sourceFilter); if (result == 0) { long total = 0, current = 0; ((IAMOpenProgress)sourceFilter).QueryProgress(out total, out current); percentageBuffered = (float)current / (float)total * 100.0f; GUIPropertyManager.SetProperty("#TV.Record.percent3", percentageBuffered.ToString()); } } catch (Exception ex) { Log.Instance.Warn("Error Quering Progress: {0}", ex.Message); } finally { if (sourceFilter != null) { DirectShowUtil.ReleaseComObject(sourceFilter, 2000); } } } } AdaptRefreshRateFromVideoRenderer(); } base.Process(); }
public Frame(string name, Texture image, int duration) { _imageName = name; _image = image; _duration = duration; if (image != null) { unsafe { _image.Disposing -= new EventHandler(D3DTexture_Disposing); _image.Disposing += new EventHandler(D3DTexture_Disposing); IntPtr ptr = DirectShowUtil.GetUnmanagedTexture(_image); _textureNumber = DXNative.FontEngineAddTexture(ptr.ToInt32(), true, (void *)ptr.ToPointer()); if (logTextures) { Log.Info("Frame:ctor() fontengine: added texture:{0} {1}", _textureNumber.ToString(), _imageName); } } } }
/// <summary> /// removes the VMR7 filter from the graph and free up all unmanaged resources /// </summary> public void RemoveVMR7() { if (vmr7intialized) { int result; Log.Info("VMR7Helper:RemoveVMR7"); //if (m_mixerBitmap != null) // while ((result=DirectShowUtil.ReleaseComObject(m_mixerBitmap))>0); m_mixerBitmap = null; // if (quality != null) // while ((result=DirectShowUtil.ReleaseComObject(quality))>0); quality = null; if (VMR7Filter != null) { //while ((result=DirectShowUtil.ReleaseComObject(VMR7Filter))>0); try { result = m_graphBuilder.RemoveFilter(VMR7Filter); if (result != 0) { Log.Info("VMR7Helper:RemoveFilter():{0}", result); } } catch (Exception) {} while ((result = DirectShowUtil.ReleaseComObject(VMR7Filter)) > 0) { ; } if (result != 0) { Log.Info("VMR7Helper:ReleaseComObject():{0}", result); } m_graphBuilder = null; } vmr7intialized = false; g_vmr7 = null; } }
/// <summary> Get a moniker's human-readable name based on a moniker string. </summary> protected string getName(string monikerString) { IMoniker parser = null; IMoniker moniker = null; try { parser = getAnyMoniker(); int eaten; parser.ParseDisplayName(null, null, monikerString, out eaten, out moniker); return(getName(parser)); } finally { if (moniker != null) { DirectShowUtil.ReleaseComObject(moniker); } moniker = null; _nameResolved = true; } }
/// <summary> /// If the url to be played can be buffered before starting playback, this function /// starts building a graph by adding the preferred video and audio render to it. /// This needs to be called on the MpMain Thread. /// </summary> /// <returns>true, if the url can be buffered (a graph was started), false if it can't be and null if an error occured building the graph</returns> public bool?PrepareGraph() { //string sourceFilterName = SOURCE_FILTER_NAME; //GetSourceFilterName(m_strCurrentFile); if (!string.IsNullOrEmpty(sourceFilterName)) { graphBuilder = (IGraphBuilder) new FilterGraph(); _rotEntry = new DsROTEntry((IFilterGraph)graphBuilder); Vmr9 = new VMR9Util(); Vmr9.AddVMR9(graphBuilder); Vmr9.Enable(false); // set VMR9 back to NOT Active -> otherwise GUI is not refreshed while graph is building GUIGraphicsContext.Vmr9Active = false; // add the audio renderer using (Settings settings = new MPSettings()) { string audiorenderer = settings.GetValueAsString("movieplayer", "audiorenderer", "Default DirectSound Device"); DirectShowUtil.AddAudioRendererToGraph(graphBuilder, audiorenderer, false); } // set fields for playback mediaCtrl = (IMediaControl)graphBuilder; mediaEvt = (IMediaEventEx)graphBuilder; mediaSeek = (IMediaSeeking)graphBuilder; mediaPos = (IMediaPosition)graphBuilder; basicAudio = (IBasicAudio)graphBuilder; videoWin = (IVideoWindow)graphBuilder; // add the source filter return(tryAddSourceFilter()); } else { return(false); } }
bool?tryAddSourceFilter() { bool? result = null; IBaseFilter sourceFilter = null; try { sourceFilter = DirectShowUtil.AddFilterToGraph(graphBuilder, sourceFilterName); if (sourceFilter != null) { //openProgress = sourceFilter as IAMOpenProgress; result = true; Logger.Instance.Debug("AirPlayerVideo: Using source filter '{0}'", sourceFilterName); } } catch (Exception ex) { Logger.Instance.Warn("Error adding '{0}' filter to graph: {1}", sourceFilterName, ex.Message); } finally { if (sourceFilter != null) { DirectShowUtil.ReleaseComObject(sourceFilter); } } if (result == null && sourceFilterName != DEFAULT_SOURCE_FILTER) { Logger.Instance.Warn("Failed to add source filter '{0}', falling back to default source filter '{1}'", sourceFilterName, DEFAULT_SOURCE_FILTER); sourceFilterName = DEFAULT_SOURCE_FILTER; return(tryAddSourceFilter()); } return(result); }
/// <summary> /// Initializes the device objects of the GUIFonts. /// </summary> public static void InitializeDeviceObjects() { lock (Renderlock) { Log.Debug("GUIFontManager InitializeDeviceObjects()"); IntPtr upDevice = DirectShowUtil.GetUnmanagedDevice(GUIGraphicsContext.DX9Device); unsafe { DXNative.FontEngineSetDevice(upDevice.ToPointer()); } foreach (GUIFont font in ListFonts) { try { font.InitializeDeviceObjects(); } catch (Exception ex) { Log.Error("GUIFontManager InitializeDeviceObjects() exception {0}", ex); } } } }
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); }
private void Cleanup() { if (graphBuilder == null) { return; } int hr; Log.Info("RTSPPlayer:cleanup DShow graph"); try { if (VMR9Util.g_vmr9 != null) { VMR9Util.g_vmr9.Vmr9MediaCtrl(_mediaCtrl); VMR9Util.g_vmr9.Enable(false); } if (mediaEvt != null) { hr = mediaEvt.SetNotifyWindow(IntPtr.Zero, WM_GRAPHNOTIFY, IntPtr.Zero); } videoWin = graphBuilder as IVideoWindow; if (videoWin != null && GUIGraphicsContext.VideoRenderer != GUIGraphicsContext.VideoRendererType.madVR) { videoWin.put_Owner(IntPtr.Zero); videoWin.put_Visible(OABool.False); } _mediaCtrl = null; mediaEvt = null; _mediaSeeking = null; mediaPos = null; basicAudio = null; basicVideo = null; videoWin = null; SubEngine.GetInstance().FreeSubtitles(); if (graphBuilder != null) { DirectShowUtil.RemoveFilters(graphBuilder); if (_rotEntry != null) { _rotEntry.SafeDispose(); _rotEntry = null; } DirectShowUtil.FinalReleaseComObject(graphBuilder); graphBuilder = null; } if (VMR9Util.g_vmr9 != null) { VMR9Util.g_vmr9.SafeDispose(); VMR9Util.g_vmr9 = null; } GUIGraphicsContext.form.Invalidate(true); _state = PlayState.Init; if (_mpegDemux != null) { Log.Info("cleanup mpegdemux"); DirectShowUtil.FinalReleaseComObject(_mpegDemux); _mpegDemux = null; } if (_rtspSource != null) { Log.Info("cleanup _rtspSource"); DirectShowUtil.FinalReleaseComObject(_rtspSource); _rtspSource = null; } if (_subtitleFilter != null) { DirectShowUtil.FinalReleaseComObject(_subtitleFilter); _subtitleFilter = null; if (this.dvbSubRenderer != null) { this.dvbSubRenderer.SetPlayer(null); } this.dvbSubRenderer = null; } if (vobSub != null) { Log.Info("cleanup vobSub"); DirectShowUtil.FinalReleaseComObject(vobSub); vobSub = null; } } catch (Exception ex) { if (VMR9Util.g_vmr9 != null) { VMR9Util.g_vmr9.RestoreGuiForMadVr(); VMR9Util.g_vmr9.SafeDispose(); } Log.Error("RTSPPlayer: Exception while cleanuping DShow graph - {0} {1}", ex.Message, ex.StackTrace); } //switch back to directx windowed mode Log.Info("RTSPPlayer: Disabling DX9 exclusive mode"); GUIMessage msg = new GUIMessage(GUIMessage.MessageType.GUI_MSG_SWITCH_FULL_WINDOWED, 0, 0, 0, 0, 0, null); GUIWindowManager.SendMessage(msg); }
public bool LoadSubtitles(IGraphBuilder graphBuilder, string filename) { LoadSettings(); //remove DirectVobSub DirectVobSubUtil.RemoveFromGraph(graphBuilder); { //remove InternalScriptRenderer as it takes subtitle pin IBaseFilter isr = null; DirectShowUtil.FindFilterByClassID(graphBuilder, ClassId.InternalScriptRenderer, out isr); if (isr != null) { graphBuilder.RemoveFilter(isr); DirectShowUtil.ReleaseComObject(isr); } } // Window size //Size size = new Size(GUIGraphicsContext.Width, GUIGraphicsContext.Height); /*List<FFDShowAPI.FFDShowInstance> ffdshowInstance = FFDShowAPI.getFFDShowInstances(); * FFDShowAPI.FFDShowAPI api = new FFDShowAPI();*/ IBaseFilter baseFilter = null; DirectShowUtil.FindFilterByClassID(graphBuilder, FFDShowAPI.FFDShowVideoGuid, out baseFilter); if (baseFilter == null) { DirectShowUtil.FindFilterByClassID(graphBuilder, FFDShowAPI.FFDShowVideoDXVAGuid, out baseFilter); } if (baseFilter == null) { DirectShowUtil.FindFilterByClassID(graphBuilder, FFDShowAPI.FFDShowVideoRawGuid, out baseFilter); } if (baseFilter == null) { return(false); } ffdshowAPI = new FFDShowAPI((object)baseFilter); IffdshowDec ffdshowDec = baseFilter as IffdshowDec; if (ffdshowDec == null) { Log.Error("FFdshow interfaces not found. Try to update FFDShow"); } else { Log.Info("FFdshow interfaces found"); } if (selectionOff) { Enable = false; } else { Enable = autoShow; } return(true); }
private void Cleanup() { if (_graphBuilder == null) { return; } int hr; using (Settings xmlreader = new MPSettings()) { int codecValue = 0; string codecType = ""; codecType = xmlreader.GetValueAsString("dvdplayer", "videocodec", ""); if (codecType == "InterVideo Video Decoder") { codecValue = xmlreader.GetValueAsInt("videocodec", "intervideo", 1); Log.Info("DVDPlayer9:Resetting InterVideo DXVA to {0}", codecValue); using ( RegistryKey subkey = Registry.CurrentUser.CreateSubKey(@"Software\InterVideo\Common\VideoDec\MediaPortal")) { subkey.SetValue("DXVA", codecValue); } } if (codecType.StartsWith("CyberLink Video/SP Decoder")) { codecValue = xmlreader.GetValueAsInt("videocodec", "cyberlink", 1); Log.Info("DVDPlayer9:Resetting CyberLink DXVA to {0}", codecValue); using (RegistryKey subkey = Registry.CurrentUser.CreateSubKey(@"Software\Cyberlink\Common\CLVSD\MediaPortal")) { subkey.SetValue("UIUseHVA", codecValue); } } if (codecType == "NVIDIA Video Decoder") { codecValue = xmlreader.GetValueAsInt("videocodec", "nvidia", 1); Log.Info("DVDPlayer9:Resetting NVIDIA DXVA to {0}", codecValue); using (RegistryKey subkey = Registry.LocalMachine.CreateSubKey(@"Software\NVIDIA Corporation\Filters\Video")) { subkey.SetValue("EnableDXVA", codecValue); } } } try { Log.Info("DVDPlayer9: cleanup DShow graph"); if (_mediaCtrl != null) { int counter = 0; FilterState state; hr = _mediaCtrl.Stop(); hr = _mediaCtrl.GetState(10, out state); while (state != FilterState.Stopped || GUIGraphicsContext.InVmr9Render) { System.Threading.Thread.Sleep(100); hr = _mediaCtrl.GetState(10, out state); counter++; if (counter >= 30) { if (state != FilterState.Stopped) { Log.Debug("DVDPlayer9: graph still running"); } if (GUIGraphicsContext.InVmr9Render) { Log.Debug("DVDPlayer9: in renderer"); } break; } } _mediaCtrl = null; } _state = PlayState.Stopped; VMR9Util.g_vmr9.EVRSetDVDMenuState(false); _visible = false; _mediaEvt = null; _dvdCtrl = null; _dvdInfo = null; _basicVideo = null; _basicAudio = null; _mediaPos = null; _videoWin = null; _pendingCmd = false; if (_cmdOption != null) { DirectShowUtil.ReleaseComObject(_cmdOption); _cmdOption = null; } if (_dvdbasefilter != null) { while ((hr = DirectShowUtil.ReleaseComObject(_dvdbasefilter)) > 0) { ; } _dvdbasefilter = null; } if (_dvdGraph != null) { while ((hr = DirectShowUtil.ReleaseComObject(_dvdGraph)) > 0) { ; } _dvdGraph = null; } if (_line21Decoder != null) { while ((hr = DirectShowUtil.ReleaseComObject(_line21Decoder)) > 0) { ; } _line21Decoder = null; } PostProcessingEngine.GetInstance().FreePostProcess(); if (_vmr9 != null) { _vmr9.Enable(false); _vmr9.SafeDispose(); _vmr9 = null; } if (_graphBuilder != null) { DirectShowUtil.RemoveFilters(_graphBuilder); // _rotEntry has a reference to _graphBuilder (see _rotEntry ctor) // so, release of _rotEntry must be before _graphBuilder is released if (_rotEntry != null) { _rotEntry.SafeDispose(); _rotEntry = null; } while ((hr = DirectShowUtil.ReleaseComObject(_graphBuilder)) > 0) { ; } _graphBuilder = null; } _state = PlayState.Init; GUIGraphicsContext.form.Invalidate(true); //GUIGraphicsContext.form.Activate(); } catch (Exception ex) { Log.Error("DVDPlayer9: Exception while cleanuping DShow graph - {0} {1}", ex.Message, ex.StackTrace); } Log.Info("DVDPlayer9: Disabling DX9 exclusive mode"); GUIMessage msg = new GUIMessage(GUIMessage.MessageType.GUI_MSG_SWITCH_FULL_WINDOWED, 0, 0, 0, 0, 0, null); GUIWindowManager.SendMessage(msg); }
/// <summary> Populate the InnerList with a list of filters from a particular category </summary> protected void getFilters(Guid category) { int hr; object comObj = null; ICreateDevEnum enumDev = null; IEnumMoniker enumMon = null; IMoniker[] mon = new IMoniker[1]; try { // Get the system device enumerator Type srvType = Type.GetTypeFromCLSID(ClassId.SystemDeviceEnum); if (srvType == null) { throw new NotImplementedException("System Device Enumerator"); } comObj = Activator.CreateInstance(srvType); enumDev = (ICreateDevEnum)comObj; // Create an enumerator to find filters in category hr = enumDev.CreateClassEnumerator(category, out enumMon, 0); if (hr != 0) { return; //throw new NotSupportedException( "No devices of the category" ); } // Loop through the enumerator IntPtr f = IntPtr.Zero; do { // Next filter hr = enumMon.Next(1, mon, f); if ((hr != 0) || (mon[0] == null)) { break; } // Add the filter Filter filter = new Filter(mon[0]); InnerList.Add(filter); // Release resources DirectShowUtil.ReleaseComObject(mon[0]); mon[0] = null; } while (true); // Sort //InnerList.Sort(); } finally { enumDev = null; if (mon[0] != null) { DirectShowUtil.ReleaseComObject(mon[0]); } mon[0] = null; if (enumMon != null) { DirectShowUtil.ReleaseComObject(enumMon); } enumMon = null; if (comObj != null) { DirectShowUtil.ReleaseComObject(comObj); } comObj = null; } }
public void SetDeinterlaceMode() { if (!GUIGraphicsContext.IsEvr) { if (!_isVmr9Initialized) { return; } Log.Debug("VMR9: SetDeinterlaceMode()"); IVMRDeinterlaceControl9 deinterlace = (IVMRDeinterlaceControl9)_vmr9Filter; IPin InPin = null; int hr = _vmr9Filter.FindPin("VMR Input0", out InPin); if (hr != 0) { Log.Error("VMR9: failed finding InPin {0:X}", hr); } AMMediaType mediatype = new AMMediaType(); InPin.ConnectionMediaType(mediatype); //Start by getting the media type of the video stream. //Only VideoInfoHeader2 formats can be interlaced. if (mediatype.formatType == FormatType.VideoInfo2) { Log.Debug("VMR9: SetDeinterlaceMode - FormatType = VideoInfo2"); int numModes = 0; VideoInfoHeader2 VideoHeader2 = new VideoInfoHeader2(); Marshal.PtrToStructure(mediatype.formatPtr, VideoHeader2); VMR9VideoDesc VideoDesc = new VMR9VideoDesc(); // If the FormatType is VideoInfo2, check the dwInterlaceFlags field for the AMInterlace.IsInterlaced flag. //The presence of this flag indicates the video is interlaced. if ((VideoHeader2.InterlaceFlags & AMInterlace.IsInterlaced) != 0) { Log.Debug("VMR9: SetDeinterlaceMode - Interlaced frame detected"); //Fill in the VMR9VideoDesc structure with a description of the video stream. VideoDesc.dwSize = Marshal.SizeOf(VideoDesc); // dwSize: Set this field to sizeof(VMR9VideoDesc). VideoDesc.dwSampleWidth = VideoHeader2.BmiHeader.Width; // dwSampleWidth: Set this field to pBMI->biWidth. VideoDesc.dwSampleHeight = VideoHeader2.BmiHeader.Height; // dwSampleHeight: Set this field to abs(pBMI->biHeight). //SampleFormat: This field describes the interlace characteristics of the media type. //Check the dwInterlaceFlags field in the VIDEOINFOHEADER2 structure, and set SampleFormat equal to the equivalent VMR9_SampleFormat flag. if ((VideoHeader2.InterlaceFlags & AMInterlace.IsInterlaced) != 0) { if ((VideoHeader2.InterlaceFlags & AMInterlace.DisplayModeBobOnly) == 0) { VideoDesc.SampleFormat = VMR9SampleFormat.ProgressiveFrame; } if ((VideoHeader2.InterlaceFlags & AMInterlace.OneFieldPerSample) != 0) { if ((VideoHeader2.InterlaceFlags & AMInterlace.Field1First) != 0) { VideoDesc.SampleFormat = VMR9SampleFormat.FieldSingleEven; } else { VideoDesc.SampleFormat = VMR9SampleFormat.FieldSingleOdd; } } if ((VideoHeader2.InterlaceFlags & AMInterlace.Field1First) != 0) { VideoDesc.SampleFormat = VMR9SampleFormat.FieldInterleavedEvenFirst; } else { VideoDesc.SampleFormat = VMR9SampleFormat.FieldInterleavedOddFirst; } } //InputSampleFreq: This field gives the input frequency, which can be calculated from the AvgTimePerFrame field in the VIDEOINFOHEADER2 structure. //In the general case, set dwNumerator to 10000000, and set dwDenominator to AvgTimePerFrame. VideoDesc.InputSampleFreq.dwDenominator = 10000000; VideoDesc.InputSampleFreq.dwNumerator = (int)VideoHeader2.AvgTimePerFrame; //OutputFrameFreq: This field gives the output frequency, which can be calculated from the InputSampleFreq value and the interleaving characteristics of the input stream: //Set OutputFrameFreq.dwDenominator equal to InputSampleFreq.dwDenominator. //If the input video is interleaved, set OutputFrameFreq.dwNumerator to 2 x InputSampleFreq.dwNumerator. (After deinterlacing, the frame rate is doubled.) //Otherwise, set the value to InputSampleFreq.dwNumerator. VideoDesc.OutputFrameFreq.dwDenominator = 10000000; VideoDesc.OutputFrameFreq.dwNumerator = (int)VideoHeader2.AvgTimePerFrame * 2; VideoDesc.dwFourCC = VideoHeader2.BmiHeader.Compression; //dwFourCC: Set this field to pBMI->biCompression. //Pass the structure to the IVMRDeinterlaceControl9::GetNumberOfDeinterlaceModes method. //Call the method twice. The first call returns the number of deinterlace modes the hardware supports for the specified format. hr = deinterlace.GetNumberOfDeinterlaceModes(ref VideoDesc, ref numModes, null); if (hr == 0 && numModes != 0) { Guid[] modes = new Guid[numModes]; { //Allocate an array of GUIDs of this size, and call the method again, passing in the address of the array. //The second call fills the array with GUIDs. Each GUID identifies one deinterlacing mode. hr = deinterlace.GetNumberOfDeinterlaceModes(ref VideoDesc, ref numModes, modes); for (int i = 0; i < numModes; i++) { //To get the capabiltiies of a particular mode, call the IVMRDeinterlaceControl9::GetDeinterlaceModeCaps method. //Pass in the same VMR9VideoDesc structure, along with one of the GUIDs from the array. //The method fills a VMR9DeinterlaceCaps structure with the mode capabilities. VMR9DeinterlaceCaps caps = new VMR9DeinterlaceCaps(); caps.dwSize = Marshal.SizeOf(typeof(VMR9DeinterlaceCaps)); hr = deinterlace.GetDeinterlaceModeCaps(modes[i], ref VideoDesc, ref caps); if (hr == 0) { Log.Debug("VMR9: AvailableDeinterlaceMode - {0}: {1}", i, modes[i]); switch (caps.DeinterlaceTechnology) { //The algorithm is unknown or proprietary case VMR9DeinterlaceTech.Unknown: { Log.Info("VMR9: Unknown H/W de-interlace mode"); break; } //The algorithm creates each missing line by repeating the line above it or below it. //This method creates jagged artifacts and is not recommended. case VMR9DeinterlaceTech.BOBLineReplicate: { Log.Info("VMR9: BOB Line Replicate capable"); break; } //The algorithm creates the missing lines by vertically stretching each video field by a factor of two. //For example, it might average two lines or use a (-1, 9, 9, -1)/16 filter across four lines. //Slight vertical adjustments are made to ensure that the resulting image does not "bob" up and down case VMR9DeinterlaceTech.BOBVerticalStretch: { Log.Info("VMR9: BOB Vertical Stretch capable"); verticalStretch = modes[i].ToString(); break; } //The algorithm uses median filtering to recreate the pixels in the missing lines. case VMR9DeinterlaceTech.MedianFiltering: { Log.Info("VMR9: Median Filtering capable"); medianFiltering = modes[i].ToString(); break; } //The algorithm uses an edge filter to create the missing lines. //In this process, spatial directional filters are applied to determine the orientation of edges in the picture content. //Missing pixels are created by filtering along (rather than across) the detected edges. case VMR9DeinterlaceTech.EdgeFiltering: { Log.Info("VMR9: Edge Filtering capable"); break; } //The algorithm uses spatial or temporal interpolation, switching between the two on a field-by-field basis, depending on the amount of motion. case VMR9DeinterlaceTech.FieldAdaptive: { Log.Info("VMR9: Field Adaptive capable"); break; } //The algorithm uses spatial or temporal interpolation, switching between the two on a pixel-by-pixel basis, depending on the amount of motion. case VMR9DeinterlaceTech.PixelAdaptive: { Log.Info("VMR9: Pixel Adaptive capable"); pixelAdaptive = modes[i].ToString(); break; } //The algorithm identifies objects within a sequence of video fields. //Before it recreates the missing pixels, it aligns the movement axes of the individual objects in the scene to make them parallel with the time axis. case VMR9DeinterlaceTech.MotionVectorSteered: { Log.Info("VMR9: Motion Vector Steered capable"); break; } } } } } //Set the MP preferred h/w de-interlace modes in order of quality //pixel adaptive, then median filtering & finally vertical stretch if (pixelAdaptive != "") { Guid DeinterlaceMode = new Guid(pixelAdaptive); Log.Debug("VMR9: trying pixel adaptive"); hr = deinterlace.SetDeinterlaceMode(0, DeinterlaceMode); if (hr != 0) { Log.Error("VMR9: pixel adaptive failed!"); } else { Log.Info("VMR9: setting pixel adaptive succeeded"); medianFiltering = ""; verticalStretch = ""; } } if (medianFiltering != "") { Guid DeinterlaceMode = new Guid(medianFiltering); Log.Debug("VMR9: trying median filtering"); hr = deinterlace.SetDeinterlaceMode(0, DeinterlaceMode); if (hr != 0) { Log.Error("VMR9: median filtering failed!"); } else { Log.Info("VMR9: setting median filtering succeeded"); verticalStretch = ""; } } if (verticalStretch != "") { Guid DeinterlaceMode = new Guid(verticalStretch); Log.Debug("VMR9: trying vertical stretch"); hr = deinterlace.SetDeinterlaceMode(0, DeinterlaceMode); if (hr != 0) { Log.Error("VMR9: Cannot set H/W de-interlace mode - using VMR9 fallback"); } Log.Info("VMR9: setting vertical stretch succeeded"); } } else { Log.Info("VMR9: No H/W de-interlaced modes supported, using fallback preference"); } } else { Log.Info("VMR9: progressive mode detected - no need to de-interlace"); } } //If the format type is VideoInfo, it must be a progressive frame. else { Log.Info("VMR9: no need to de-interlace this video source"); } DsUtils.FreeAMMediaType(mediatype); //release the VMR9 pin hr = DirectShowUtil.ReleaseComObject(InPin); InPin = null; mediatype = null; } }
//public bool IsVMR9Connected #endregion #region public members /// <summary> /// Add VMR9 filter to graph and configure it /// </summary> /// <param name="graphBuilder"></param> public bool AddVMR9(IGraphBuilder graphBuilder) { if (!_useVmr9) { Log.Debug("VMR9: addvmr9 - vmr9 is deactivated"); return(false); } if (_isVmr9Initialized) { Log.Debug("VMR9: addvmr9: vmr9 has already been initialized"); return(false); } bool _useEvr = GUIGraphicsContext.IsEvr; if (_instanceCounter != 0) { Log.Error("VMR9: Multiple instances of VMR9 running!!!"); throw new Exception("VMR9Helper: Multiple instances of VMR9 running!!!"); } HResult hr; IntPtr hMonitor = Manager.GetAdapterMonitor(GUIGraphicsContext.DX9Device.DeviceCaps.AdapterOrdinal); IntPtr upDevice = DirectShowUtil.GetUnmanagedDevice(GUIGraphicsContext.DX9Device); _scene = new PlaneScene(this); _scene.Init(); if (_useEvr) { EvrInit(_scene, (uint)upDevice.ToInt32(), ref _vmr9Filter, (uint)hMonitor.ToInt32()); hr = new HResult(graphBuilder.AddFilter(_vmr9Filter, "Enhanced Video Renderer")); Log.Info("VMR9: added EVR Renderer to graph"); } else { _vmr9Filter = (IBaseFilter) new VideoMixingRenderer9(); Log.Info("VMR9: added Video Mixing Renderer 9 to graph"); Vmr9Init(_scene, (uint)upDevice.ToInt32(), _vmr9Filter, (uint)hMonitor.ToInt32()); hr = new HResult(graphBuilder.AddFilter(_vmr9Filter, "Video Mixing Renderer 9")); } if (_vmr9Filter == null) { Error.SetError("Unable to play movie", "Renderer could not be added"); Log.Error("VMR9: Renderer not installed / cannot be used!"); return(false); } if (hr != 0) { if (_useEvr) { EvrDeinit(); } else { Vmr9Deinit(); } _scene.Stop(); _scene.Deinit(); _scene = null; DirectShowUtil.ReleaseComObject(_vmr9Filter); _vmr9Filter = null; Error.SetError("Unable to play movie", "Unable to initialize Renderer"); Log.Error("VMR9: Failed to add Renderer to filter graph"); return(false); } _qualityInterface = _vmr9Filter as IQualProp; _vmr9MixerBitmapInterface = _vmr9Filter as IVMRMixerBitmap9; _graphBuilderInterface = graphBuilder; _instanceCounter++; _isVmr9Initialized = true; if (!_useEvr) { SetDeinterlacePrefs(); IVMRMixerControl9 mixer = _vmr9Filter as IVMRMixerControl9; if (mixer != null) { VMR9MixerPrefs dwPrefs; mixer.GetMixingPrefs(out dwPrefs); dwPrefs &= ~VMR9MixerPrefs.RenderTargetMask; dwPrefs |= VMR9MixerPrefs.RenderTargetYUV; // YUV saves graphics bandwith http://msdn2.microsoft.com/en-us/library/ms788177(VS.85).aspx hr.Set(mixer.SetMixingPrefs(dwPrefs)); Log.Debug("VMR9: Enabled YUV mixing - " + hr.ToDXString()); using (Settings xmlreader = new MPSettings()) { //Enable nonsquaremixing if (xmlreader.GetValueAsBool("general", "nonsquare", true)) { mixer.GetMixingPrefs(out dwPrefs); dwPrefs |= VMR9MixerPrefs.NonSquareMixing; hr.Set(mixer.SetMixingPrefs(dwPrefs)); Log.Debug("VRM9: Turning on nonsquare mixing - " + hr.ToDXString()); hr.Set(mixer.SetMixingPrefs(dwPrefs)); } // Enable DecimateMask - this will effectively use only half of the input width & length if (xmlreader.GetValueAsBool("general", "dx9decimatemask", false)) { mixer.GetMixingPrefs(out dwPrefs); dwPrefs &= ~VMR9MixerPrefs.DecimateMask; dwPrefs |= VMR9MixerPrefs.DecimateOutput; hr.Set(mixer.SetMixingPrefs(dwPrefs)); Log.Debug("VRM9: Enable decimatemask - " + hr.ToDXString()); hr.Set(mixer.SetMixingPrefs(dwPrefs)); } // see D3DTEXTUREFILTERTYPE Enumerated Type documents for further information // MixerPref9_PointFiltering // MixerPref9_BiLinearFiltering // MixerPref9_AnisotropicFiltering // MixerPref9_PyramidalQuadFiltering // MixerPref9_GaussianQuadFiltering mixer.SetMixingPrefs(dwPrefs); mixer.GetMixingPrefs(out dwPrefs); dwPrefs &= ~VMR9MixerPrefs.FilteringMask; string filtermode9 = xmlreader.GetValueAsString("general", "dx9filteringmode", "Gaussian Quad Filtering"); if (filtermode9 == "Point Filtering") { dwPrefs |= VMR9MixerPrefs.PointFiltering; } else if (filtermode9 == "Bilinear Filtering") { dwPrefs |= VMR9MixerPrefs.BiLinearFiltering; } else if (filtermode9 == "Anisotropic Filtering") { dwPrefs |= VMR9MixerPrefs.AnisotropicFiltering; } else if (filtermode9 == "Pyrimidal Quad Filtering") { dwPrefs |= VMR9MixerPrefs.PyramidalQuadFiltering; } else { dwPrefs |= VMR9MixerPrefs.GaussianQuadFiltering; } hr.Set(mixer.SetMixingPrefs(dwPrefs)); Log.Debug("VRM9: Set filter mode - " + filtermode9 + " " + hr.ToDXString()); } } } _threadId = Thread.CurrentThread.ManagedThreadId; GUIGraphicsContext.Vmr9Active = true; g_vmr9 = this; Log.Debug("VMR9: Renderer successfully added"); return(true); }
public bool LoadSubtitles(IGraphBuilder graphBuilder, string filename) { FreeSubtitles(); LoadSettings(); { //remove InternalScriptRenderer as it takes subtitle pin IBaseFilter isr = null; DirectShowUtil.FindFilterByClassID(graphBuilder, ClassId.InternalScriptRenderer, out isr); if (isr != null) { graphBuilder.RemoveFilter(isr); DirectShowUtil.ReleaseComObject(isr); } } vobSub = (IDirectVobSub)DirectVobSubUtil.AddToGraph(graphBuilder); if (vobSub == null) { return(false); } { //set style Log.Debug("VideoPlayerVMR9: Setting DirectVobsub parameters"); LOGFONT logFont = new LOGFONT(); int txtcolor; bool fShadow, fOutLine, fAdvancedRenderer = false; int size = Marshal.SizeOf(typeof(LOGFONT)); vobSub.get_TextSettings(logFont, size, out txtcolor, out fShadow, out fOutLine, out fAdvancedRenderer); FontStyle fontStyle = defStyle.fontIsBold ? FontStyle.Regular : FontStyle.Bold; Font Subfont = new Font(defStyle.fontName, defStyle.fontSize, fontStyle, GraphicsUnit.Point, (byte)defStyle.fontCharset); Subfont.ToLogFont(logFont); fShadow = defStyle.shadow > 0; fOutLine = defStyle.isBorderOutline; vobSub.put_TextSettings(logFont, size, defStyle.fontColor, fShadow, fOutLine, fAdvancedRenderer); vobSub.put_FileName(filename); bool fBuffer, fOnlyForced, fPolygonize; vobSub.get_VobSubSettings(out fBuffer, out fOnlyForced, out fPolygonize); if (selectionOff) { vobSub.put_VobSubSettings(fBuffer, false, fPolygonize); } else { vobSub.put_VobSubSettings(fBuffer, !this.autoShow, fPolygonize); } } { //load sub streams IBaseFilter hms = null; DirectShowUtil.FindFilterByClassID(graphBuilder, ClassId.HaaliGuid, out hms); if (hms == null) { DirectShowUtil.FindFilterByClassID(graphBuilder, ClassId.LAVFilterSource, out hms); } if (hms == null) { DirectShowUtil.FindFilterByClassID(graphBuilder, ClassId.LAVFilter, out hms); } embeddedSelector = hms as IAMStreamSelect; if (embeddedSelector != null) { AddStreams(embeddedSelector); } vobSub.get_LanguageCount(out extCount); if (intSubs.Count > 0) { //if there are embedded subtitles, //last stream of directvobsub is currently selected embedded subtitle extCount--; } } FFDShowEngine.DisableFFDShowSubtitles(graphBuilder); Current = 0; if (selectionOff) { Enable = false; } return(true); }
public static void RemoveFromGraph(IGraphBuilder graphBuilder) { IBaseFilter vob = null; using (Settings xmlreader = new MPSettings()) { string engineType = xmlreader.GetValueAsString("subtitles", "engine", "DirectVobSub"); XySubFilter = engineType.Equals("XySubFilter"); } if (!XySubFilter) { DirectShowUtil.FindFilterByClassID(graphBuilder, ClassId.DirectVobSubAutoload, out vob); if (vob == null) { //Try the "normal" filter then. DirectShowUtil.FindFilterByClassID(graphBuilder, ClassId.DirectVobSubNormal, out vob); } } if (vob == null) { DirectShowUtil.FindFilterByClassID(graphBuilder, ClassId.XySubFilterAutoload, out vob); if (vob != null) { //remove the XySubFilter filter from the graph graphBuilder.RemoveFilter(vob); DirectShowUtil.ReleaseComObject(vob); vob = null; return; } //Try the XySubFilter "normal" filter then. DirectShowUtil.FindFilterByClassID(graphBuilder, ClassId.XySubFilterNormal, out vob); if (vob != null) { //remove the XySubFilter filter from the graph graphBuilder.RemoveFilter(vob); DirectShowUtil.ReleaseComObject(vob); vob = null; } return; } Log.Info("VideoPlayerVMR9: DirectVobSub in graph, removing..."); // Check where video inputs are connected IPin pinVideoIn = DsFindPin.ByDirection(vob, PinDirection.Input, 0); IPin pinVideoOut = DsFindPin.ByDirection(vob, PinDirection.Output, 0); //find directvobsub's video output pin source input pin IPin pinVideoTo = null; if (pinVideoOut != null) { pinVideoOut.ConnectedTo(out pinVideoTo); } //find directvobsub's video input pin source output pin IPin pinVideoFrom = null; if (pinVideoIn != null) { pinVideoIn.ConnectedTo(out pinVideoFrom); } int hr = 0; if (pinVideoFrom != null) { hr = pinVideoFrom.Disconnect(); if (hr != 0) { Log.Error("VideoPlayerVMR9: DirectVobSub failed disconnecting source pin"); } } if (pinVideoTo != null) { hr = pinVideoTo.Disconnect(); if (hr != 0) { Log.Error("VideoPlayerVMR9: DirectVobSub failed disconnecting destination pin"); } } //remove the DirectVobSub filter from the graph graphBuilder.RemoveFilter(vob); DirectShowUtil.ReleaseComObject(vob); vob = null; //reconnect the source output pin to the vmr9/evr filter if (pinVideoFrom != null) { if (pinVideoTo != null) { hr = graphBuilder.Connect(pinVideoFrom, pinVideoTo); } //hr = graphBuilder.Render(pinVideoFrom); DirectShowUtil.ReleaseComObject(pinVideoFrom); pinVideoFrom = null; } if (pinVideoTo != null) { DirectShowUtil.ReleaseComObject(pinVideoTo); pinVideoTo = null; } if (pinVideoOut != null) { DirectShowUtil.ReleaseComObject(pinVideoOut); pinVideoOut = null; } if (pinVideoIn != null) { DirectShowUtil.ReleaseComObject(pinVideoIn); pinVideoIn = null; } if (hr != 0) { Log.Error("VideoPlayerVMR9: Could not connect video out to video renderer: {0}", hr); } else { Log.Debug("VideoPlayerVMR9: DirectVobSub graph rebuild finished"); } }
protected override bool GetInterfaces() { GetInterface = true; try { graphBuilder = (IGraphBuilder) new FilterGraph(); _rotEntry = new DsROTEntry((IFilterGraph)graphBuilder); int hr; filterConfig = GetFilterConfiguration(); filterCodec = GetFilterCodec(); if (filterConfig.bAutoDecoderSettings) { AutoRenderingCheck = true; return(base.GetInterfaces()); } string extension = Path.GetExtension(m_strCurrentFile).ToLowerInvariant(); GUIMessage msg; if (extension == ".mpls" || extension == ".bdmv") { filterConfig.bForceSourceSplitter = false; filterConfig = GetFilterConfigurationBD(); } //Manually add codecs based on file extension if not in auto-settings // switch back to directx fullscreen mode Log.Info("MyAnime3Player: Enabling DX9 exclusive mode"); msg = new GUIMessage(GUIMessage.MessageType.GUI_MSG_SWITCH_FULL_WINDOWED, 0, 0, 0, 1, 0, null); GUIWindowManager.SendMessage(msg); // add the VMR9 in the graph // after enabeling exclusive mode, if done first it causes MediPortal to minimize if for example the "Windows key" is pressed while playing a video if (extension != ".dts" && extension != ".mp3" && extension != ".mka" && extension != ".ac3") { if (g_Player.MediaInfo != null && !g_Player.MediaInfo.MediaInfoNotloaded && !g_Player._mediaInfo.HasVideo) { AudioOnly = true; } else { Vmr9 = new VMR9Util(); Vmr9.AddVMR9(graphBuilder); Vmr9.Enable(false); } } else { AudioOnly = true; } if (filterConfig.strsplitterfilter == LAV_SPLITTER_FILTER_SOURCE && filterConfig.bForceSourceSplitter) { LoadLAVSplitter(LAV_SPLITTER_FILTER_SOURCE); hr = graphBuilder.AddFilter(_interfaceSourceFilter, LAV_SPLITTER_FILTER_SOURCE); DsError.ThrowExceptionForHR(hr); Log.Debug("MyAnime3Player: Add LAVSplitter Source to graph"); IFileSourceFilter interfaceFile = (IFileSourceFilter)_interfaceSourceFilter; hr = interfaceFile.Load(m_strCurrentFile, null); if (hr != 0) { Error.SetError("Unable to play movie", "Unable build graph for VMR9"); Cleanup(); return(false); } } else { _interfaceSourceFilter = filterConfig.bForceSourceSplitter ? DirectShowUtil.AddFilterToGraph(graphBuilder, filterConfig.strsplitterfilter) : null; if (_interfaceSourceFilter == null && !filterConfig.bForceSourceSplitter) { graphBuilder.AddSourceFilter(m_strCurrentFile, null, out _interfaceSourceFilter); } else { try { int result = ((IFileSourceFilter)_interfaceSourceFilter).Load(m_strCurrentFile, null); if (result != 0) { graphBuilder.RemoveFilter(_interfaceSourceFilter); DirectShowUtil.ReleaseComObject(_interfaceSourceFilter); _interfaceSourceFilter = null; graphBuilder.AddSourceFilter(m_strCurrentFile, null, out _interfaceSourceFilter); } } catch (Exception ex) { Log.Error( "MyAnime3Player: Exception loading Source Filter setup in setting in DShow graph , try to load by merit", ex); graphBuilder.RemoveFilter(_interfaceSourceFilter); DirectShowUtil.ReleaseComObject(_interfaceSourceFilter); _interfaceSourceFilter = null; graphBuilder.AddSourceFilter(m_strCurrentFile, null, out _interfaceSourceFilter); } } //Detection of File Source (Async.) as source filter, return true if found IBaseFilter fileSyncbaseFilter = null; DirectShowUtil.FindFilterByClassID(graphBuilder, ClassId.FilesyncSource, out fileSyncbaseFilter); if (fileSyncbaseFilter == null) { graphBuilder.FindFilterByName("File Source (Async.)", out fileSyncbaseFilter); } if (fileSyncbaseFilter != null && filterConfig.bForceSourceSplitter) { FileSync = true; DirectShowUtil.ReleaseComObject(fileSyncbaseFilter); fileSyncbaseFilter = null; if (filterConfig.strsplitterfilefilter == LAV_SPLITTER_FILTER) { LoadLAVSplitter(LAV_SPLITTER_FILTER); hr = graphBuilder.AddFilter(Splitter, LAV_SPLITTER_FILTER); DsError.ThrowExceptionForHR(hr); Log.Debug("MyAnime3Player: Add LAVSplitter to graph"); if (hr != 0) { Error.SetError("Unable to play movie", "Unable build graph for VMR9"); Cleanup(); return(false); } } else { Splitter = DirectShowUtil.AddFilterToGraph(graphBuilder, filterConfig.strsplitterfilefilter); } } } // Add preferred video filters UpdateFilters("Video"); //Add Audio Renderer if (filterConfig.AudioRenderer.Length > 0 && filterCodec._audioRendererFilter == null) { filterCodec._audioRendererFilter = DirectShowUtil.AddAudioRendererToGraph(graphBuilder, filterConfig.AudioRenderer, false); } // Add preferred audio filters UpdateFilters("Audio"); #region Set High Audio //Set High Resolution Output > 2 channels IBaseFilter baseFilter = null; bool FFDShowLoaded = false; graphBuilder.FindFilterByName("WMAudio Decoder DMO", out baseFilter); if (baseFilter != null && filterConfig.wmvAudio != false) //Also check configuration option enabled { //Set the filter setting to enable more than 2 audio channels const string g_wszWMACHiResOutput = "_HIRESOUTPUT"; object val = true; IPropertyBag propBag = (IPropertyBag)baseFilter; hr = propBag.Write(g_wszWMACHiResOutput, ref val); if (hr != 0) { Log.Info("VideoPlayer9: Unable to turn WMAudio multichannel on. Reason: {0}", hr); } else { Log.Info("VideoPlayer9: WMAudio Decoder now set for > 2 audio channels"); } if (!FFDShowLoaded) { IBaseFilter FFDShowAudio = DirectShowUtil.GetFilterByName(graphBuilder, FFDSHOW_AUDIO_DECODER_FILTER); if (FFDShowAudio != null) { DirectShowUtil.ReleaseComObject(FFDShowAudio); FFDShowAudio = null; } else { _FFDShowAudio = DirectShowUtil.AddFilterToGraph(graphBuilder, FFDSHOW_AUDIO_DECODER_FILTER); } FFDShowLoaded = true; } DirectShowUtil.ReleaseComObject(baseFilter); baseFilter = null; } #endregion if (_interfaceSourceFilter != null) { DirectShowUtil.RenderGraphBuilderOutputPins(graphBuilder, _interfaceSourceFilter); } //Test and remove orphelin Audio Renderer //RemoveAudioR(); //remove InternalScriptRenderer as it takes subtitle pin disableISR(); //disable Closed Captions! disableCC(); DirectShowUtil.RemoveUnusedFiltersFromGraph(graphBuilder); //remove orphelin audio renderer RemoveAudioR(); //EnableClock(); if ((Vmr9 == null || !Vmr9.IsVMR9Connected) && !AudioOnly) { Log.Error("MyAnime3Player: Failed to render file -> vmr9"); mediaCtrl = null; Cleanup(); return(false); } mediaCtrl = (IMediaControl)graphBuilder; mediaEvt = (IMediaEventEx)graphBuilder; mediaSeek = (IMediaSeeking)graphBuilder; mediaPos = (IMediaPosition)graphBuilder; basicAudio = (IBasicAudio)graphBuilder; videoWin = (IVideoWindow)graphBuilder; if (Vmr9 != null) { m_iVideoWidth = Vmr9.VideoWidth; m_iVideoHeight = Vmr9.VideoHeight; Vmr9.SetDeinterlaceMode(); } return(true); } catch (Exception ex) { Error.SetError("Unable to play movie", "Unable build graph for VMR9"); Log.Error("MyAnime3Player: Exception while creating DShow graph {0} {1}", ex.Message, ex.StackTrace); Cleanup(); return(false); } }
private void Cleanup() { if (_graphBuilder == null || (VMR9Util.g_vmr9 != null && VMR9Util.g_vmr9.isCurrentStopping)) { return; } int hr; using (Settings xmlreader = new MPSettings()) { int codecValue = 0; string codecType = ""; codecType = xmlreader.GetValueAsString("dvdplayer", "videocodec", ""); if (codecType == "InterVideo Video Decoder") { codecValue = xmlreader.GetValueAsInt("videocodec", "intervideo", 1); Log.Info("DVDPlayer9:Resetting InterVideo DXVA to {0}", codecValue); using ( RegistryKey subkey = Registry.CurrentUser.CreateSubKey(@"Software\InterVideo\Common\VideoDec\MediaPortal")) { subkey.SetValue("DXVA", codecValue); } } if (codecType.StartsWith("CyberLink Video/SP Decoder")) { codecValue = xmlreader.GetValueAsInt("videocodec", "cyberlink", 1); Log.Info("DVDPlayer9:Resetting CyberLink DXVA to {0}", codecValue); using (RegistryKey subkey = Registry.CurrentUser.CreateSubKey(@"Software\Cyberlink\Common\CLVSD\MediaPortal")) { subkey.SetValue("UIUseHVA", codecValue); } } if (codecType == "NVIDIA Video Decoder") { codecValue = xmlreader.GetValueAsInt("videocodec", "nvidia", 1); Log.Info("DVDPlayer9:Resetting NVIDIA DXVA to {0}", codecValue); using (RegistryKey subkey = Registry.LocalMachine.CreateSubKey(@"Software\NVIDIA Corporation\Filters\Video")) { subkey.SetValue("EnableDXVA", codecValue); } } } try { Log.Info("DVDPlayer9: cleanup DShow graph"); _state = PlayState.Stopped; VMR9Util.g_vmr9.EVRSetDVDMenuState(false); if (VMR9Util.g_vmr9 != null) { VMR9Util.g_vmr9.Vmr9MediaCtrl(_mediaCtrl); VMR9Util.g_vmr9.Enable(false); } if (_mediaEvt != null) { hr = _mediaEvt.SetNotifyWindow(IntPtr.Zero, WM_GRAPHNOTIFY, IntPtr.Zero); } if (VMR9Util.g_vmr9 != null && VMR9Util.g_vmr9._vmr9Filter != null) { MadvrInterface.EnableExclusiveMode(false, VMR9Util.g_vmr9._vmr9Filter); DirectShowUtil.DisconnectAllPins(_graphBuilder, VMR9Util.g_vmr9._vmr9Filter); Log.Info("DVDPlayer9: Cleanup VMR9"); } // Clean post process PostProcessingEngine.GetInstance().FreePostProcess(); AudioPostEngine.GetInstance().FreePostProcess(); if (_videoWin != null && GUIGraphicsContext.VideoRenderer != GUIGraphicsContext.VideoRendererType.madVR) { _videoWin.put_Owner(IntPtr.Zero); _videoWin.put_Visible(OABool.False); } _mediaCtrl = null; _visible = false; _dvdCtrl = null; _dvdInfo = null; _videoWin = null; _basicVideo = null; _basicAudio = null; _mediaPos = null; _pendingCmd = false; if (_cmdOption != null) { DirectShowUtil.FinalReleaseComObject(_cmdOption); _cmdOption = null; } if (_dvdbasefilter != null) { DirectShowUtil.FinalReleaseComObject(_dvdbasefilter); _dvdbasefilter = null; } if (_dvdGraph != null) { DirectShowUtil.FinalReleaseComObject(_dvdGraph); _dvdGraph = null; } if (_line21Decoder != null) { DirectShowUtil.FinalReleaseComObject(_line21Decoder); _line21Decoder = null; } if (_graphBuilder != null) { DirectShowUtil.RemoveFilters(_graphBuilder); // _rotEntry has a reference to _graphBuilder (see _rotEntry ctor) // so, release of _rotEntry must be before _graphBuilder is released if (_rotEntry != null) { _rotEntry.SafeDispose(); _rotEntry = null; } DirectShowUtil.FinalReleaseComObject(_graphBuilder); _graphBuilder = null; } if (VMR9Util.g_vmr9 != null) { VMR9Util.g_vmr9.SafeDispose(); VMR9Util.g_vmr9 = null; } _state = PlayState.Init; } catch (Exception ex) { if (VMR9Util.g_vmr9 != null) { VMR9Util.g_vmr9.RestoreGuiForMadVr(); VMR9Util.g_vmr9.SafeDispose(); } Log.Error("DVDPlayer9: Exception while cleanuping DShow graph - {0} {1}", ex.Message, ex.StackTrace); } Log.Info("DVDPlayer9: Disabling DX9 exclusive mode"); GUIMessage msg = new GUIMessage(GUIMessage.MessageType.GUI_MSG_SWITCH_FULL_WINDOWED, 0, 0, 0, 0, 0, null); GUIWindowManager.SendMessage(msg); }
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.ToLowerInvariant() != ".ts" && ext.ToLowerInvariant() != ".mpg") { Log.Info("TSReader2WMV: wrong file format"); return(false); } Log.Info("TSReader2WMV: create graph"); graphBuilder = (IGraphBuilder) new FilterGraph(); _rotEntry = new DsROTEntry((IFilterGraph)graphBuilder); Log.Info("TSReader2WMV: add filesource"); TsReader reader = new TsReader(); tsreaderSource = (IBaseFilter)reader; //ITSReader ireader = (ITSReader)reader; //ireader.SetTsReaderCallback(this); //ireader.SetRequestAudioChangeCallback(this); IBaseFilter filter = (IBaseFilter)tsreaderSource; graphBuilder.AddFilter(filter, "TSReader Source"); IFileSourceFilter fileSource = (IFileSourceFilter)tsreaderSource; Log.Info("TSReader2WMV: 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("TSReader2WMV: 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("TSReader2WMV: 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("TSReader2WMV: 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("TSReader2WMV: 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("TSReader2WMV: add audio/video decoders to graph"); if (usingH264 == false) { Log.Info("TSReader2WMV: add mpeg2 video decoder:{0}", strVideoCodec); VideoCodec = DirectShowUtil.AddFilterToGraph(graphBuilder, strVideoCodec); if (VideoCodec == null) { Log.Error("TSReader2WMV: unable to add mpeg2 video decoder"); Cleanup(); return(false); } } else { Log.Info("TSReader2WMV: add h264 video codec:{0}", strH264VideoCodec); VideoCodec = DirectShowUtil.AddFilterToGraph(graphBuilder, strH264VideoCodec); if (VideoCodec == null) { Log.Error("TSReader2WMV: FAILED:unable to add h264 video codec"); Cleanup(); return(false); } } if (usingAAC == false) { Log.Info("TSReader2WMV: add mpeg2 audio codec:{0}", strAudioCodec); AudioCodec = DirectShowUtil.AddFilterToGraph(graphBuilder, strAudioCodec); if (AudioCodec == null) { Log.Error("TSReader2WMV: FAILED:unable to add mpeg2 audio codec"); Cleanup(); return(false); } } else { Log.Info("TSReader2WMV: add aac audio codec:{0}", strAACAudioCodec); AudioCodec = DirectShowUtil.AddFilterToGraph(graphBuilder, strAACAudioCodec); if (AudioCodec == null) { Log.Error("TSReader2WMV: FAILED:unable to add aac audio codec"); Cleanup(); return(false); } } Log.Info("TSReader2WMV: 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("TSReader2WMV: FAILED: unable to get pins of video/audio codecs"); Cleanup(); return(false); } hr = graphBuilder.Connect(pinOut0, pinIn0); if (hr != 0) { Log.Error("TSReader2WMV: FAILED: unable to connect audio pins :0x{0:X}", hr); Cleanup(); return(false); } hr = graphBuilder.Connect(pinOut1, pinIn1); if (hr != 0) { Log.Error("TSReader2WMV: 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("TSReader2WMV: start pre-run"); mediaControl = graphBuilder as IMediaControl; mediaSeeking = tsreaderSource as IMediaSeeking; 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("TSReader2WMV: movie duration:{0}", Util.Utils.SecondsToHMSString((int)duration)); hr = mediaControl.Run(); if (hr != 0) { Log.Error("TSReader2WMV: 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("TSReader2WMV: pre-run done"); Log.Info("TSReader2WMV: Get duration of movie"); mediaControl.Stop(); FilterState state; mediaControl.GetState(500, out state); GC.Collect(); GC.Collect(); GC.Collect(); GC.WaitForPendingFinalizers(); Log.Info("TSReader2WMV: reconnect mpeg2 video codec->ASF WM Writer"); graphBuilder.RemoveFilter(fileWriterbase); if (!AddWmAsfWriter(outputFilename, quality, standard)) { return(false); } Log.Info("TSReader2WMV: Start transcoding"); hr = mediaControl.Run(); if (hr != 0) { Log.Error("TSReader2WMV: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 Get(string fileName, out float uoffs, out float voffs, out float umax, out float vmax, out int iWidth, out int iHeight, out Texture tex, out int textureNo) { uoffs = voffs = umax = vmax = 0.0f; iWidth = iHeight = 0; textureNo = -1; tex = null; if (_packedTextures == null) { return(false); } if (fileName.StartsWith(@"\")) { fileName = fileName.Remove(0, 1); } fileName = fileName.ToLowerInvariant(); if (fileName == string.Empty) { return(false); } int index = 0; PackedTexture bigOne = null; PackedTextureNode foundNode = null; // Look for textures first in the current theme location. Theme textures override default textures. // If the default theme is selected then avoid looking through the theme. if (!GUIThemeManager.CurrentThemeIsDefault) { string skinThemeTexturePath = GUIThemeManager.CurrentTheme + @"\media\"; skinThemeTexturePath = skinThemeTexturePath.ToLowerInvariant(); // If a theme texture exists but was not able to be packed then avoid trying to unpack the texture all together. This prevents // a base skin texture from being unpacked and returned when the base texture could be packed but the overriding theme texture // could not be packed. if (!IsTexturePacked(skinThemeTexturePath + fileName)) { return(false); } foreach (PackedTexture texture in _packedTextures) { if ((foundNode = texture.root.Get(skinThemeTexturePath + fileName)) != null) { bigOne = texture; break; } index++; } } // No theme texture was found. Check the default skin location. if (foundNode == null) { index = 0; foreach (PackedTexture texture in _packedTextures) { if ((foundNode = texture.root.Get(fileName)) != null) { bigOne = texture; break; } index++; } } if (foundNode != null) { uoffs = (float)(foundNode.Rect.Left + 1) / bigOne.root.Rect.Width; voffs = (float)(foundNode.Rect.Top + 1) / bigOne.root.Rect.Height; umax = (float)(foundNode.Rect.Width - 2) / bigOne.root.Rect.Width; vmax = (float)(foundNode.Rect.Height - 2) / bigOne.root.Rect.Height; iWidth = foundNode.Rect.Width - 2; iHeight = foundNode.Rect.Height - 2; if (bigOne.texture == null) { LoadPackedGraphics(index); } tex = bigOne.texture; if (bigOne.textureNo == -1) { unsafe { IntPtr ptr = DirectShowUtil.GetUnmanagedTexture(bigOne.texture); bigOne.textureNo = DXNative.FontEngineAddTexture(ptr.ToInt32(), true, ptr.ToPointer()); Log.Info("TexturePacker: fontengine add texure:{0}", bigOne.textureNo); } } textureNo = bigOne.textureNo; return(true); } return(false); }
public bool LoadSubtitles(IGraphBuilder graphBuilder, string filename) { LoadSettings(); MpcSubtitles.SetDefaultStyle(ref this.defStyle, this.overrideASSStyle); if (selectionOff) { MpcSubtitles.SetShowForcedOnly(false); } else { MpcSubtitles.SetShowForcedOnly(!this.autoShow); } //remove DirectVobSub DirectVobSubUtil.RemoveFromGraph(graphBuilder); { //remove InternalScriptRenderer as it takes subtitle pin IBaseFilter isr = null; DirectShowUtil.FindFilterByClassID(graphBuilder, ClassId.InternalScriptRenderer, out isr); if (isr != null) { graphBuilder.RemoveFilter(isr); DirectShowUtil.ReleaseComObject(isr); } } FFDShowEngine.DisableFFDShowSubtitles(graphBuilder); Size size = new Size(GUIGraphicsContext.Width, GUIGraphicsContext.Height); // Get Default Language from MP Setting and parse it to MPC-HC Engine (needed for forced track) string defaultLanguageCulture = "EN"; string localizedCINameSub = "EN"; int lcidCI = 0; using (Settings xmlreader = new MPSettings()) { try { if (g_Player.IsVideo && (g_Player.CurrentFile.ToUpperInvariant().Contains(@"\BDMV\INDEX.BDMV"))) { localizedCINameSub = (xmlreader.GetValueAsString("bdplayer", "subtitlelanguage", "English")); foreach (CultureInfo ci in CultureInfo.GetCultures(CultureTypes.NeutralCultures)) { if (ci.EnglishName == localizedCINameSub) { lcidCI = ci.TextInfo.LCID;; } } Log.Info("MpcEngine: Subtitle Blu-ray Player CultureInfo {0}", localizedCINameSub); } else { CultureInfo ci = new CultureInfo(xmlreader.GetValueAsString("subtitles", "language", defaultLanguageCulture)); lcidCI = ci.TextInfo.LCID; Log.Info("MpcEngine: Subtitle VideoPlayer CultureInfo {0}", ci); } } catch (Exception ex) { CultureInfo ci = new CultureInfo(defaultLanguageCulture); lcidCI = ci.TextInfo.LCID; Log.Error( "MpcEngine: SelectSubtitleLanguage - unable to build CultureInfo, make sure MediaPortal.xml is not corrupted! - {0}", ex); } } return(MpcSubtitles.LoadSubtitles( DirectShowUtil.GetUnmanagedDevice(GUIGraphicsContext.DX9Device), size, filename, graphBuilder, subPaths, lcidCI)); }
/// <summary> create the used COM components and get the interfaces. </summary> protected override bool GetInterfaces(string path) { int hr; object comobj = null; _freeNavigator = true; _dvdInfo = null; _dvdCtrl = null; _videoWin = null; string dvdDNavigator = "DVD Navigator"; string aspectRatio = ""; string displayMode = ""; bool turnoffDXVA = false; bool showClosedCaptions = false; int codecValue = 0; string codecType = ""; using (Settings xmlreader = new MPSettings()) { showClosedCaptions = xmlreader.GetValueAsBool("dvdplayer", "showclosedcaptions", false); dvdDNavigator = xmlreader.GetValueAsString("dvdplayer", "navigator", "DVD Navigator"); if (dvdDNavigator.ToLower().Contains("cyberlink dvd navigator")) { _cyberlinkDVDNavigator = true; } aspectRatio = xmlreader.GetValueAsString("dvdplayer", "armode", "").ToLower(); if (aspectRatio == "crop") { arMode = AspectRatioMode.Crop; } else if (aspectRatio == "letterbox") { arMode = AspectRatioMode.LetterBox; } else if (aspectRatio == "stretch") { arMode = AspectRatioMode.Stretched; } else if (aspectRatio == "follow stream") { arMode = AspectRatioMode.StretchedAsPrimary; } displayMode = xmlreader.GetValueAsString("dvdplayer", "displaymode", "").ToLower(); if (displayMode == "default") { _videoPref = DvdPreferredDisplayMode.DisplayContentDefault; } else if (displayMode == "16:9") { _videoPref = DvdPreferredDisplayMode.Display16x9; } else if (displayMode == "4:3 pan scan") { _videoPref = DvdPreferredDisplayMode.Display4x3PanScanPreferred; } else if (displayMode == "4:3 letterbox") { _videoPref = DvdPreferredDisplayMode.Display4x3LetterBoxPreferred; } turnoffDXVA = xmlreader.GetValueAsBool("dvdplayer", "turnoffdxva", true); Log.Info("DVDPlayer9:Turn off DXVA value = {0}", turnoffDXVA); if (turnoffDXVA == true) { codecType = xmlreader.GetValueAsString("dvdplayer", "videocodec", ""); Log.Info("DVDPlayer9:Video Decoder = {0}", codecType); if (codecType == "InterVideo Video Decoder") { codecValue = xmlreader.GetValueAsInt("videocodec", "intervideo", 1); if (codecValue == 1) { Log.Info("DVDPlayer9:Turning InterVideo DXVA off"); using ( RegistryKey subkey = Registry.CurrentUser.CreateSubKey(@"Software\InterVideo\Common\VideoDec\MediaPortal")) { subkey.SetValue("DXVA", 0); } } if (codecValue == 0) { Log.Info("DVDPlayer9:InterVideo DXVA already off"); } } if (codecType.StartsWith("CyberLink Video/SP Decoder")) { codecValue = xmlreader.GetValueAsInt("videocodec", "cyberlink", 1); if (codecValue == 1) { Log.Info("DVDPlayer9:Turning CyberLink DXVA off"); using ( RegistryKey subkey = Registry.CurrentUser.CreateSubKey(@"Software\Cyberlink\Common\CLVSD\MediaPortal")) { subkey.SetValue("UIUseHVA", 0); } } if (codecValue == 0) { Log.Info("DVDPlayer9:CyberLink DXVA already off"); } } if (codecType == "NVIDIA Video Decoder") { codecValue = xmlreader.GetValueAsInt("videocodec", "nvidia", 1); if (codecValue == 1) { Log.Info("DVDPlayer9:Turning NVIDIA DXVA off"); using ( RegistryKey subkey = Registry.LocalMachine.CreateSubKey(@"Software\NVIDIA Corporation\Filters\Video")) { subkey.SetValue("EnableDXVA", 0); } } if (codecValue == 0) { Log.Info("DVDPlayer9:NVIDIA DXVA already off"); } } } } Log.Info("DVDPlayer9:Enabling DX9 exclusive mode"); GUIMessage msg = new GUIMessage(GUIMessage.MessageType.GUI_MSG_SWITCH_FULL_WINDOWED, 0, 0, 0, 1, 0, null); GUIWindowManager.SendMessage(msg); try { _dvdGraph = (IDvdGraphBuilder) new DvdGraphBuilder(); hr = _dvdGraph.GetFiltergraph(out _graphBuilder); DsError.ThrowExceptionForHR(hr); _rotEntry = new DsROTEntry((IFilterGraph)_graphBuilder); _vmr9 = new VMR9Util(); _vmr9.AddVMR9(_graphBuilder); _vmr9.Enable(false); try { Log.Info("DVDPlayer9:Add {0}", dvdDNavigator); _dvdbasefilter = DirectShowUtil.AddFilterToGraph(_graphBuilder, dvdDNavigator); if (_dvdbasefilter != null) { AddPreferedCodecs(_graphBuilder); _dvdCtrl = (IDvdControl2)_dvdbasefilter; if (_dvdCtrl != null) { _dvdInfo = (IDvdInfo2)_dvdbasefilter; if (!String.IsNullOrEmpty(path)) { hr = _dvdCtrl.SetDVDDirectory(path); DsError.ThrowExceptionForHR(hr); } _dvdCtrl.SetOption(DvdOptionFlag.HMSFTimeCodeEvents, true); // use new HMSF timecode format _dvdCtrl.SetOption(DvdOptionFlag.ResetOnStop, false); DirectShowUtil.RenderGraphBuilderOutputPins(_graphBuilder, _dvdbasefilter); _freeNavigator = false; } } } catch (Exception ex) { Log.Error("DVDPlayer9:Add {0} as navigator failed: {1}", dvdDNavigator, ex.Message); } if (_dvdInfo == null) { Log.Info("Dvdplayer9:Volume rendered, get interfaces"); hr = _dvdGraph.GetDvdInterface(typeof(IDvdInfo2).GUID, out comobj); DsError.ThrowExceptionForHR(hr); _dvdInfo = (IDvdInfo2)comobj; comobj = null; } if (_dvdCtrl == null) { Log.Info("Dvdplayer9:Get IDvdControl2"); hr = _dvdGraph.GetDvdInterface(typeof(IDvdControl2).GUID, out comobj); DsError.ThrowExceptionForHR(hr); _dvdCtrl = (IDvdControl2)comobj; comobj = null; if (_dvdCtrl != null) { Log.Info("Dvdplayer9:Get IDvdControl2"); } else { Log.Error("Dvdplayer9:Failed to get IDvdControl2"); } } // disable Closed Captions! IBaseFilter basefilter; _graphBuilder.FindFilterByName("Line 21 Decoder", out basefilter); if (basefilter == null) { _graphBuilder.FindFilterByName("Line21 Decoder", out basefilter); } if (basefilter == null) { _graphBuilder.FindFilterByName("Line 21 Decoder 2", out basefilter); } if (basefilter != null) { Log.Info("Dvdplayer9: Line21 Decoder (Closed Captions), in use: {0}", showClosedCaptions); _line21Decoder = (IAMLine21Decoder)basefilter; if (_line21Decoder != null) { AMLine21CCState state = showClosedCaptions ? AMLine21CCState.On : AMLine21CCState.Off; hr = _line21Decoder.SetServiceState(state); if (hr == 0) { Log.Info("DVDPlayer9: Closed Captions state change successful"); } else { Log.Info("DVDPlayer9: Failed to change Closed Captions state"); } } } if (!_vmr9.IsVMR9Connected) { Log.Info("DVDPlayer9:Failed vmr9 not connected"); _mediaCtrl = null; Cleanup(); return(false); } #region PostProcessingEngine Detection IPostProcessingEngine postengine = PostProcessingEngine.GetInstance(true); if (!postengine.LoadPostProcessing(_graphBuilder)) { PostProcessingEngine.engine = new PostProcessingEngine.DummyEngine(); } #endregion _mediaCtrl = (IMediaControl)_graphBuilder; _mediaEvt = (IMediaEventEx)_graphBuilder; _basicAudio = (IBasicAudio)_graphBuilder; _mediaPos = (IMediaPosition)_graphBuilder; _basicVideo = (IBasicVideo2)_graphBuilder; _videoWidth = _vmr9.VideoWidth; _videoHeight = _vmr9.VideoHeight; DirectShowUtil.SetARMode(_graphBuilder, arMode); _vmr9.SetDeinterlaceMode(); _vmr9.Enable(true); Log.Info("Dvdplayer9:Graph created"); _started = true; return(true); } catch (Exception ex) { Log.Error("DvdPlayer9:Exception while creating DShow graph {0} {1}", ex.Message, ex.StackTrace); CloseInterfaces(); return(false); } }
private void Cleanup() { if (graphBuilder == null) { return; } int hr; Log.Info("RTSPPlayer:cleanup DShow graph"); try { if (_mediaCtrl != null) { int counter = 0; FilterState state; hr = _mediaCtrl.Stop(); hr = _mediaCtrl.GetState(10, out state); while (state != FilterState.Stopped || GUIGraphicsContext.InVmr9Render) { Thread.Sleep(100); hr = _mediaCtrl.GetState(10, out state); counter++; if (counter >= 30) { if (state != FilterState.Stopped) { Log.Error("RTSPPlayer: graph still running"); } if (GUIGraphicsContext.InVmr9Render) { Log.Error("RTSPPlayer: in renderer"); } break; } } _mediaCtrl = null; } if (Vmr9 != null) { Vmr9.Enable(false); } if (mediaEvt != null) { hr = mediaEvt.SetNotifyWindow(IntPtr.Zero, WM_GRAPHNOTIFY, IntPtr.Zero); mediaEvt = null; } videoWin = graphBuilder as IVideoWindow; if (videoWin != null) { hr = videoWin.put_Visible(OABool.False); hr = videoWin.put_Owner(IntPtr.Zero); videoWin = null; } _mediaSeeking = null; mediaPos = null; basicAudio = null; basicVideo = null; videoWin = null; SubEngine.GetInstance().FreeSubtitles(); if (graphBuilder != null) { DirectShowUtil.RemoveFilters(graphBuilder); if (_rotEntry != null) { _rotEntry.SafeDispose(); _rotEntry = null; } DirectShowUtil.ReleaseComObject(graphBuilder); graphBuilder = null; } if (Vmr9 != null) { Vmr9.SafeDispose(); Vmr9 = null; } GUIGraphicsContext.form.Invalidate(true); _state = PlayState.Init; if (_mpegDemux != null) { Log.Info("cleanup mpegdemux"); while ((hr = DirectShowUtil.ReleaseComObject(_mpegDemux)) > 0) { ; } _mpegDemux = null; } if (_rtspSource != null) { Log.Info("cleanup _rtspSource"); while ((hr = DirectShowUtil.ReleaseComObject(_rtspSource)) > 0) { ; } _rtspSource = null; } if (_subtitleFilter != null) { while ((hr = DirectShowUtil.ReleaseComObject(_subtitleFilter)) > 0) { ; } _subtitleFilter = null; if (this.dvbSubRenderer != null) { this.dvbSubRenderer.SetPlayer(null); } this.dvbSubRenderer = null; } if (vobSub != null) { Log.Info("cleanup vobSub"); while ((hr = DirectShowUtil.ReleaseComObject(vobSub)) > 0) { ; } vobSub = null; } } catch (Exception ex) { Log.Error("RTSPPlayer: Exception while cleanuping DShow graph - {0} {1}", ex.Message, ex.StackTrace); } //switch back to directx windowed mode Log.Info("RTSPPlayer: Disabling DX9 exclusive mode"); GUIMessage msg = new GUIMessage(GUIMessage.MessageType.GUI_MSG_SWITCH_FULL_WINDOWED, 0, 0, 0, 0, 0, null); GUIWindowManager.SendMessage(msg); }
/// <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); } }
private void Cleanup() { Log.Info("DVRMS2DIVX: cleanup"); if (_rotEntry != null) { _rotEntry.SafeDispose(); } _rotEntry = null; if (mediaControl != null) { mediaControl.Stop(); mediaControl = null; } fileWriterFilter = null; mediaSeeking = null; mediaEvt = null; mediaPos = null; mediaControl = null; if (divxCodec != null) { DirectShowUtil.ReleaseComObject(divxCodec); } divxCodec = null; if (mp3Codec != null) { DirectShowUtil.ReleaseComObject(mp3Codec); } mp3Codec = null; if (aviMuxer != null) { DirectShowUtil.ReleaseComObject(aviMuxer); } aviMuxer = null; if (Mpeg2AudioCodec != null) { DirectShowUtil.ReleaseComObject(Mpeg2AudioCodec); } Mpeg2AudioCodec = null; if (Mpeg2VideoCodec != null) { DirectShowUtil.ReleaseComObject(Mpeg2VideoCodec); } Mpeg2VideoCodec = null; if (bufferSource != null) { DirectShowUtil.ReleaseComObject(bufferSource); } bufferSource = null; DirectShowUtil.RemoveFilters(graphBuilder); if (graphBuilder != null) { DirectShowUtil.ReleaseComObject(graphBuilder); } graphBuilder = null; GC.Collect(); GC.Collect(); GC.Collect(); GC.WaitForPendingFinalizers(); }
public override bool Play(string strFile) { updateTimer = DateTime.Now; m_speedRate = 10000; GUIGraphicsContext.IsWindowVisible = false; m_iVolume = 100; _state = PlayState.Init; m_strCurrentFile = strFile; m_bFullScreen = true; m_ar = GUIGraphicsContext.ARType; VideoRendererStatistics.VideoState = VideoRendererStatistics.State.VideoPresent; _updateNeeded = true; Log.Info("RTSPPlayer:play {0}", strFile); //lock ( typeof(VideoPlayerVMR7) ) { CloseInterfaces(); m_bStarted = false; if (!GetInterfaces()) { m_strCurrentFile = ""; CloseInterfaces(); return(false); } int hr = mediaEvt.SetNotifyWindow(GUIGraphicsContext.ActiveForm, WM_GRAPHNOTIFY, IntPtr.Zero); if (hr < 0) { Error.SetError("Unable to play movie", "Can not set notifications"); m_strCurrentFile = ""; CloseInterfaces(); return(false); } DirectShowUtil.SetARMode(graphBuilder, AspectRatioMode.Stretched); _rotEntry = new DsROTEntry((IFilterGraph)graphBuilder); // DsUtils.DumpFilters(graphBuilder); hr = _mediaCtrl.Run(); if (hr < 0) { Error.SetError("Unable to play movie", "Unable to start movie"); m_strCurrentFile = ""; CloseInterfaces(); return(false); } GUIMessage msg = new GUIMessage(GUIMessage.MessageType.GUI_MSG_PLAYBACK_STARTED, 0, 0, 0, 0, 0, null); msg.Label = strFile; GUIWindowManager.SendThreadMessage(msg); _state = PlayState.Playing; //Brutus GUIGraphicsContext.IsFullScreenVideo=true; m_iPositionX = GUIGraphicsContext.VideoWindow.X; m_iPositionY = GUIGraphicsContext.VideoWindow.Y; m_iWidth = GUIGraphicsContext.VideoWindow.Width; m_iHeight = GUIGraphicsContext.VideoWindow.Height; m_ar = GUIGraphicsContext.ARType; _updateNeeded = true; SetVideoWindow(); mediaPos.get_Duration(out _duration); Log.Info("RTSPPlayer:Duration:{0}", _duration); if (_mediaType == g_Player.MediaType.TV) { //if (_duration < 1) _duration = 1; //SeekAbsolute(_duration - 1); } else { //SeekAbsolute(0); } OnInitialized(); } // Wait for a while to wait VMR9 to get ready. // Implemented due to problems starting to play before VMR9 was ready resulting in black screen. Thread.Sleep(200); 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() != ".dvr-ms" && ext.ToLower() != ".sbe") { Log.Info("DVRMS2DIVX: wrong file format"); return(false); } //disable xvid status window while encoding /* try * { * using (RegistryKey subkey = Registry.CurrentUser.OpenSubKey(@"Software\GNU\XviD", true)) * { * if (subkey != null) * { * Int32 uivalue = 0; * subkey.SetValue("display_status", (Int32)uivalue); * subkey.SetValue("debug", (Int32)uivalue); * subkey.SetValue("bitrate", (Int32)bitrate); * * uivalue = 1; * subkey.SetValue("interlacing", (Int32)uivalue); * } * } * } * catch (Exception) * { * }*/ //Type comtype = null; //object comobj = null; try { graphBuilder = (IGraphBuilder) new FilterGraph(); _rotEntry = new DsROTEntry((IFilterGraph)graphBuilder); Log.Info("DVRMS2DIVX: add filesource"); bufferSource = (IStreamBufferSource) new StreamBufferSource(); IBaseFilter filter = (IBaseFilter)bufferSource; graphBuilder.AddFilter(filter, "SBE SOURCE"); IFileSourceFilter fileSource = (IFileSourceFilter)bufferSource; Log.Info("DVRMS2DIVX: load file:{0}", info.file); int hr = fileSource.Load(info.file, null); /*string strDemuxerMoniker = @"@device:sw:{083863F1-70DE-11D0-BD40-00A0C911CE86}\{AFB6C280-2C41-11D3-8A60-0000F81E0E4A}"; * * mpegDemuxer = Marshal.BindToMoniker(strDemuxerMoniker) as IBaseFilter; * if (mpegDemuxer == null) * { * Log.Error("DVRMS2DIVX:FAILED:unable to add mpeg2 demuxer"); * Cleanup(); * return false; * } * hr = graphBuilder.AddFilter(mpegDemuxer, "MPEG-2 Demultiplexer"); * if (hr != 0) * { * Log.Error("DVRMS2DIVX:FAILED:Add mpeg2 demuxer to filtergraph :0x{0:X}", hr); * Cleanup(); * return false; * }*/ //add mpeg2 audio/video codecs string strVideoCodecMoniker = @"@device:sw:{083863F1-70DE-11D0-BD40-00A0C911CE86}\{39F498AF-1A09-4275-B193-673B0BA3D478}"; string strAudioCodec = "MPC - MPA Decoder Filter"; Log.Info("DVRMS2DIVX: add MPV mpeg2 video decoder"); Mpeg2VideoCodec = Marshal.BindToMoniker(strVideoCodecMoniker) as IBaseFilter; if (Mpeg2VideoCodec == null) { Log.Error("DVRMS2DIVX:FAILED:unable to add MPV mpeg2 video decoder"); Cleanup(); return(false); } hr = graphBuilder.AddFilter(Mpeg2VideoCodec, "MPC - MPEG-2 Video Decoder (Gabest)"); if (hr != 0) { Log.Error("DVRMS2DIVX:FAILED:Add MPV mpeg2 video to filtergraph :0x{0:X}", hr); Cleanup(); return(false); } Log.Info("DVRMS2DIVX: add MPA mpeg2 audio codec:{0}", strAudioCodec); Mpeg2AudioCodec = DirectShowUtil.AddFilterToGraph(graphBuilder, strAudioCodec); if (Mpeg2AudioCodec == null) { Log.Error("DVRMS2DIVX:FAILED:unable to add MPV mpeg2 audio codec"); Cleanup(); return(false); } //connect output #0 of streambuffer source->mpeg2 audio codec pin 1 //connect output #1 of streambuffer source->mpeg2 video codec pin 1 Log.Info("DVRMS2DIVX: connect streambufer source->mpeg audio/video decoders"); 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("DVRMS2DIVX: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("DVRMS2DIVX:FAILED:unable to get pins of mpeg2 video/audio codec"); Cleanup(); return(false); } hr = graphBuilder.Connect(pinOut0, pinIn1); if (hr != 0) { Log.Error("DVRMS2DIVX:FAILED:unable to connect audio pins :0x{0:X}", hr); Cleanup(); return(false); } hr = graphBuilder.Connect(pinOut1, pinIn0); if (hr != 0) { Log.Error("DVRMS2DIVX:FAILED:unable to connect video pins :0x{0:X}", hr); Cleanup(); return(false); } if (!AddCodecs(graphBuilder, info)) { return(false); } // hr=(graphBuilder as IMediaFilter).SetSyncSource(null); // if (hr!=0) // Log.Error("DVRMS2DIVX:FAILED:to SetSyncSource :0x{0:X}",hr); mediaControl = graphBuilder as IMediaControl; mediaSeeking = bufferSource as IStreamBufferMediaSeeking; mediaEvt = graphBuilder as IMediaEventEx; mediaPos = graphBuilder as IMediaPosition; //get file duration Log.Info("DVRMS2DIVX: Get duration of movie"); 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("DVRMS2DIVX: movie duration:{0}", MediaPortal.Util.Utils.SecondsToHMSString((int)duration)); // hr=(graphBuilder as IMediaFilter).SetSyncSource(null); // if (hr!=0) // Log.Error("DVRMS2DIVX:FAILED:to SetSyncSource :0x{0:X}",hr); hr = mediaControl.Run(); if (hr != 0) { Log.Error("DVRMS2DIVX: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(aviMuxer); graphBuilder.RemoveFilter(divxCodec); graphBuilder.RemoveFilter(mp3Codec); graphBuilder.RemoveFilter((IBaseFilter)fileWriterFilter); if (!AddCodecs(graphBuilder, info)) { return(false); } // hr=(graphBuilder as IMediaFilter).SetSyncSource(null); // if (hr!=0) // Log.Error("DVRMS2DIVX:FAILED:to SetSyncSource :0x{0:X}",hr); Log.Info("DVRMS2DIVX: start transcoding"); hr = mediaControl.Run(); if (hr != 0) { Log.Error("DVRMS2DIVX:FAILED:unable to start graph :0x{0:X}", hr); Cleanup(); return(false); } } catch (Exception ex) { Log.Error("DVRMS2DIVX:Unable create graph: {0}", ex.Message); Cleanup(); return(false); } return(true); }
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 static IBaseFilter AddToGraph(IGraphBuilder graphBuilder) { IBaseFilter vob = null; using (Settings xmlreader = new MPSettings()) { string engineType = xmlreader.GetValueAsString("subtitles", "engine", "DirectVobSub"); XySubFilter = engineType.Equals("XySubFilter"); } if (!XySubFilter) { DirectShowUtil.FindFilterByClassID(graphBuilder, ClassId.DirectVobSubAutoload, out vob); if (vob == null) { //Try the "normal" filter then. DirectShowUtil.FindFilterByClassID(graphBuilder, ClassId.DirectVobSubNormal, out vob); } } else { //Try the XySubFilter "autoload" filter. DirectShowUtil.FindFilterByClassID(graphBuilder, ClassId.XySubFilterAutoload, out vob); if (vob != null) { return(vob); } //Try the XySubFilter "normal" filter then. DirectShowUtil.FindFilterByClassID(graphBuilder, ClassId.XySubFilterNormal, out vob); if (vob != null) { return(vob); } vob = DirectShowUtil.AddFilterToGraph(graphBuilder, "XySubFilter"); if (vob == null) { Log.Warn("VideoPlayerVMR9: DirectVobSub or XySubFilter filter not found! You need to install XySubFilter"); return(null); } Log.Debug("VideoPlayerVMR9: VobSub filter added to graph"); return(vob); } //if the directvobsub filter has not been added to the graph. (i.e. with evr) //we add a bit more intelligence to determine if subtitles are enabled. //and if subtitles are present for the video / movie then we add it if necessary to the graph. if (vob == null) { Log.Info("VideoPlayerVMR9: No VobSub filter in the current graph"); //the filter has not been added lets check if it should be added or not. //add the filter to the graph vob = DirectShowUtil.AddFilterToGraph(graphBuilder, "DirectVobSub"); if (vob == null) { Log.Warn("VideoPlayerVMR9: DirectVobSub or XySubFilter filter not found! You need to install VSFilter"); return(null); } Log.Debug("VideoPlayerVMR9: VobSub filter added to graph"); } else // VobSub already loaded { return(vob); } // Check if Haali Media Splitter is in the graph. IBaseFilter hms = null; DirectShowUtil.FindFilterByClassID(graphBuilder, ClassId.HaaliGuid, out hms); if (hms == null) { DirectShowUtil.FindFilterByClassID(graphBuilder, ClassId.MPCMatroska, out hms); } if (hms == null) { DirectShowUtil.FindFilterByClassID(graphBuilder, ClassId.MPCMatroskaSource, out hms); } if (hms == null) { DirectShowUtil.FindFilterByClassID(graphBuilder, ClassId.LAVFilter, out hms); } if (hms == null) { DirectShowUtil.FindFilterByClassID(graphBuilder, ClassId.LAVFilterSource, out hms); } if (hms != null) { IPin pinSubTo = null; // It is. Connect it' subtitle output pin (if any) to Vobsub's subtitle input. pinSubTo = DirectShowUtil.FindPin(hms, PinDirection.Output, "Subtitle"); if (pinSubTo == null) { while (true) { IPin freeSubtitle = DirectShowUtil.FindFirstFreePinSub(hms, PinDirection.Output, ""); IPin freeVobSub = DirectShowUtil.FindFirstFreePin(vob, PinDirection.Input, "Input"); if (freeSubtitle != null && freeVobSub != null) { Log.Debug("VideoPlayerVMR9: Connecting Matroska's subtitle output to VobSub's input."); graphBuilder.Connect(freeSubtitle, freeVobSub); DirectShowUtil.ReleaseComObject(freeSubtitle); freeSubtitle = null; DirectShowUtil.ReleaseComObject(freeVobSub); freeVobSub = null; } else { break; } } } DirectShowUtil.ReleaseComObject(hms); hms = null; if (pinSubTo != null) { Log.Debug("VideoPlayerVMR9: Connecting Haali's subtitle output to VobSub's input."); // Try to render pins IPin pinVobSubSub = DirectShowUtil.FindPin(vob, PinDirection.Input, "Input"); // If pinSubTo is already connected (disconnect it) graphBuilder.Disconnect(pinSubTo); graphBuilder.Connect(pinSubTo, pinVobSubSub); DirectShowUtil.ReleaseComObject(pinSubTo); pinSubTo = null; DirectShowUtil.ReleaseComObject(pinVobSubSub); pinVobSubSub = null; } } // Now check if vobsub's video input is not connected. // Check only if vmr9 is connected (render was successful). VMR9Util Vmr9 = VMR9Util.g_vmr9; if (Vmr9.IsVMR9Connected) { Log.Debug("VideoPlayerVMR9: Connect VobSub's video pins"); IPin pinVobSubVideoIn = DsFindPin.ByDirection(vob, PinDirection.Input, 0); IPin pinVobSubVideoOut = DsFindPin.ByDirection(vob, PinDirection.Output, 0); // This is the pin that we will connect to vobsub's input. IPin pinVideoTo = Vmr9.PinConnectedTo; IPin pinVideoFrom = null; pinVideoTo.ConnectedTo(out pinVideoFrom); pinVideoTo.Disconnect(); pinVideoFrom.Disconnect(); //Now make connection to VobSub int hr = graphBuilder.Connect(pinVideoTo, pinVobSubVideoIn); //hr = graphBuilder.Render(pinVideoFrom); if (hr != 0) { Log.Error("VideoPlayerVMR9: could not connect Vobsub's input video pin"); return(null); } hr = graphBuilder.Connect(pinVobSubVideoOut, pinVideoFrom); //hr = graphBuilder.Render(pinVobSubVideoOut); if (hr != 0) { Log.Error("VideoPlayerVMR9: could not connect Vobsub's output video pin"); return(null); } Log.Debug("VideoPlayerVMR9: Vobsub's video pins connected"); DirectShowUtil.ReleaseComObject(pinVideoTo); pinVideoTo = null; DirectShowUtil.ReleaseComObject(pinVobSubVideoIn); pinVobSubVideoIn = null; DirectShowUtil.ReleaseComObject(pinVobSubVideoOut); pinVobSubVideoOut = null; DirectShowUtil.ReleaseComObject(pinVideoFrom); pinVideoFrom = null; } Vmr9 = null; return(vob); }