/// <summary> /// Adds a source filter to the graph and sets the input. /// </summary> protected virtual void AddSourceFilter() { int hr = 0; var networkResourceAccessor = _resourceAccessor as INetworkResourceAccessor; if (networkResourceAccessor != null) { ServiceRegistration.Get <ILogger>().Debug("{0}: Initializing for network media item '{1}'", PlayerTitle, networkResourceAccessor.URL); // try to render the url and let DirectShow choose the source filter hr = _graphBuilder.RenderFile(networkResourceAccessor.URL, null); new HRESULT(hr).Throw(); return; } var fileSystemResourceAccessor = _resourceAccessor as IFileSystemResourceAccessor; if (fileSystemResourceAccessor != null) { ServiceRegistration.Get <ILogger>().Debug("{0}: Initializing for file system media item '{1}'", PlayerTitle, fileSystemResourceAccessor.Path); // For locally accessible files prefer the default filters ILocalFsResourceAccessor lfsra = fileSystemResourceAccessor as ILocalFsResourceAccessor; if (lfsra != null) { // try to render the file and let DirectShow choose the source filter hr = _graphBuilder.RenderFile(lfsra.LocalFileSystemPath, null); new HRESULT(hr).Throw(); return; } // use the DotNetStreamSourceFilter as source filter _streamFilter = new DotNetStreamSourceFilter(); _resourceStream = fileSystemResourceAccessor.OpenRead(); _streamFilter.SetSourceStream(_resourceStream, fileSystemResourceAccessor.ResourcePathName); hr = _graphBuilder.AddFilter(_streamFilter, _streamFilter.Name); new HRESULT(hr).Throw(); using (DSFilter source2 = new DSFilter(_streamFilter)) hr = source2.OutputPin.Render(); new HRESULT(hr).Throw(); return; } throw new IllegalCallException("The VideoPlayer can only play resources of type INetworkResourceAccessor or IFileSystemResourceAccessor"); }
// Starts playing a new cinematic public void PlayCinematic(string file, int x, int y, int w, int h) { // Lame bugfix: DirectShow and Fullscreen doesnt like eachother if (CVars.Instance.Get("r_fs", "0", CVarFlags.ARCHIVE).Integer == 1) { if (AlterGameState) { playing = true; StopCinematic(); } return; } // Check if file exists if (FileCache.Instance.Contains(file)) file = FileCache.Instance.GetFile(file).FullName; else { if (AlterGameState) { playing = true; StopCinematic(); } Common.Instance.WriteLine("PlayCinematic: Could not find video: {0}", file); return; } // Have the graph builder construct its the appropriate graph automatically this.graphBuilder = (IGraphBuilder)new FilterGraph(); int hr = graphBuilder.RenderFile(file, null); DsError.ThrowExceptionForHR(hr); mediaControl = (IMediaControl)this.graphBuilder; mediaEventEx = (IMediaEventEx)this.graphBuilder; videoWindow = this.graphBuilder as IVideoWindow; basicVideo = this.graphBuilder as IBasicVideo; // Setup the video window hr = this.videoWindow.put_Owner(Renderer.Instance.form.Handle); DsError.ThrowExceptionForHR(hr); hr = this.videoWindow.put_WindowStyle(WindowStyle.Child | WindowStyle.ClipSiblings | WindowStyle.ClipChildren); DsError.ThrowExceptionForHR(hr); // Set the video size //int lWidth, lHeight; //hr = this.basicVideo.GetVideoSize(out lWidth, out lHeight); hr = this.videoWindow.SetWindowPosition(x, y, w, h); videoWindow.put_FullScreenMode((CVars.Instance.Get("r_fs", "0", CVarFlags.ARCHIVE).Integer == 1) ? OABool.True : OABool.False); DsError.ThrowExceptionForHR(hr); // Run the graph to play the media file hr = this.mediaControl.Run(); DsError.ThrowExceptionForHR(hr); playing = true; if (AlterGameState) Client.Instance.state = CubeHags.common.ConnectState.CINEMATIC; Common.Instance.WriteLine("Playing cinematic: {0}", file); EventCode code; }
/// <summary> /// Check whether DirectShow can render a video file /// </summary> /// <param name="fileName"></param> /// <returns>true if graphedit can render the input</returns> public bool checkRender(string fileName) { Type comtype = null; object comobj = null; try { comtype = Type.GetTypeFromCLSID(Clsid.FilterGraph); if (comtype == null) { throw new NotSupportedException("DirectX (8.1 or higher) not installed?"); } comobj = Activator.CreateInstance(comtype); graphBuilder = (IGraphBuilder)comobj; comobj = null; int hr = graphBuilder.RenderFile(fileName, null); if (hr >= 0) { return(true); } else { return(false); } } catch (Exception) { return(false); //throw (e); // May add more handling here later } }
/// <summary> /// Adds the file source filter to the graph. /// </summary> protected virtual void AddFileSource() { // Render the file int hr = _graphBuilder.RenderFile(SourcePathOrUrl, null); DsError.ThrowExceptionForHR(hr); }
/// <summary> /// Open the file in <see cref="FilePath"/> and load it. /// </summary> private void OpenMediaFile() { ClosePlayer(); int hr = 0; this.graphBuilder = (IGraphBuilder) new FilterGraph(); hr = graphBuilder.RenderFile(this.FilePath, null); DsError.ThrowExceptionForHR(hr); this.mediaControl = (IMediaControl)this.graphBuilder; this.mediaEventEx = (IMediaEventEx)this.graphBuilder; this.mediaSeeking = (IMediaSeeking)this.graphBuilder; this.mediaPosition = (IMediaPosition)this.graphBuilder; this.videoWindow = this.graphBuilder as IVideoWindow; this.basicVideo = this.graphBuilder as IBasicVideo; int x, y; this.basicVideo.GetVideoSize(out x, out y); this.VideoSize = new Size(x, y); this.basicAudio = (IBasicAudio)this.graphBuilder; hr = this.mediaEventEx.SetNotifyWindow(notifyTarget, WMGraphNotify, IntPtr.Zero); DsError.ThrowExceptionForHR(hr); hr = this.videoWindow.put_Owner(owner); DsError.ThrowExceptionForHR(hr); hr = this.videoWindow.put_WindowStyle(WindowStyle.Child | WindowStyle.ClipSiblings | WindowStyle.ClipChildren); DsError.ThrowExceptionForHR(hr); videoWindow.SetWindowPosition(0, 0, Control.FromHandle(this.owner).Width, Control.FromHandle(this.owner).Height); double time; mediaPosition.get_Duration(out time); this.Length = (int)(time * 1000); this.State = PlayState.Opened; }
public CAviDS(string filename, double playSpeed) { builder = new FilterGraph() as IGraphBuilder; grabber = new SampleGrabber() as ISampleGrabber; mediaType = new AMMediaType(); mediaType.majorType = MediaType.Video; mediaType.subType = MediaSubType.RGB32; mediaType.formatType = FormatType.VideoInfo; DsError.ThrowExceptionForHR(grabber.SetMediaType(mediaType)); DsError.ThrowExceptionForHR(builder.AddFilter(grabber as IBaseFilter, "Sample Grabber(DTXMania)")); DsError.ThrowExceptionForHR(builder.RenderFile(filename, null)); CDirectShow.ConnectNullRendererFromSampleGrabber(builder, grabber as IBaseFilter); if (builder is IVideoWindow videoWindow) { videoWindow.put_AutoShow(OABool.False); } DsError.ThrowExceptionForHR(grabber.GetConnectedMediaType(mediaType)); videoInfo = (VideoInfoHeader)Marshal.PtrToStructure(mediaType.formatPtr, typeof(VideoInfoHeader)); nWidth = videoInfo.BmiHeader.Width; nHeight = videoInfo.BmiHeader.Height; seeker = builder as IMediaSeeking; DsError.ThrowExceptionForHR(seeker.GetDuration(out nMediaLength)); DsError.ThrowExceptionForHR(seeker.SetRate(playSpeed / 20.0)); control = builder as IMediaControl; filter = builder as IMediaFilter; grabber.SetBufferSamples(BufferThem: true); Run(); Pause(); bPlaying = false; bPause = false; }
/// <summary> /// Creates a new Video Player. Automatically creates the required Texture2D on the specificied GraphicsDevice. /// </summary> /// <param name="FileName">The video file to open</param> /// <param name="graphicsDevice">XNA Graphics Device</param> public VideoPlayer(string FileName, GraphicsDevice graphicsDevice) { try { currentState = VideoState.Stopped; filename = FileName; InitInterfaces(); SampleGrabber sg = new SampleGrabber(); ISampleGrabber sampleGrabber = (ISampleGrabber)sg; DsError.ThrowExceptionForHR(gb.AddFilter((IBaseFilter)sg, "Grabber")); AMMediaType mt = new AMMediaType(); mt.majorType = MEDIATYPE_Video; // Video mt.subType = MEDIASUBTYPE_RGB24; // RGB24 mt.formatType = FORMAT_VideoInfo; // VideoInfo DsError.ThrowExceptionForHR(sampleGrabber.SetMediaType(mt)); DsError.ThrowExceptionForHR(gb.RenderFile(filename, null)); DsError.ThrowExceptionForHR(sampleGrabber.SetBufferSamples(true)); DsError.ThrowExceptionForHR(sampleGrabber.SetOneShot(false)); DsError.ThrowExceptionForHR(sampleGrabber.SetCallback((ISampleGrabberCB)this, 1)); IVideoWindow pVideoWindow = (IVideoWindow)gb; DsError.ThrowExceptionForHR(pVideoWindow.put_AutoShow(OABool.False)); AMMediaType MediaType = new AMMediaType(); DsError.ThrowExceptionForHR(sampleGrabber.GetConnectedMediaType(MediaType)); VideoInfoHeader pVideoHeader = new VideoInfoHeader(); Marshal.PtrToStructure(MediaType.formatPtr, pVideoHeader); videoHeight = pVideoHeader.BmiHeader.Height; videoWidth = pVideoHeader.BmiHeader.Width; avgTimePerFrame = pVideoHeader.AvgTimePerFrame; bitRate = pVideoHeader.BitRate; DsError.ThrowExceptionForHR(ms.GetDuration(out videoDuration)); videoFrameBytes = new byte[(videoHeight * videoWidth) * 4]; // RGBA format (4 bytes per pixel) bgrData = new byte[(videoHeight * videoWidth) * 3]; // BGR24 format (3 bytes per pixel) outputFrame = new Texture2D(graphicsDevice, videoWidth, videoHeight, 1, TextureUsage.None, SurfaceFormat.Color); } catch { throw new Exception("Unable to Load or Play the video file"); } }
protected override void DoLoad(string mediaSource) { builder = new FilterGraph() as IGraphBuilder; builder.RenderFile(mediaSource, null); controller = builder as IMediaControl; seeker = builder as IMediaPosition; }
/// <summary> /// Render a Media File /// </summary> /// <param name="filename"></param> /// <returns></returns> public int RenderMediaFile(string filename) { int hr = _graphBuilder.RenderFile(filename, string.Empty); dsDaggerUIGraph1.SyncGraphs(null); dsDaggerUIGraph1.ArrangeNodes(AutoArrangeStyle.All); return(hr); }
// //Method to start to play a media file // private void LoadFile(string fName) { try { //get the graph filter ready to render graphBuilder.RenderFile(fName, null); //set the trackbar OABool bCsf, bCsb; mediaPos.CanSeekBackward(out bCsb); mediaPos.CanSeekForward(out bCsf); isSeeking = (bCsb == OABool.True) && (bCsf == OABool.True); if (isSeeking) { trackBar1.Enabled = true; } else { trackBar1.Enabled = false; } trackBar1.Minimum = 0; double duration; mediaPos.get_Duration(out duration); trackBar1.Maximum = (int)(duration * 100.0); Text = fName; //check for the ability to step frameStep = graphBuilder as IVideoFrameStep; if (frameStep.CanStep(1, null) == 0) { canStep = true; buttonFramestep.Enabled = true; } //prepare and set the video window videoWin = graphBuilder as IVideoWindow; videoWin.put_Owner((IntPtr)panel1.Handle); videoWin.put_WindowStyle(WindowStyle.Child | WindowStyle.ClipSiblings | WindowStyle.ClipChildren); Rectangle rc = panel1.ClientRectangle; videoWin.SetWindowPosition(0, 0, rc.Right, rc.Bottom); mediaEvt.SetNotifyWindow((IntPtr)this.Handle, WM_GRAPHNOTIFY, (IntPtr)0); //set the different values for controls trackBar1.Value = 0; minutes = (int)duration / 60; seconds = (int)duration % 60; statusBar1.Panels[0].Text = "Duration: " + minutes.ToString("D2") + ":m" + seconds.ToString("D2") + ":s"; graphState = State.Playing; this.buttonPlay.Text = "Pause"; //start the playback mediaCtrl.Run(); } catch (Exception) { Text = "Error loading file"; } }
private void Config() { IBaseFilter pFilter; IGraphBuilder gb = (IGraphBuilder) new FilterGraph(); m_mc = (IMediaControl)gb; int hr = gb.RenderFile(@"foo.avi", null); hr = gb.FindFilterByName("Video Renderer", out pFilter); IPin iPin = DsFindPin.ByDirection(pFilter, PinDirection.Input, 0); m_pc = iPin as IPinConnection; }
private void CreateGraph() { graphBuilder = (IGraphBuilder) new FilterGraph(); graphBuilder.RenderFile(tempFileName, null); mediaControl = (IMediaControl)graphBuilder; mediaSeeking = (IMediaSeeking)graphBuilder; mediaEvent = (IMediaEventEx)graphBuilder; //var filter = new MpqFileSourceFilter(File); //DsError.ThrowExceptionForHR(graphBuilder.AddFilter(filter, filter.Name)); //DsError.ThrowExceptionForHR(graphBuilder.Render(filter.OutputPin)); mediaSeeking.GetCapabilities(out seekingCapabilities); mediaSeeking.SetTimeFormat(TimeFormat.MediaTime); mediaEvent.SetNotifyWindow(Handle, WM_GRAPHNOTIFY, IntPtr.Zero); }
private void Config() { IGraphBuilder gb = (IGraphBuilder) new FilterGraph(); IBaseFilter pFilter; int hr = gb.RenderFile(@"nwn.mp1", null); DsError.ThrowExceptionForHR(hr); hr = gb.FindFilterByName("MPEG-I Stream Splitter", out pFilter); DsError.ThrowExceptionForHR(hr); m_ss = pFilter as IAMStreamSelect; }
/// <summary>Do the conversion from DVR-MS to WAV.</summary> /// <returns>Null; ignored.</returns> protected override object DoWork() { // Get the filter graph object filterGraph = ClassId.CoCreateInstance(ClassId.FilterGraph); DisposalCleanup.Add(filterGraph); IGraphBuilder graph = (IGraphBuilder)filterGraph; // Add the ASF writer and set the output name IBaseFilter asfWriterFilter = (IBaseFilter)ClassId.CoCreateInstance(ClassId.WMAsfWriter); DisposalCleanup.Add(asfWriterFilter); graph.AddFilter(asfWriterFilter, null); IFileSinkFilter sinkFilter = (IFileSinkFilter)asfWriterFilter; sinkFilter.SetFileName(OutputFilePath, null); // Set the profile to be used for conversion if (_profilePath != null && _profilePath.Trim().Length > 0) { // Load the profile XML contents string profileData; using (StreamReader reader = new StreamReader(File.OpenRead(_profilePath))) { profileData = reader.ReadToEnd(); } // Create an appropriate IWMProfile from the data IWMProfileManager profileManager = ProfileManager.CreateInstance(); DisposalCleanup.Add(profileManager); IntPtr wmProfile = profileManager.LoadProfileByData(profileData); DisposalCleanup.Add(wmProfile); // Set the profile on the writer IConfigAsfWriter2 configWriter = (IConfigAsfWriter2)asfWriterFilter; configWriter.ConfigureFilterUsingProfile(wmProfile); } // Add the source filter; should connect automatically through the appropriate transform filters graph.RenderFile(InputFilePath, null); // Run the graph to completion RunGraph(graph, asfWriterFilter); return(null); }
/// <summary> create the used COM components and get the interfaces. </summary> private bool GetInterfaces() { int iStage = 1; string audioDevice; using (Settings xmlreader = new MPSettings()) { audioDevice = xmlreader.GetValueAsString("audioplayer", "sounddevice", "Default DirectSound Device"); } //Type comtype = null; //object comobj = null; try { graphBuilder = (IGraphBuilder) new FilterGraph(); iStage = 5; DirectShowUtil.AddAudioRendererToGraph(graphBuilder, audioDevice, false); int hr = graphBuilder.RenderFile(m_strCurrentFile, null); if (hr != 0) { Error.SetError("Unable to play file", "Missing codecs to play this file"); return(false); } iStage = 6; mediaCtrl = (IMediaControl)graphBuilder; iStage = 7; mediaEvt = (IMediaEventEx)graphBuilder; iStage = 8; mediaSeek = (IMediaSeeking)graphBuilder; iStage = 9; mediaPos = (IMediaPosition)graphBuilder; iStage = 10; basicAudio = graphBuilder as IBasicAudio; iStage = 11; return(true); } catch (Exception ex) { Log.Info("Can not start {0} stage:{1} err:{2} stack:{3}", m_strCurrentFile, iStage, ex.Message, ex.StackTrace); return(false); } }
private void StartGraph() { int hr = 0; CloseGraph(); string path = GetMoviePath(); if (path == string.Empty) { return; } try { graph = (IGraphBuilder) new FilterGraph(); filter = (IBaseFilter) new VideoMixingRenderer9(); IVMRFilterConfig9 filterConfig = (IVMRFilterConfig9)filter; hr = filterConfig.SetRenderingMode(VMR9Mode.Renderless); DsError.ThrowExceptionForHR(hr); hr = filterConfig.SetNumberOfStreams(2); DsError.ThrowExceptionForHR(hr); SetAllocatorPresenter(); hr = graph.AddFilter(filter, "Video Mixing Renderer 9"); DsError.ThrowExceptionForHR(hr); hr = graph.RenderFile(path, null); DsError.ThrowExceptionForHR(hr); mediaControl = (IMediaControl)graph; hr = mediaControl.Run(); DsError.ThrowExceptionForHR(hr); } catch { } }
private void playAudioToDevice(string fName, int devIndex) { object source = null; DsDevice[] devices; devices = DsDevice.GetDevicesOfCat(FilterCategory.AudioRendererCategory); DsDevice device = (DsDevice)devices[devIndex]; Guid iid = typeof(IBaseFilter).GUID; device.Mon.BindToObject(null, null, ref iid, out source); m_objFilterGraph = (IGraphBuilder) new FilterGraph(); m_objFilterGraph.AddFilter((IBaseFilter)source, "Audio Render"); m_objFilterGraph.RenderFile(fName, ""); m_objBasicAudio = m_objFilterGraph as IBasicAudio; m_objMediaControl = m_objFilterGraph as IMediaControl; m_objMediaControl.Run(); }
void RenderSomething(string filename, string errmsg) { try { log("graphBuilder.RenderFile " + filename); int hr = graphBuilder.RenderFile(filename, null); DsError.ThrowExceptionForHR(hr); log("RenderFile ok"); } catch (COMException e) { ShowCOMException(e, errmsg + filename); return; } catch (Exception e) { MessageBox.Show(e.Message, errmsg + filename); return; } ReloadGraph(); log("Rendering done."); }
private void open() { int hr; if (this.GraphBuilder == null) { this.GraphBuilder = (IGraphBuilder) new FilterGraph(); hr = GraphBuilder.RenderFile(file, null);//读取文件 DsError.ThrowExceptionForHR(hr); this.MediaControl = (IMediaControl)this.GraphBuilder; this.MediaEventEx = (IMediaEventEx)this.GraphBuilder; MediaSeeking = (IMediaSeeking)this.GraphBuilder; MediaSeeking.SetTimeFormat(TIME_FORMAT_FRAME); MediaSeeking.SetRate(0.3); this.VideoFrameStep = (IVideoFrameStep)this.GraphBuilder; // MediaPosition= (IMediaPosition)this.GraphBuilder; this.VideoWindow = this.GraphBuilder as IVideoWindow; this.BasicVideo = this.GraphBuilder as IBasicVideo; this.BasicAudio = this.GraphBuilder as IBasicAudio; hr = this.MediaEventEx.SetNotifyWindow(this.Handle, WM_GRAPHNOTIFY, IntPtr.Zero); DsError.ThrowExceptionForHR(hr); hr = this.VideoWindow.put_Owner(this.Handle); DsError.ThrowExceptionForHR(hr); hr = this.VideoWindow.put_WindowStyle(WindowStyle.Child | WindowStyle.ClipSiblings | WindowStyle.ClipChildren); DsError.ThrowExceptionForHR(hr); this.Focus(); hr = InitVideoWindow(1, 1); DsError.ThrowExceptionForHR(hr); long time; MediaSeeking.GetDuration(out time); label20.Text = time.ToString(); trackBar1.SetRange(0, (int)time); t = new Thread(new ThreadStart(updateTimeBarThread)); } }
public bool Open(PandoraSong file) { try { Close(); graphBuilder = (IGraphBuilder) new FilterGraph(); // create interface objects for various actions mediaControl = (IMediaControl)graphBuilder; mediaEventEx = (IMediaEventEx)graphBuilder; mediaSeeking = (IMediaSeeking)graphBuilder; mediaPosition = (IMediaPosition)graphBuilder; basicAudio = (IBasicAudio)graphBuilder; int hr = 0; StartEventLoop(); //hr = graphBuilder.AddFilter( // Have the graph builder construct its the appropriate graph automatically hr = graphBuilder.RenderFile(file.AudioURL, null); DsError.ThrowExceptionForHR(hr); // maintain previous volume level so it persists from track to track if (PreviousVolume != null) { Volume = (double)PreviousVolume; } loadedSong = file; return(true); } catch (Exception) { return(false); } }
private void CreateGraph() { graphBuilder = (IGraphBuilder)new FilterGraph(); graphBuilder.RenderFile(tempFileName, null); mediaControl = (IMediaControl)graphBuilder; mediaSeeking = (IMediaSeeking)graphBuilder; mediaEvent = (IMediaEventEx)graphBuilder; //var filter = new MpqFileSourceFilter(File); //DsError.ThrowExceptionForHR(graphBuilder.AddFilter(filter, filter.Name)); //DsError.ThrowExceptionForHR(graphBuilder.Render(filter.OutputPin)); mediaSeeking.GetCapabilities(out seekingCapabilities); mediaSeeking.SetTimeFormat(TimeFormat.MediaTime); mediaEvent.SetNotifyWindow(Handle, WM_GRAPHNOTIFY, IntPtr.Zero); }
DSStreamResultCodes InitWithVideoFile(WTVStreamingVideoRequest strq) { UsingSBEFilter = false; // Not using stream buffer // Init variables IPin[] pin = new IPin[1]; string dPin = string.Empty; string sName = string.Empty; string dName = string.Empty; string sPin = string.Empty; FileInfo fiInputFile = new FileInfo(strq.FileName); string txtOutputFNPath = fiInputFile.FullName + ".wmv"; if ( (fiInputFile.Extension.ToLowerInvariant().Equals(".wtv")) || (fiInputFile.Extension.ToLowerInvariant().Equals(".dvr-ms")) ) { return(DSStreamResultCodes.ErrorInvalidFileType); } int hr = 0; try { // Get the graphbuilder interface SendDebugMessage("Creating Graph Object", 0); IGraphBuilder graphbuilder = (IGraphBuilder)currentFilterGraph; // Create an ASF writer filter SendDebugMessage("Creating ASF Writer", 0); WMAsfWriter asf_filter = new WMAsfWriter(); dc.Add(asf_filter); // CHECK FOR ERRORS currentOutputFilter = (IBaseFilter)asf_filter; // class variable // Add the ASF filter to the graph hr = graphbuilder.AddFilter((IBaseFilter)asf_filter, "WM Asf Writer"); DsError.ThrowExceptionForHR(hr); // Set the filename SendDebugMessage("Setting filename", 0); IFileSinkFilter sinkFilter = (IFileSinkFilter)asf_filter; string destPathFN = fiInputFile.FullName + ".wmv"; hr = sinkFilter.SetFileName(destPathFN, null); DsError.ThrowExceptionForHR(hr); // Handy to have an ACM Wrapper filter hanging around for AVI files with MP3 audio SendDebugMessage("Adding ACM Wrapper", 0); IBaseFilter ACMFilter = FilterDefinition.AddToFilterGraph(FilterDefinitions.Other.ACMWrapperFilter, ref graphbuilder); dc.Add(ACMFilter); // Render file - then build graph SendDebugMessage("Rendering file", 0); graphbuilder.RenderFile(fiInputFile.FullName, null); SendDebugMessage("Saving graph", 0); FilterGraphTools.SaveGraphFile(graphbuilder, "C:\\ProgramData\\RemotePotato\\lastfiltergraph.grf"); // Are both our ASF pins connected? IPin ASFVidInputPin = FilterGraphTools.FindPinByMediaType((IBaseFilter)asf_filter, PinDirection.Input, MediaType.Video, MediaSubType.Null); IPin ASFAudInputPin = FilterGraphTools.FindPinByMediaType((IBaseFilter)asf_filter, PinDirection.Input, MediaType.Audio, MediaSubType.Null); // Run graph [can use this also to get media type => see, e.g. dvrmstowmvhd by Babgvant] SendDebugMessage("Run graph for testing purposes", 0); IMediaControl tempControl = (IMediaControl)graphbuilder; IMediaEvent tempEvent = (IMediaEvent)graphbuilder; DsError.ThrowExceptionForHR(tempControl.Pause()); EventCode pEventCode; hr = tempEvent.WaitForCompletion(1000, out pEventCode); // Get media type from vid input pin for ASF writer AMMediaType pmt = new AMMediaType(); hr = ASFVidInputPin.ConnectionMediaType(pmt); FrameSize SourceFrameSize = null; if (pmt.formatType == FormatType.VideoInfo2) { // Now graph has been run and stopped we can get the video width and height from the output pin of the main video decoder VideoInfoHeader2 pvih2 = new VideoInfoHeader2(); Marshal.PtrToStructure(pmt.formatPtr, pvih2); SourceFrameSize = new FrameSize(pvih2.BmiHeader.Width, pvih2.BmiHeader.Height); } else if (pmt.formatType == FormatType.VideoInfo) //{05589f80-c356-11ce-bf01-00aa0055595a} { VideoInfoHeader pvih = new VideoInfoHeader(); Marshal.PtrToStructure(pmt.formatPtr, pvih); SourceFrameSize = new FrameSize(pvih.BmiHeader.Width, pvih.BmiHeader.Height); } else { SourceFrameSize = new FrameSize(200, 200); // SQUARE } // Stop graph if necessary FilterState pFS; hr = tempControl.GetState(1000, out pFS); if (pFS != FilterState.Stopped) { DsError.ThrowExceptionForHR(tempControl.Stop()); } // Free up media type DsUtils.FreeAMMediaType(pmt); pmt = null; // (re)Configure the ASF writer with the selected WM Profile ConfigureASFWriter(asf_filter, strq, SourceFrameSize); // Release pins SendDebugMessage("Releasing COM objects (pins)", 0); // source Marshal.ReleaseComObject(ASFVidInputPin); ASFVidInputPin = null; Marshal.ReleaseComObject(ASFAudInputPin); ASFAudInputPin = null; } catch (Exception ex) { SendDebugMessageWithException(ex.Message, ex); return(DSStreamResultCodes.ErrorExceptionOccurred); } return(DSStreamResultCodes.OK); }
public void StartDisplay(Panel panel, IntPtr notifyWindow, DisplaySource dispSource, string filename) { int hr = 0; displaySource = dispSource; if (dispSource == DisplaySource.Clip) { if (filename == String.Empty) { return; } } try { graphBuilder = (IGraphBuilder) new FilterGraph(); // QueryInterface for DirectShow interfaces mediaControl = (IMediaControl)graphBuilder; mediaEventEx = (IMediaEventEx)graphBuilder; mediaSeeking = (IMediaSeeking)graphBuilder; mediaPosition = (IMediaPosition)graphBuilder; // Query for video interfaces, which may not be relevant for audio files videoWindow = graphBuilder as IVideoWindow; basicVideo = graphBuilder as IBasicVideo; // Query for audio interfaces, which may not be relevant for video-only files basicAudio = graphBuilder as IBasicAudio; if (displaySource == DisplaySource.Stream) { /// Find source filter /// string possibleTvTunerName = "Video Capture"; DsDevice[] vidInputDevices = GetVideoInputDevices(); for (int i = 0; i < vidInputDevices.Length; i++) { DsDevice possibleTvTuner = vidInputDevices[i]; // use first device if none defined if (videoInputDevicePath == "") { videoInputDevicePath = possibleTvTuner.DevicePath; } if (possibleTvTuner.DevicePath != videoInputDevicePath) { continue; } try { if (sourceFilter != null) { Marshal.ReleaseComObject(sourceFilter); sourceFilter = null; } //Create the filter for the selected video input device sourceFilter = CreateFilterFromPath(FilterCategory.VideoInputDevice, possibleTvTuner.DevicePath); possibleTvTunerName = possibleTvTuner.Name; videoInputDeviceName = possibleTvTuner.Name; if (sourceFilter == null) { return; } } catch (Exception ex) { MessageBox.Show(ex.ToString()); //System.Diagnostics.Debug.WriteLine(ex.ToString()); } } /////////////////////////////////////////////////////////////////////////////////////////// captureGraphBuilder = (ICaptureGraphBuilder2) new CaptureGraphBuilder2(); // Attach the filter graph to the capture graph hr = captureGraphBuilder.SetFiltergraph(graphBuilder); DsError.ThrowExceptionForHR(hr); // Add Capture filter to our graph. hr = graphBuilder.AddFilter(sourceFilter, possibleTvTunerName /*"Video Capture"*/); DsError.ThrowExceptionForHR(hr); //// Init tuner/crossbar ////////////////////////////////////////////////////////////////// object o; tuner = null; crossbar = null; hr = captureGraphBuilder.FindInterface(FindDirection.UpstreamOnly, null, sourceFilter, typeof(IAMTVTuner).GUID, out o); //DsError.ThrowExceptionForHR(hr); if (hr >= 0) { tuner = (IAMTVTuner)o; o = null; hr = captureGraphBuilder.FindInterface(null, null, sourceFilter, typeof(IAMCrossbar).GUID, out o); DsError.ThrowExceptionForHR(hr); if (hr >= 0) { crossbar = (IAMCrossbar)o; //crossbar = (IBaseFilter)o; o = null; } usingCrossBar = true; } else { usingCrossBar = false; } /////////////////////////////////////////////////////////////////////////////////////////// // Render the preview pin on the video capture filter // Use this instead of this.graphBuilder.RenderFile hr = captureGraphBuilder.RenderStream(PinCategory.Preview, DirectShowLib.MediaType.Video, sourceFilter, null, null); DsError.ThrowExceptionForHR(hr); // If we are using tv tuner, force audio on..and set device input from tuner if (tuner != null) { if (videoInputDeviceSource == PhysicalConnectorType.Video_Tuner) { ChangeVideoInputSource(PhysicalConnectorType.Video_Tuner); ChangeAudioInputSource(PhysicalConnectorType.Audio_Tuner); } } // Now that the filter has been added to the graph and we have // rendered its stream, we can release this reference to the filter. // temp //Marshal.ReleaseComObject(sourceFilter); isAudioOnly = false; } else { // Have the graph builder construct its the appropriate graph automatically hr = graphBuilder.RenderFile(filename, null); DsError.ThrowExceptionForHR(hr); // Is this an audio-only file (no video component)? CheckVisibility(); } if (!isAudioOnly) { RenderToPanel(panel, notifyWindow); GetFrameStepInterface(); } else { /// Initialize the default player size and enable playback menu items /// <jefri> hr = InitPlayerWindow(); /// <jefri> DsError.ThrowExceptionForHR(hr); /// <jefri> EnablePlaybackMenu(true, MediaType.Audio); } currentPlaybackRate = 1.0; #if DEBUG rot = new DsROTEntry(this.graphBuilder); #endif // Run the graph to play the media hr = mediaControl.Run(); DsError.ThrowExceptionForHR(hr); currentState = PlayState.Running; // Every call to this method,volume level will be 0, // so inform client to adjust volume level // Raise event, so our client can take action for it if (PlayerStarted != null) { PlayerStarted(new EventArgs()); } } catch (COMException ce) { NotifyEventArgs args = new NotifyEventArgs(); args.Summary = "DirectShow Exception"; args.Source = ce.Source; args.Message = ce.Message; args.Exception = ce; OnNotifyError(args); } catch { NotifyEventArgs args = new NotifyEventArgs(); args.Summary = "DirectShow Exception"; args.Source = ""; args.Message = "An unrecoverable error has occurred."; args.Exception = null; OnNotifyError(args); } }
public bool Open(PandoraSong file) { try { Close(); graphBuilder = (IGraphBuilder)new FilterGraph(); // create interface objects for various actions mediaControl = (IMediaControl)graphBuilder; mediaEventEx = (IMediaEventEx)graphBuilder; mediaSeeking = (IMediaSeeking)graphBuilder; mediaPosition = (IMediaPosition)graphBuilder; basicAudio = (IBasicAudio)graphBuilder; int hr = 0; StartEventLoop(); //hr = graphBuilder.AddFilter( // Have the graph builder construct its the appropriate graph automatically hr = graphBuilder.RenderFile(file.AudioURL, null); DsError.ThrowExceptionForHR(hr); // maintain previous volume level so it persists from track to track if (PreviousVolume != null) Volume = (double)PreviousVolume; loadedSong = file; return true; } catch (Exception) { return false; } }
public void openVid(string fileName) { if (!File.Exists(fileName)) { errorMsg("El archivo '" + fileName + "' no existe."); videoPanel.Visible = false; isVideoLoaded = false; drawPositions(); return; } if (VideoBoxType == PreviewType.AviSynth) { avsClip = null; //butPause.Enabled = true; //butPlayR.Enabled = true; //butPlay.Enabled = true; //butStop.Enabled = true; videoPictureBox.Visible = false; //closeVidDShow(); // añadido } if (mediaControl != null) { mediaControl.Stop(); videoWindow.put_Visible(DirectShowLib.OABool.False); videoWindow.put_Owner(IntPtr.Zero); } // Dshow :~~ graphBuilder = (IGraphBuilder)new FilterGraph(); graphBuilder.RenderFile(fileName, null); mediaControl = (IMediaControl)graphBuilder; // mediaEventEx = (IMediaEventEx)this.graphBuilder; mediaSeeking = (IMediaSeeking)graphBuilder; mediaPosition = (IMediaPosition)graphBuilder; basicVideo = graphBuilder as IBasicVideo; videoWindow = graphBuilder as IVideoWindow; VideoBoxType = PreviewType.DirectShow; // sacando información int x, y; double atpf; basicVideo.GetVideoSize(out x, out y); if (x == 0 || y == 0) { errorMsg("No se puede abrir un vídeo sin dimensiones."); videoPanel.Visible = false; isVideoLoaded = false; drawPositions(); return; } if (videoInfo == null) videoInfo = new VideoInfo(fileName); videoInfo.Resolution = new Size(x, y); basicVideo.get_AvgTimePerFrame(out atpf); videoInfo.FrameRate = Math.Round(1 / atpf, 3); //labelResFPS.Text = x.ToString() + "x" + y.ToString() + " @ " + videoInfo.FrameRate.ToString() + " fps"; textResX.Text = x.ToString(); textResY.Text = y.ToString(); textFPS.Text = videoInfo.FrameRate.ToString(); if (File.Exists(Application.StartupPath+"\\MediaInfo.dll") && File.Exists(Application.StartupPath+"\\MediaInfoWrapper.dll")) { treeView1.Enabled = true; try { RetrieveMediaFileInfo(fileName); } catch { treeView1.Enabled = false; } } else treeView1.Enabled = false; if (x != 0) { vidScaleFactor.Enabled = true; try { vidScaleFactor.Text = getFromConfigFile("mainW_Zoom"); } catch { vidScaleFactor.Text = "50%"; }; double p = double.Parse(vidScaleFactor.Text.Substring(0, vidScaleFactor.Text.IndexOf('%'))); p = p / 100; int new_x = (int)(x * p); int new_y = (int)(y * p); videoWindow.put_Height(new_x); videoWindow.put_Width(new_y); videoWindow.put_Owner(videoPanel.Handle); videoPanel.Size = new System.Drawing.Size(new_x, new_y); videoWindow.SetWindowPosition(0, 0, videoPanel.Width, videoPanel.Height); videoWindow.put_WindowStyle(WindowStyle.Child); videoWindow.put_Visible(DirectShowLib.OABool.True); } else vidScaleFactor.Enabled = false; // timer actualizaFrames.Interval = 10; actualizaFrames.Enabled = true; //mediaControl.Run(); drawPositions(); framesFin.Enabled = true; buttonAddFrameInicio.Enabled = buttonAddFrameInicio.Visible = true; framesInicio.Enabled = true; buttonAddFrameFin.Enabled = buttonAddFrameFin.Visible = true; butClip.Enabled = false; mediaSeeking.SetTimeFormat(DirectShowLib.TimeFormat.Frame); videoInfo.FrameTotal = VideoUnitConversion.getTotal(mediaSeeking, videoInfo.FrameRate); seekBar.Maximum = FrameTotal; seekBar.TickFrequency = seekBar.Maximum / 10; // VFW ( __ SOLO AVIs __ ) try { AVIFileWrapper.AVIFileInit(); int aviFile = 0; IntPtr aviStream; int res = AVIFileWrapper.AVIFileOpen(ref aviFile, fileName, 0x20, 0); res = AVIFileWrapper.AVIFileGetStream(aviFile, out aviStream, 1935960438, 0); videoInfo.KeyFrames = new ArrayList(); int nFrames = FrameTotal; for (int i = 0; i < nFrames; i++) { if (isKeyFrame(aviStream.ToInt32(), i)) videoInfo.KeyFrames.Add(i); } setStatus(videoInfo.KeyFrames.Count + " detectados"); AVIFileWrapper.AVIStreamRelease(aviStream); AVIFileWrapper.AVIFileRelease(aviFile); AVIFileWrapper.AVIFileExit(); KeyframesAvailable = true; /* nextK.Enabled = true; prevK.Enabled = true; drawKeyFrameBox(); */ } catch { /* nextK.Enabled = false; prevK.Enabled = false; keyFrameBox.Visible = false; */ KeyframesAvailable = false; } if (openFile != null && al.Count > 1 && gridASS.RowCount>0) { gridASS.Rows[1].Selected = true; gridASS.Rows[0].Selected = true; gridASS.Rows[1].Selected = false; } frameTime = new Hashtable(); for (int i = 0; i < FrameTotal; i++) frameTime.Add(i, new Tiempo((double)((double)i / videoInfo.FrameRate))); isVideoLoaded = true; updateMenuEnables(); mediaControl.Pause(); setStatus("Vídeo " + fileName + " cargado. [DirectShow]"); script.GetHeader().SetHeaderValue("Video File", fileName); if (isKeyframeGuessNeeded()) KeyframeGuess(false); //FrameIndex = 0; }
private void StartGraph() { int hr = 0; CloseGraph(); string path = GetMoviePath(); if (path == string.Empty) return; try { graph = (IGraphBuilder) new FilterGraph(); filter = (IBaseFilter) new VideoMixingRenderer9(); IVMRFilterConfig9 filterConfig = (IVMRFilterConfig9) filter; hr = filterConfig.SetRenderingMode(VMR9Mode.Renderless); DsError.ThrowExceptionForHR(hr); hr = filterConfig.SetNumberOfStreams(2); DsError.ThrowExceptionForHR(hr); SetAllocatorPresenter(); hr = graph.AddFilter(filter, "Video Mixing Renderer 9"); DsError.ThrowExceptionForHR(hr); hr = graph.RenderFile(path, null); DsError.ThrowExceptionForHR(hr); mediaControl = (IMediaControl) graph; hr = mediaControl.Run(); DsError.ThrowExceptionForHR(hr); } catch { } }
/// <summary> /// Create a new graph. /// </summary> private void CreateGraph() { try { _currentVolume = VolumeFull; int hr = 0; if (String.IsNullOrEmpty(_filename)) { return; } _graphBuilder = (IGraphBuilder) new FilterGraph(); // Have the graph builder construct its the appropriate graph automatically hr = _graphBuilder.RenderFile(_filename, null); DsError.ThrowExceptionForHR(hr); // QueryInterface for DirectShow interfaces _mediaControl = (IMediaControl)_graphBuilder; _mediaEventEx = (IMediaEventEx)_graphBuilder; _mediaSeeking = (IMediaSeeking)_graphBuilder; _mediaPosition = (IMediaPosition)_graphBuilder; // Query for video interfaces, which may not be relevant for audio files _videoWindow = _graphBuilder as IVideoWindow; _basicVideo = _graphBuilder as IBasicVideo; // Query for audio interfaces, which may not be relevant for video-only files _basicAudio = _graphBuilder as IBasicAudio; // Is this an audio-only file (no video component)? CheckVisibility(); // Have the graph signal event via window callbacks for performance hr = _mediaEventEx.SetNotifyWindow(_playWindow.Handle, WMGraphNotify, IntPtr.Zero); DsError.ThrowExceptionForHR(hr); if (!_isAudioOnly) { // Setup the video window hr = _videoWindow.put_Owner(_playWindow.Handle); DsError.ThrowExceptionForHR(hr); hr = _videoWindow.put_WindowStyle(WindowStyle.Child | WindowStyle.ClipSiblings | WindowStyle.ClipChildren); DsError.ThrowExceptionForHR(hr); hr = InitVideoWindow(1, 1); DsError.ThrowExceptionForHR(hr); // Position video window in client rect of owner window _playWindow.Resize += new EventHandler(onPlayerWindowResize); onPlayerWindowResize(this, null); GetFrameStepInterface(); } // Complete window initialization _isFullScreen = false; _currentPlaybackRate = 1.0; _currentState = PlayState.Stopped; } catch (Exception) { Close(); throw; } }
private void loadVideo(String videoPath) { videoFilepath = videoPath; videoFileName.Text = getDisplayVideoName(); if (graph != null) { graph = null; } if (mediaControl != null) { // Stop media playback this.mediaControl.Stop(); mediaControl = null; } if (videoWindow != null) { videoWindow.put_Owner(IntPtr.Zero); videoWindow = null; } if (mediaSeeking != null) { mediaSeeking = null; } if (basicAudio != null) { basicAudio = null; } GC.Collect(); /* if (mediaPosition != null) { mediaPosition = null; }*/ graph = (IGraphBuilder)new FilterGraph(); mediaControl = (IMediaControl)graph; //mediaPosition = (IMediaPosition)graph; videoWindow = (IVideoWindow)graph; mediaSeeking = (IMediaSeeking)graph; basicAudio = (IBasicAudio)graph; AviSplitter spliter = new AviSplitter(); graph.AddFilter((IBaseFilter)spliter, null); graph.RenderFile(videoPath, null); graph.SetDefaultSyncSource(); /* * AMSeekingSeekingCapabilities cap = AMSeekingSeekingCapabilities.CanGetCurrentPos; if (mediaSeeking.CheckCapabilities(ref cap) > 0) { this.consoleErreur.AppendText("Impossible de recuperer la position de la frame"); } * */ videoWindow.put_Owner(videoPanel.Handle); videoWindow.put_MessageDrain(videoPanel.Handle); videoWindow.put_WindowStyle(WindowStyle.Child); videoWindow.put_WindowStyleEx(WindowStyleEx.ControlParent); videoWindow.put_Left(0); videoWindow.put_Top(0); videoWindow.put_Width(videoPanel.Width); videoWindow.put_Height(videoPanel.Height); //positionTrackbar.Enabled = true; speedTrackBar.Enabled = true; mediaSeeking.SetTimeFormat(TimeFormat.Frame); double rate; mediaSeeking.GetRate(out rate); rateText.Text = rate.ToString(); speedTrackBar.Value = (int)(speedTrackBar.Maximum * rate / 2); trackBar1.Value = trackBar1.Maximum / 2; this.basicAudio.put_Volume(-5000 + 5000 * trackBar1.Value / trackBar1.Maximum); //mediaPosition.put_Rate(0.5); running = false; frameChanged = false; }
void Play(String fileName) { try { graphBuilder = (IGraphBuilder)new FilterGraph(); mediaCtrl = (IMediaControl)graphBuilder; mediaEvt = (IMediaEventEx)graphBuilder; mediaPos = (IMediaPosition)graphBuilder; videoWin = (IVideoWindow)graphBuilder; pane.getInfo(InfoQueue, fileName); graphBuilder.RenderFile( fileName, null ); videoWin.put_Owner(Video_panel.Handle); //videoWin.put_Owner(this.Handle); videoWin.put_WindowStyle(WindowStyle.Child | WindowStyle.ClipChildren); setWindow(); mediaCtrl.Run(); double total_time; mediaPos.get_Duration(out total_time); Video_timer.Enabled = true; iStatus = InfoStatus.Play; message_label.Width = 0; message_label.Height = 0; } catch (Exception) { MessageBox.Show("Couldn't start"); } }
/// <summary> create the used COM components and get the interfaces. </summary> private bool GetInterfaces() { int iStage = 1; string audioDevice; using (Settings xmlreader = new MPSettings()) { audioDevice = xmlreader.GetValueAsString("audioplayer", "sounddevice", "Default DirectSound Device"); } //Type comtype = null; //object comobj = null; try { graphBuilder = (IGraphBuilder)new FilterGraph(); iStage = 5; DirectShowUtil.AddAudioRendererToGraph(graphBuilder, audioDevice, false); int hr = graphBuilder.RenderFile(m_strCurrentFile, null); if (hr != 0) { Error.SetError("Unable to play file", "Missing codecs to play this file"); return false; } iStage = 6; mediaCtrl = (IMediaControl)graphBuilder; iStage = 7; mediaEvt = (IMediaEventEx)graphBuilder; iStage = 8; mediaSeek = (IMediaSeeking)graphBuilder; iStage = 9; mediaPos = (IMediaPosition)graphBuilder; iStage = 10; basicAudio = graphBuilder as IBasicAudio; iStage = 11; return true; } catch (Exception ex) { Log.Info("Can not start {0} stage:{1} err:{2} stack:{3}", m_strCurrentFile, iStage, ex.Message, ex.StackTrace); return false; } }
public static void GetAppVersions(string encPath = "", string javaPath = "") { if (String.IsNullOrEmpty(encPath)) { encPath = AppSettings.ToolsPath; } if (String.IsNullOrEmpty(javaPath)) { javaPath = AppSettings.JavaInstallPath; } X264 x264Enc = new X264(); AppSettings.Lastx264Ver = x264Enc.GetVersionInfo(encPath, false); if (Environment.Is64BitOperatingSystem) { AppSettings.Lastx26464Ver = x264Enc.GetVersionInfo(encPath, true); } FfMpeg ffmpeg = new FfMpeg(); AppSettings.LastffmpegVer = ffmpeg.GetVersionInfo(encPath, false); if (Environment.Is64BitOperatingSystem) { AppSettings.Lastffmpeg64Ver = ffmpeg.GetVersionInfo(encPath, true); } Eac3To eac3To = new Eac3To(); AppSettings.Lasteac3ToVer = eac3To.GetVersionInfo(encPath); LsDvd lsdvd = new LsDvd(); AppSettings.LastlsdvdVer = lsdvd.GetVersionInfo(encPath); MkvMerge mkvMerge = new MkvMerge(); AppSettings.LastMKVMergeVer = mkvMerge.GetVersionInfo(encPath); MPlayer mplayer = new MPlayer(); AppSettings.LastMplayerVer = mplayer.GetVersionInfo(encPath); TsMuxeR tsmuxer = new TsMuxeR(); AppSettings.LastTSMuxerVer = tsmuxer.GetVersionInfo(encPath); MJpeg mjpeg = new MJpeg(); AppSettings.LastMJPEGToolsVer = mjpeg.GetVersionInfo(encPath); DvdAuthor dvdauthor = new DvdAuthor(); AppSettings.LastDVDAuthorVer = dvdauthor.GetVersionInfo(encPath); MP4Box mp4Box = new MP4Box(); AppSettings.LastMp4BoxVer = mp4Box.GetVersionInfo(encPath); HcEnc hcenc = new HcEnc(); AppSettings.LastHcEncVer = hcenc.GetVersionInfo(encPath); OggEnc ogg = new OggEnc(); AppSettings.LastOggEncVer = ogg.GetVersionInfo(encPath, false); if (AppSettings.UseOptimizedEncoders) { AppSettings.LastOggEncLancerVer = ogg.GetVersionInfo(encPath, true); } NeroAACEnc aac = new NeroAACEnc(); AppSettings.LastNeroAacEncVer = aac.GetVersionInfo(encPath); Lame lame = new Lame(); AppSettings.LastLameVer = lame.GetVersionInfo(encPath); VpxEnc vpxEnc = new VpxEnc(); AppSettings.LastVpxEncVer = vpxEnc.GetVersionInfo(encPath); XvidEnc xvidEnc = new XvidEnc(); string myVer = xvidEnc.GetVersionInfo(encPath); if (!String.IsNullOrEmpty(javaPath)) { BdSup2SubTool bdSup2Sub = new BdSup2SubTool(); AppSettings.LastBDSup2SubVer = bdSup2Sub.GetVersionInfo(encPath, javaPath); } #region Get AviSynth Version IGraphBuilder graphBuilder = (IGraphBuilder) new FilterGraph(); string avsFile = AviSynthGenerator.GenerateTestFile(); int result = graphBuilder.RenderFile(avsFile, null); Log.DebugFormat("RenderFile Result: {0}", result); if (result < 0) { Log.Debug("AviSynth is not installed"); } else { FileVersionInfo ver = FileVersionInfo.GetVersionInfo(Path.Combine(Environment.SystemDirectory, "avisynth.dll")); string appVer = String.Format("{0:g}.{1:g}.{2:g}.{3:g}", ver.FileMajorPart, ver.FileMinorPart, ver.FileBuildPart, ver.FilePrivatePart); Log.DebugFormat("Avisynth version {0:s} installed", appVer); AppSettings.LastAviSynthVer = appVer; } File.Delete(avsFile); #endregion GetAviSynthPluginsVer(); GetUpdaterVersion(); AppSettings.UpdateVersions = false; AppSettings.SaveSettings(); }
public CAviDS(string filename, double playSpeed) { int hr = 0x0; builder = (IGraphBuilder) new FilterGraph(); #region [Sample Grabber] { grabber = new SampleGrabber() as ISampleGrabber; mediaType = new AMMediaType(); mediaType.majorType = MediaType.Video; mediaType.subType = MediaSubType.RGB32; mediaType.formatType = FormatType.VideoInfo; hr = grabber.SetMediaType(mediaType); DsError.ThrowExceptionForHR(hr); hr = builder.AddFilter((IBaseFilter)grabber, "Sample Grabber"); DsError.ThrowExceptionForHR(hr); } #endregion hr = builder.RenderFile(filename, null); DsError.ThrowExceptionForHR(hr); // Null レンダラに接続しないとウィンドウが表示される。 // また、レンダリングを行わないため処理速度を向上できる。 CDirectShow.ConnectNullRendererFromSampleGrabber(builder, grabber as IBaseFilter); CDirectShow.tグラフを解析しデバッグ出力する(builder); IVideoWindow videoWindow = builder as IVideoWindow; if (videoWindow != null) { videoWindow.put_AutoShow(OABool.False); } #region [Video Info] { hr = grabber.GetConnectedMediaType(mediaType); DsError.ThrowExceptionForHR(hr); videoInfo = (VideoInfoHeader)Marshal.PtrToStructure(mediaType.formatPtr, typeof(VideoInfoHeader)); nWidth = videoInfo.BmiHeader.Width; nHeight = videoInfo.BmiHeader.Height; } #endregion #region [ Seeker ] { seeker = builder as IMediaSeeking; hr = seeker.GetDuration(out nMediaLength); DsError.ThrowExceptionForHR(hr); hr = seeker.SetRate(playSpeed / 20); DsError.ThrowExceptionForHR(hr); } #endregion #region [Control] { control = builder as IMediaControl; } #endregion #region [Filter] { filter = builder as IMediaFilter; } #endregion grabber.SetBufferSamples(true); this.Run(); this.Pause(); bPlaying = false; bPause = false; // 外見えには演奏停止している。PAUSE中として外に見せないこと。 }
/// <summary> /// Check whether DirectShow can render a video file /// </summary> /// <param name="fileName"></param> /// <returns>true if graphedit can render the input</returns> public bool checkRender(string fileName) { Type comtype = null; object comobj = null; try { comtype = Type.GetTypeFromCLSID(Clsid.FilterGraph); if (comtype == null) throw new NotSupportedException("DirectX (8.1 or higher) not installed?"); comobj = Activator.CreateInstance(comtype); graphBuilder = (IGraphBuilder)comobj; comobj = null; int hr = graphBuilder.RenderFile(fileName, null); if (hr >= 0) return true; else return false; } catch (Exception) { return false; //throw (e); // May add more handling here later } }
protected override void SetAudioTrack_Call(AudioTrack value) { int hr = 0; if (!value.isExternal) { isExternalAudio = false; IAMStreamSelect stream; IBaseFilter filter; filter = GetFilter(graphBuilder,".mkv"); stream = (IAMStreamSelect)filter; int current = value.Number; hr = stream.Enable(current, AMStreamSelectEnableFlags.Enable); DsError.ThrowExceptionForHR(hr); //Debug.WriteLine("Using subtitles : " +current); } else { isExternalAudio = true; if (graphBuilderExtAudio != null) Marshal.ReleaseComObject(graphBuilderExtAudio); graphBuilderExtAudio = (IGraphBuilder) new FilterGraph(); mediaPositionExtAudio = graphBuilderExtAudio as IMediaPosition; mediaControlExtAudio = graphBuilderExtAudio as IMediaControl; basicAudioExtAudio = graphBuilderExtAudio as IBasicAudio; string pathtofile = Path.Combine(FileService.GetPathToLearningItem(value.LearningItem),value.ExternalFile); // Have the graph builder construct its the appropriate graph automatically try { hr = graphBuilderExtAudio.RenderFile(pathtofile, null); DsError.ThrowExceptionForHR(hr); } catch(Exception ex) { SystemMessage.Show( Loc.T("Player.Message.CantOpenExternalAudioFile") + Environment.NewLine + pathtofile + Environment.NewLine + Environment.NewLine + "Exeption details :" + Environment.NewLine + ex.Message + Environment.NewLine + ex.Source ); return; } #if DEBUG rot = new DsROTEntry(graphBuilderExtAudio); #endif // Run the graph to play the media file hr = mediaControlExtAudio.Run(); DsError.ThrowExceptionForHR(hr); SyncronizeVideoAndAudio(); } }
protected override void Open_Call(string filename) { int hr = 0; graphBuilder = (IGraphBuilder) new FilterGraph(); // Have the graph builder construct its the appropriate graph automatically hr = graphBuilder.RenderFile(filename, null); DsError.ThrowExceptionForHR(hr); /* try { hr = graphBuilder.RenderFile(filename, null); DsError.ThrowExceptionForHR(hr); } catch(Exception ex) { SystemMessage.Show( Loc.T("Player.Message.CantOpenVideoFile") + Environment.NewLine+ Environment.NewLine + "Exeption details :" + Environment.NewLine + ex.Message + Environment.NewLine + ex.Source ); return; } */ // QueryInterface for DirectShow interfaces mediaControl = (IMediaControl) graphBuilder; mediaEventEx = (IMediaEventEx) graphBuilder; //mediaSeeking = (IMediaSeeking) graphBuilder; mediaPosition = (IMediaPosition) graphBuilder; // Query for video interfaces, which may not be relevant for audio files videoWindow = graphBuilder as IVideoWindow; basicVideo = graphBuilder as IBasicVideo; // Query for audio interfaces, which may not be relevant for video-only files basicAudio = graphBuilder as IBasicAudio; // Have the graph signal event via window callbacks for performance hr = mediaEventEx.SetNotifyWindow(Handle, WMGraphNotify, IntPtr.Zero); DsError.ThrowExceptionForHR(hr); // Setup the video window hr = this.videoWindow.put_Owner(Handle); DsError.ThrowExceptionForHR(hr); hr = this.videoWindow.put_WindowStyle(DirectShowLib.WindowStyle.Child | DirectShowLib.WindowStyle.ClipSiblings | DirectShowLib.WindowStyle.ClipChildren); DsError.ThrowExceptionForHR(hr); try { Host_SizeChanged(null, null); } catch { } #if DEBUG rot = new DsROTEntry(this.graphBuilder); #endif //this.Focus(); // Run the graph to play the media file hr = this.mediaControl.Run(); DsError.ThrowExceptionForHR(hr); }
//Мотод для загрузки видео файла. public void FileLoad(string sfile, Panel vPanel) { CleanUp(); graphBuilder = (IGraphBuilder) new FilterGraph(); mediaControl = graphBuilder as IMediaControl; mediaPosition = graphBuilder as IMediaPosition; videoWindow = graphBuilder as IVideoWindow; basicAudio = graphBuilder as IBasicAudio; ddColor.lBrightness = 0; ddColor.lContrast = 0; ddColor.lGamma = 0; ddColor.lSaturation = 0; graphBuilder.RenderFile(sfile, null); videoWindow.put_Owner(vPanel.Handle); videoWindow.put_WindowStyle(WindowStyle.Child | WindowStyle.ClipSiblings | WindowStyle.ClipChildren); videoWindow.SetWindowPosition(vPanel.ClientRectangle.Left, vPanel.ClientRectangle.Top, vPanel.ClientRectangle.Width, vPanel.ClientRectangle.Height); mediaControl.Run(); CurrentStatus = mStatus.Play; mediaPosition.get_Duration(out mediaTimeSeconds); allSeconds = (int)mediaTimeSeconds; }
private void BridgeCallback(MediaBridge.MediaBridgeGraphInfo GraphInfo) { try { int hr = 0; //Convert pointer of filter graph to an object we can use graph = (IFilterGraph)Marshal.GetObjectForIUnknown(GraphInfo.FilterGraph); graphBuilder = (IGraphBuilder)graph; hr = graphBuilder.RenderFile(filepath, null); DsError.ThrowExceptionForHR(hr); } catch (Exception ex) { Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal, (ThreadStart)delegate() { ErrorException("BridgeCallback: " + ex.Message, ex.StackTrace); PreviewError(Languages.Translate("Error") + "...", Brushes.Red); }); } }
/// <summary> /// <para>指定された動画ファイルから音声のみをエンコードし、WAVファイルイメージを作成して返す。</para> /// </summary> public static void t変換(string fileName, out byte[] wavFileImage) { int hr = 0; IGraphBuilder graphBuilder = null; try { graphBuilder = (IGraphBuilder) new FilterGraph(); #region [ オーディオ用サンプルグラバの作成と追加。] //----------------- ISampleGrabber sampleGrabber = null; try { sampleGrabber = (ISampleGrabber) new SampleGrabber(); // サンプルグラバのメディアタイプの設定。 var mediaType = new AMMediaType() { majorType = MediaType.Audio, subType = MediaSubType.PCM, formatType = FormatType.WaveEx, }; try { hr = sampleGrabber.SetMediaType(mediaType); DsError.ThrowExceptionForHR(hr); } finally { if (mediaType != null) { DsUtils.FreeAMMediaType(mediaType); } } // サンプルグラバのバッファリングを有効にする。 hr = sampleGrabber.SetBufferSamples(true); DsError.ThrowExceptionForHR(hr); // サンプルグラバにコールバックを追加する。 sampleGrabberProc = new CSampleGrabberCallBack(); hr = sampleGrabber.SetCallback(sampleGrabberProc, 1); // 1:コールバックの BufferCB() メソッドの方を呼び出す。 // サンプルグラバをグラフに追加する。 hr = graphBuilder.AddFilter((IBaseFilter)sampleGrabber, "SampleGrabber for Audio/PCM"); DsError.ThrowExceptionForHR(hr); } finally { C共通.tCOMオブジェクトを解放する(ref sampleGrabber); } //----------------- #endregion var e = new DirectShowLib.DsROTEntry(graphBuilder); // fileName からグラフを自動生成。 hr = graphBuilder.RenderFile(fileName, null); // IMediaControl.RenderFile() は推奨されない DsError.ThrowExceptionForHR(hr); // ビデオレンダラを除去。 // オーディオレンダラをNullに変えるより前に実行すること。 // (CDirectShow.tオーディオレンダラをNullレンダラに変えてフォーマットを取得する() の中で一度再生するので、 // そのときにActiveウィンドウが表示されてしまうため。) // chnmr0 : ウィンドウを表示しないだけなら IVideoWindow で put_AutoShow した。 IVideoWindow vw = graphBuilder as IVideoWindow; vw.put_AutoShow(OABool.False); // オーディオレンダラを NullRenderer に置換。 WaveFormat wfx; byte[] wfx拡張領域; CDirectShow.tオーディオレンダラをNullレンダラに変えてフォーマットを取得する(graphBuilder, out wfx, out wfx拡張領域); // 基準クロックを NULL(最高速)に設定する。 IMediaFilter mediaFilter = graphBuilder as IMediaFilter; mediaFilter.SetSyncSource(null); mediaFilter = null; // メモリストリームにデコードデータを出力する。 sampleGrabberProc.MemoryStream = new MemoryStream(); // CDirectShow.tオーディオレンダラをNullレンダラに変えてフォーマットを取得する() で一度再生しているので、ストリームをクリアする。 var ms = sampleGrabberProc.MemoryStream; var bw = new BinaryWriter(ms); bw.Write(new byte[] { 0x52, 0x49, 0x46, 0x46 }); // 'RIFF' bw.Write((UInt32)0); // ファイルサイズ - 8 [byte];今は不明なので後で上書きする。 bw.Write(new byte[] { 0x57, 0x41, 0x56, 0x45 }); // 'WAVE' bw.Write(new byte[] { 0x66, 0x6D, 0x74, 0x20 }); // 'fmt ' bw.Write((UInt32)(16 + ((wfx拡張領域.Length > 0) ? (2 /*sizeof(WAVEFORMATEX.cbSize)*/ + wfx拡張領域.Length) : 0))); // fmtチャンクのサイズ[byte] bw.Write((UInt16)wfx.Encoding); // フォーマットID(リニアPCMなら1) bw.Write((UInt16)wfx.Channels); // チャンネル数 bw.Write((UInt32)wfx.SampleRate); // サンプリングレート bw.Write((UInt32)wfx.AverageBytesPerSecond); // データ速度 bw.Write((UInt16)wfx.BlockAlign); // ブロックサイズ bw.Write((UInt16)wfx.BitsPerSample); // サンプルあたりのビット数 if (wfx拡張領域.Length > 0) { bw.Write((UInt16)wfx拡張領域.Length); // 拡張領域のサイズ[byte] bw.Write(wfx拡張領域); // 拡張データ } bw.Write(new byte[] { 0x64, 0x61, 0x74, 0x61 }); // 'data' int nDATAチャンクサイズ位置 = (int)ms.Position; bw.Write((UInt32)0); // dataチャンクのサイズ[byte];今は不明なので後で上書きする。 #region [ 再生を開始し、終了を待つ。- 再生中、sampleGrabberProc.MemoryStream に PCM データが蓄積されていく。] //----------------- IMediaControl mediaControl = graphBuilder as IMediaControl; mediaControl.Run(); // 再生開始 IMediaEvent mediaEvent = graphBuilder as IMediaEvent; EventCode eventCode; hr = mediaEvent.WaitForCompletion(-1, out eventCode); DsError.ThrowExceptionForHR(hr); if (eventCode != EventCode.Complete) { throw new Exception("再生待ちに失敗しました。"); } mediaControl.Stop(); mediaEvent = null; mediaControl = null; //----------------- #endregion bw.Seek(4, SeekOrigin.Begin); bw.Write((UInt32)ms.Length - 8); // ファイルサイズ - 8 [byte] bw.Seek(nDATAチャンクサイズ位置, SeekOrigin.Begin); bw.Write((UInt32)ms.Length - (nDATAチャンクサイズ位置 + 4)); // dataチャンクサイズ [byte] // 出力その2を作成。 wavFileImage = ms.ToArray(); // 終了処理。 bw.Close(); sampleGrabberProc.Dispose(); // ms.Close() } finally { C共通.tCOMオブジェクトを解放する(ref graphBuilder); } }
private void translateW_Load(object sender, EventArgs e) { //this.MaximumSize = this.Size; //this.MinimumSize = this.Size; toolStripStatusLabel2.Text = "Cargando el Asistente de Traducción..."; // cargamos script autoComplete = new ArrayList(); al = mW.al; gridCont.RowCount = al.Count; bool hasAutoComplete = (mW.script.GetHeader().GetHeaderValue("AutoComplete") != string.Empty); for (int i = 0; i < al.Count; i++) { lineaASS lass = (lineaASS)al[i]; gridCont[0, i].Value = lass.personaje; if (!autoComplete.Contains(lass.personaje) && !hasAutoComplete) if (lass.personaje.Trim()!="") autoComplete.Add(lass.personaje); gridCont[1, i].Value = lass.texto; } if (hasAutoComplete) InsertAutoCompleteFromScript(); labelLineaActual.Text = "1 de " + (al.Count) + " (0%)"; textPersonaje.Text = gridCont[0, 0].Value.ToString(); textOrig.Text = gridCont[1, 0].Value.ToString(); // cargamos video graphBuilder = (IGraphBuilder)new FilterGraph(); graphBuilder.RenderFile(videoInfo.FileName, null); mediaControl = (IMediaControl)graphBuilder; // mediaEventEx = (IMediaEventEx)this.graphBuilder; mediaSeeking = (IMediaSeeking)graphBuilder; mediaPosition = (IMediaPosition)graphBuilder; basicVideo = graphBuilder as IBasicVideo; basicAudio = graphBuilder as IBasicAudio; videoWindow = graphBuilder as IVideoWindow; try { int x, y; double atpf; basicVideo.GetVideoSize(out x, out y); basicVideo.get_AvgTimePerFrame(out atpf); videoInfo.FrameRate = Math.Round(1 / atpf, 3); int new_x = videoPanel.Width; int new_y = (new_x * y) / x; videoWindow.put_Height(new_x); videoWindow.put_Width(new_y); videoWindow.put_Owner(videoPanel.Handle); videoPanel.Size = new System.Drawing.Size(new_x, new_y); videoWindow.SetWindowPosition(0, 0, videoPanel.Width, videoPanel.Height); videoWindow.put_WindowStyle(WindowStyle.Child); videoWindow.put_Visible(DirectShowLib.OABool.True); mediaSeeking.SetTimeFormat(DirectShowLib.TimeFormat.Frame); mediaControl.Run(); } catch { mW.errorMsg("Imposible cargar el vídeo. Debe haber algún problema con el mismo, y el asistente será muy inestable"); } // activamos timers & handlers timer1.Tick += new EventHandler(timer1_Tick); timer1.Enabled = true; timer2.Tick += new EventHandler(timer2_Tick); AutoSaveTimer.Tick += new EventHandler(timer3_Tick); AutoSaveTimer.Enabled = true; gridCont.CellClick += new DataGridViewCellEventHandler(gridCont_CellClick); textPersonaje.TextChanged += new EventHandler(textPersonaje_TextChanged); textTradu.TextChanged += new EventHandler(textTradu_TextChanged); textTradu.KeyUp += new KeyEventHandler(textBox1_KeyUp); textTradu.KeyDown += new KeyEventHandler(textTradu_KeyDown); textTradu.KeyPress += new KeyPressEventHandler(textTradu_KeyPress); textPersonaje.KeyDown += new KeyEventHandler(textPersonaje_KeyDown); textPersonaje.KeyPress += new KeyPressEventHandler(textPersonaje_KeyPress); button8.GotFocus += new EventHandler(button8_GotFocus); button9.GotFocus += new EventHandler(button9_GotFocus); gridCont.DoubleClick += new EventHandler(gridCont_DoubleClick); gridCont.SelectionChanged += new EventHandler(gridCont_SelectionChanged); gridCont.KeyUp += new KeyEventHandler(gridCont_KeyUp); listBox1.KeyUp += new KeyEventHandler(listBox1_KeyUp); textToAdd.KeyPress += new KeyPressEventHandler(textToAdd_KeyPress); progressBar1.MouseDown += new MouseEventHandler(progressBar1_MouseDown); tiempoInicio_.TimeValidated += new TimeTextBox.OnTimeTextBoxValidated(tiempo_TimeValidated); tiempoFin_.TimeValidated += new TimeTextBox.OnTimeTextBoxValidated(tiempo_TimeValidated); this.Move += new EventHandler(translateW_Move); //textTradu.ContextMenu = new ASSTextBoxRegExDefaultContextMenu(textTradu); mediaControl.Pause(); // cargar de config try { checkAutoComplete.Checked = Convert.ToBoolean(mW.getFromConfigFile("translateW_autoC")); checkTagSSA.Checked = Convert.ToBoolean(mW.getFromConfigFile("translateW_tagSSA")); checkComment.Checked = Convert.ToBoolean(mW.getFromConfigFile("translateW_Comment")); checkVideo.Checked = Convert.ToBoolean(mW.getFromConfigFile("translateW_aud")); checkAudio.Checked = Convert.ToBoolean(mW.getFromConfigFile("translateW_vid")); checkSaveTime.Checked = Convert.ToBoolean(mW.getFromConfigFile("translateW_preTime")); } catch {} try { AutoSaveTimer.Interval = int.Parse(mW.getFromConfigFile("translateW_AutoSaveInterval")); } catch { AutoSaveTimer.Interval = 30000; } // fin de inicializacion vil textTradu.Focus(); try { string[] bleh = mW.getFromConfigFileA("translateW_Reference"); for (int i = 0; i < bleh.Length; i++) Diccionarios.Add(bleh[i]); } catch { Diccionarios.Add("WordReference|http://www.wordreference.com/"); Diccionarios.Add("Wikipedia|http://es.wikipedia.org"); Diccionarios.Add("RAE|http://www.rae.es"); Diccionarios.Add("Dictionary|http://dictionary.reference.com/"); } diccionarios.DataSource = Diccionarios; CreateReferenceTabs(); UpdateStatusFile(); TiempoInicio = DateTime.Now; Estadisticas.Interval = 1000; Estadisticas.Tick += new EventHandler(Estadisticas_Tick); Estadisticas.Enabled = true; InitRPC(); archivosView.KeyDown += new KeyEventHandler(archivosView_KeyDown); archivosView.SelectedIndexChanged += new EventHandler(archivosView_SelectedIndexChanged); textTradu.EnableSpellChecking = mW.spellEnabled; if (mW.spellEnabled) { textTradu.DictionaryPath = mW.dictDir; textTradu.Dictionary = mW.ActiveDict; } toolStripStatusLabel2.Text = "Asistente cargado correctamente."; bool showpopup = true; try { showpopup = Convert.ToBoolean(mW.getFromConfigFile("translateW_ShowPopup")); } catch { mW.updateReplaceConfigFile("translateW_ShowPopup", showpopup.ToString()); } if (showpopup) { TranslationStyle estilo = TranslationStyle.FromScriptWithActors; translateW_Popup pop = new translateW_Popup(mW); switch (pop.ShowDialog()) { case DialogResult.Yes: estilo = TranslationStyle.FromScriptWithActors; break; case DialogResult.No: estilo = TranslationStyle.FromScriptWithoutActors; break; case DialogResult.Cancel: estilo = TranslationStyle.FromScratch; break; case DialogResult.Ignore: estilo = TranslationStyle.FromScratchAudio; break; } switch (estilo) { case TranslationStyle.FromScriptWithActors: modeSelector.Checked = true; splitText.Checked = false; audioMode.Checked = false; break; case TranslationStyle.FromScriptWithoutActors: modeSelector.Checked = true; splitText.Checked = true; audioMode.Checked = false; break; case TranslationStyle.FromScratch: modeSelector.Checked = false; splitText.Checked = false; audioMode.Checked = false; break; case TranslationStyle.FromScratchAudio: modeSelector.Checked = false; splitText.Checked = true; audioMode.Checked = true; break; } } }
void SetupPlaybackGraph(string fname) { int hr; try { hr = graphBuilder.RenderFile(fname, null); if (hr < 0) { Marshal.ThrowExceptionForHR(hr); } AMMediaType media = new AMMediaType(); media.majorType = MediaType.Video; media.subType = MediaSubType.RGB24; media.formatType = FormatType.VideoInfo; // ??? hr = sampGrabber.SetMediaType(media); if (hr < 0) { Marshal.ThrowExceptionForHR(hr); } hr = graphBuilder.AddFilter(baseGrabFlt, "Ds.NET Grabber"); if (hr < 0) { Marshal.ThrowExceptionForHR(hr); } hr = graphBuilder.AddFilter(smartTee, "smartTee"); if (hr < 0) { Marshal.ThrowExceptionForHR(hr); } IBaseFilter renderer; hr = graphBuilder.FindFilterByName("Video Renderer", out renderer); if (hr < 0) { Marshal.ThrowExceptionForHR(hr); } IPin inPin; IPin srcPin; hr = DsUtils.GetPin(renderer, PinDirection.Input, out inPin, 0); if (hr < 0) { Marshal.ThrowExceptionForHR(hr); } hr = inPin.ConnectedTo(out srcPin); if (hr < 0) { Marshal.ThrowExceptionForHR(hr); } hr = srcPin.Disconnect(); if (hr < 0) { Marshal.ThrowExceptionForHR(hr); } hr = graphBuilder.RemoveFilter(renderer); if (hr < 0) { Marshal.ThrowExceptionForHR(hr); } Marshal.ReleaseComObject(renderer); Marshal.ReleaseComObject(inPin); hr = DsUtils.GetPin(smartTee, PinDirection.Input, out inPin, 0); if (hr < 0) { Marshal.ThrowExceptionForHR(hr); } hr = graphBuilder.Connect(srcPin, inPin); if (hr < 0) { Marshal.ThrowExceptionForHR(hr); } Marshal.ReleaseComObject(srcPin); Marshal.ReleaseComObject(inPin); srcPin = inPin = null; hr = DsUtils.GetPin(smartTee, PinDirection.Output, out srcPin, 1); if (hr < 0) { Marshal.ThrowExceptionForHR(hr); } // grabber Input hr = DsUtils.GetPin(baseGrabFlt, PinDirection.Input, out inPin, 0); if (hr < 0) { Marshal.ThrowExceptionForHR(hr); } // smartTee -> grabber hr = graphBuilder.Connect(srcPin, inPin); if (hr < 0) { Marshal.ThrowExceptionForHR(hr); } Marshal.ReleaseComObject(srcPin); Marshal.ReleaseComObject(inPin); srcPin = inPin = null; if (preview) { // grabber Input hr = DsUtils.GetPin(smartTee, PinDirection.Output, out srcPin, 0); if (hr < 0) { Marshal.ThrowExceptionForHR(hr); } hr = graphBuilder.Render(srcPin); if (hr < 0) { Marshal.ThrowExceptionForHR(hr); } Marshal.ReleaseComObject(srcPin); srcPin = null; } media = new AMMediaType(); hr = sampGrabber.GetConnectedMediaType(media); if (hr < 0) { Marshal.ThrowExceptionForHR(hr); } if ((media.formatType != FormatType.VideoInfo) || (media.formatPtr == IntPtr.Zero)) { throw new NotSupportedException("Unknown Grabber Media Format"); } videoInfoHeader = (VideoInfoHeader)Marshal.PtrToStructure(media.formatPtr, typeof(VideoInfoHeader)); Marshal.FreeCoTaskMem(media.formatPtr); media.formatPtr = IntPtr.Zero; //Modified according to the platform SDK, to capture the buffer hr = sampGrabber.SetBufferSamples(false); if (hr == 0) { hr = sampGrabber.SetOneShot(false); } if (hr == 0) { hr = sampGrabber.SetCallback(sampleGrabber, 1); } if (hr < 0) { Marshal.ThrowExceptionForHR(hr); } } catch (Exception ee) { throw new Exception("Could not setup graph\r\n" + ee.Message); } }
/// <summary> /// Creates a new Video Player. Automatically creates the required Texture2D on the specificied GraphicsDevice. /// </summary> /// <param name="FileName">The video file to open</param> /// <param name="graphicsDevice">XNA Graphics Device</param> public XNAPlayer(Feel feel, string FileName, GraphicsDevice graphicsDevice, Action callback) { Utils.RunAsynchronously(() => { try { // Set video state currentState = VideoState.Stopped; // Store Filename filename = FileName; // Open DirectShow Interfaces InitInterfaces(); // Create a SampleGrabber Filter and add it to the FilterGraph SampleGrabber sg = new SampleGrabber(); ISampleGrabber sampleGrabber = (ISampleGrabber)sg; DsError.ThrowExceptionForHR(gb.AddFilter((IBaseFilter)sg, "Grabber")); // Setup Media type info for the SampleGrabber AMMediaType mt = new AMMediaType(); mt.majorType = MEDIATYPE_Video; // Video mt.subType = MEDIASUBTYPE_RGB24; // RGB24 mt.formatType = FORMAT_VideoInfo; // VideoInfo DsError.ThrowExceptionForHR(sampleGrabber.SetMediaType(mt)); // Construct the rest of the FilterGraph DsError.ThrowExceptionForHR(gb.RenderFile(filename, null)); // Set SampleGrabber Properties DsError.ThrowExceptionForHR(sampleGrabber.SetBufferSamples(true)); DsError.ThrowExceptionForHR(sampleGrabber.SetOneShot(false)); DsError.ThrowExceptionForHR(sampleGrabber.SetCallback((ISampleGrabberCB)this, 1)); // Hide Default Video Window IVideoWindow pVideoWindow = (IVideoWindow)gb; DsError.ThrowExceptionForHR(pVideoWindow.put_MessageDrain(IntPtr.Zero)); DsError.ThrowExceptionForHR(pVideoWindow.put_WindowState(WindowState.Hide)); DsError.ThrowExceptionForHR(pVideoWindow.put_AutoShow(OABool.False)); // Create AMMediaType to capture video information AMMediaType MediaType = new AMMediaType(); DsError.ThrowExceptionForHR(sampleGrabber.GetConnectedMediaType(MediaType)); VideoInfoHeader pVideoHeader = new VideoInfoHeader(); Marshal.PtrToStructure(MediaType.formatPtr, pVideoHeader); // Store video information videoHeight = pVideoHeader.BmiHeader.Height; videoWidth = pVideoHeader.BmiHeader.Width; avgTimePerFrame = pVideoHeader.AvgTimePerFrame; bitRate = pVideoHeader.BitRate; DsError.ThrowExceptionForHR(ms.GetDuration(out videoDuration)); // Create byte arrays to hold video data videoFrameBytes = new byte[(videoHeight * videoWidth) * 4]; // RGBA format (4 bytes per pixel) bgrData = new byte[(videoHeight * videoWidth) * 4]; // BGR24 format (3 bytes per pixel + 1 for safety) // Create Output Frame Texture2D with the height and width of the video outputFrame = new Texture2D(graphicsDevice, videoWidth, videoHeight, 1, TextureUsage.None, SurfaceFormat.Color); feel.RunOnUIThread(callback); } catch { feel.ShowToast("Unable to Load or Play the video file"); } }, () => { }); }
private void StartConversion() { // build directshow graph _filterGraph = new FilterGraph(); _graphBuilder = (IGraphBuilder)_filterGraph; // Create Standard MPEG Filter Guid guid = new Guid("CFD87339-C61F-46ca-B6A1-F87D6B96243E"); Type comtype = Type.GetTypeFromCLSID(guid); _mpegFilter = (IBaseFilter)Activator.CreateInstance(comtype); SetFilterParams(); // Set the output file IBaseFilter fileWriter = (IBaseFilter)new FileWriter(); IFileSinkFilter fs = (IFileSinkFilter)fileWriter; int hr = fs.SetFileName(textBoxTgt.Text, null); hr = _graphBuilder.AddFilter(fileWriter, "File Writer Filter"); DsError.ThrowExceptionForHR(hr); // Add the encoder filter to the graph hr = _graphBuilder.AddFilter(_mpegFilter, "MPEG Filter"); DsError.ThrowExceptionForHR(hr); // use Intelligent connect to build the rest of the graph hr = _graphBuilder.RenderFile(textBoxSrc.Text, null); DsError.ThrowExceptionForHR(hr); // get the interfaces we need for info and control _mediaControl = (IMediaControl)_filterGraph; _mediaEvent = (IMediaEventEx)_filterGraph; _mediaSeeking = (IMediaSeeking)_mpegFilter; hr = _mediaEvent.SetNotifyWindow(this.Handle, WM_GRAPHNOTIFY, IntPtr.Zero); DsError.ThrowExceptionForHR(hr); // we are ready to convert hr = _mediaControl.Run(); DsError.ThrowExceptionForHR(hr); }
private void BuildGraph() { int hr; try { lblTotalTime.Text = mvs.PlayTime.ToString(); TimeSpan tt = TimeSpan.Parse(mvs.PlayTime); DateTime dt = new DateTime(tt.Ticks); lblTotalTime.Text = String.Format("{0:HH:mm:ss}", dt); if (mvs.LocalMedia[0].IsDVD) { mediaToPlay = mvs.LocalMedia[0]; MediaState mediaState = mediaToPlay.State; if (mediaState == MediaState.NotMounted) { MountResult result = mediaToPlay.Mount(); } string videoPath = mediaToPlay.GetVideoPath(); if (videoPath != null) { FirstPlayDvd(videoPath); } else { FirstPlayDvd(mvs.LocalMedia[0].File.FullName); } // Add delegates for Windowless operations AddHandlers(); MainForm_ResizeMove(null, null); } else { _graphBuilder = (IFilterGraph2) new FilterGraph(); _rotEntry = new DsROTEntry((IFilterGraph)_graphBuilder); _mediaCtrl = (IMediaControl)_graphBuilder; _mediaSeek = (IMediaSeeking)_graphBuilder; _mediaPos = (IMediaPosition)_graphBuilder; _mediaStep = (IVideoFrameStep)_graphBuilder; _vmr9Filter = (IBaseFilter) new VideoMixingRenderer9(); ConfigureVMR9InWindowlessMode(); AddHandlers(); MainForm_ResizeMove(null, null); hr = _graphBuilder.AddFilter(_vmr9Filter, "Video Mixing Render 9"); AddPreferedCodecs(_graphBuilder); DsError.ThrowExceptionForHR(hr); hr = _graphBuilder.RenderFile(mvs.LocalMedia[0].File.FullName, null); DsError.ThrowExceptionForHR(hr); } } catch (Exception e) { CloseDVDInterfaces(); logger.ErrorException("An error occured during the graph building : \r\n\r\n", e); } }
private void BuildGraph() { int hr; try { lblTotalTime.Text = mvs.PlayTime.ToString(); TimeSpan tt = TimeSpan.Parse(mvs.PlayTime); DateTime dt = new DateTime(tt.Ticks); lblTotalTime.Text = String.Format("{0:HH:mm:ss}", dt); if (mvs.LocalMedia[0].IsDVD) { mediaToPlay = mvs.LocalMedia[0]; MediaState mediaState = mediaToPlay.State; if (mediaState == MediaState.NotMounted) { MountResult result = mediaToPlay.Mount(); } string videoPath = mediaToPlay.GetVideoPath(); if (videoPath != null) FirstPlayDvd(videoPath); else FirstPlayDvd(mvs.LocalMedia[0].File.FullName); // Add delegates for Windowless operations AddHandlers(); MainForm_ResizeMove(null, null); } else { _graphBuilder = (IFilterGraph2)new FilterGraph(); _rotEntry = new DsROTEntry((IFilterGraph)_graphBuilder); _mediaCtrl = (IMediaControl)_graphBuilder; _mediaSeek = (IMediaSeeking)_graphBuilder; _mediaPos = (IMediaPosition)_graphBuilder; _mediaStep = (IVideoFrameStep)_graphBuilder; _vmr9Filter = (IBaseFilter)new VideoMixingRenderer9(); ConfigureVMR9InWindowlessMode(); AddHandlers(); MainForm_ResizeMove(null, null); hr = _graphBuilder.AddFilter(_vmr9Filter, "Video Mixing Render 9"); AddPreferedCodecs(_graphBuilder); DsError.ThrowExceptionForHR(hr); hr = _graphBuilder.RenderFile(mvs.LocalMedia[0].File.FullName, null); DsError.ThrowExceptionForHR(hr); } } catch (Exception e) { CloseDVDInterfaces(); logger.ErrorException("An error occured during the graph building : \r\n\r\n",e); } }
/// <summary> /// Creates a new Video Player. Automatically creates the required Texture2D on the specificied GraphicsDevice. /// </summary> /// <param name="FileName">The video file to open</param> /// <param name="graphicsDevice">XNA Graphics Device</param> protected VideoPlayer(string FileName) { try { // Set video state currentState = VideoState.Stopped; // Store Filename filename = FileName; // Open DirectShow Interfaces InitInterfaces(); // Create a SampleGrabber Filter and add it to the FilterGraph //SampleGrabber sg = new SampleGrabber(); var comtype = Type.GetTypeFromCLSID(Clsid.SampleGrabber); if (comtype == null) { throw new NotSupportedException("DirectX (8.1 or higher) not installed?"); } m_comObject = Activator.CreateInstance(comtype); ISampleGrabber sampleGrabber = (ISampleGrabber)m_comObject; m_graphBuilder.AddFilter((IBaseFilter)m_comObject, "Grabber"); // Setup Media type info for the SampleGrabber AMMediaType mt = new AMMediaType(); mt.majorType = MEDIATYPE_Video; // Video mt.subType = MEDIASUBTYPE_RGB32; // RGB32 mt.formatType = FORMAT_VideoInfo; // VideoInfo sampleGrabber.SetMediaType(mt); // Construct the rest of the FilterGraph m_graphBuilder.RenderFile(filename, null); // Set SampleGrabber Properties sampleGrabber.SetBufferSamples(true); sampleGrabber.SetOneShot(false); sampleGrabber.SetCallback((ISampleGrabberCB)this, 1); // Hide Default Video Window IVideoWindow pVideoWindow = (IVideoWindow)m_graphBuilder; //pVideoWindow.put_AutoShow(OABool.False); pVideoWindow.put_AutoShow(0); // Create AMMediaType to capture video information AMMediaType MediaType = new AMMediaType(); sampleGrabber.GetConnectedMediaType(MediaType); VideoInfoHeader pVideoHeader = new VideoInfoHeader(); Marshal.PtrToStructure(MediaType.formatPtr, pVideoHeader); // Store video information videoHeight = pVideoHeader.BmiHeader.Height; videoWidth = pVideoHeader.BmiHeader.Width; avgTimePerFrame = pVideoHeader.AvgTimePerFrame; bitRate = pVideoHeader.BitRate; m_mediaSeeking.GetDuration(out videoDuration); // Create byte arrays to hold video data m_videoDataRgba = new MySwapQueue <byte[]>(() => new byte[(videoHeight * videoWidth) * 4]); // RGBA format (4 bytes per pixel) } catch (Exception e) { throw new Exception("Unable to Load or Play the video file", e); } }
// // This method converts the input file to a mkv file // void Convert2Mkv(string fileName) { try { progressText.Text = "Dönüþtürme iþlemi devam ediyor"; start.Enabled = false; convert.Enabled = false; SaveFileDialog saveFile = new SaveFileDialog(); if (saveFile.ShowDialog() == DialogResult.OK) { hr = me.SetNotifyWindow(this.Handle, WM_GRAPHNOTIFY, IntPtr.Zero); DsError.ThrowExceptionForHR(hr); // we want to add a filewriter filter to the filter graph FileWriter file_writer = new FileWriter(); // make sure we access the IFileSinkFilter interface to // set the file name IFileSinkFilter fs = (IFileSinkFilter)file_writer; fs.SetFileName(saveFile.FileName + ".mkv", null); string[] fileNewName = saveFile.FileName.Split('\\'); outPutText.Text = fileNewName[fileNewName.Length - 1].ToString() + ".mkv"; DsError.ThrowExceptionForHR(hr); // add the filter to the graph hr = gb.AddFilter((IBaseFilter)file_writer, "File Writer"); DsError.ThrowExceptionForHR(hr); // create an instance of the matroska multiplex filter and add it // Matroska Mux Clsid = {1E1299A2-9D42-4F12-8791-D79E376F4143} Guid guid = new Guid("1E1299A2-9D42-4F12-8791-D79E376F4143"); Type comtype = Type.GetTypeFromCLSID(guid); matroska_mux = (IBaseFilter)Activator.CreateInstance(comtype); hr = gb.AddFilter((IBaseFilter)matroska_mux, "Matroska Muxer"); DsError.ThrowExceptionForHR(hr); // use Intelligent connect to build the rest of the graph hr = gb.RenderFile(fileName + fExt, null); DsError.ThrowExceptionForHR(hr); // we are ready to convert hr = mc.Run(); DsError.ThrowExceptionForHR(hr); } else { convert.Enabled = true; } } catch (Exception ex) { MessageBox.Show("Mkv ye çevirilirken hata olustu " + ex.Message); timerThread.Stop(); topProgressBar.Value = 0; fileName.Text = ""; outPutText.Text = ""; start.Enabled = true; convert.Enabled = true; progressText.Text = "Hata olustu, dönüstürme islemi devam ettirilemiyor"; } }
private void BridgeCallback(MediaBridge.MediaBridgeGraphInfo GraphInfo) { try { int hr = 0; //Convert pointer of filter graph to an object we can use graph = (IFilterGraph)Marshal.GetObjectForIUnknown(GraphInfo.FilterGraph); graphBuilder = (IGraphBuilder)graph; hr = graphBuilder.RenderFile(filepath, null); DsError.ThrowExceptionForHR(hr); } catch (Exception ex) { ErrorException("BridgeCallback: " + ex.Message, ex.StackTrace); } }