Ejemplo n.º 1
0
        public string ChooseDstFileName()
        {
            string          ret  = null;
            IFileSinkFilter fdst = basefilter as IFileSinkFilter;

            if (fdst != null)
            {
                using (var fd = new SaveFileDialog())
                {
                    if (fd.ShowDialog() == DialogResult.OK)
                    {
                        try
                        {
                            int hr = fdst.SetFileName(fd.FileName, null);
                            DsError.ThrowExceptionForHR(hr);
                            ret = fd.FileName;
                        }
                        catch (COMException e)
                        {
                            Graph.ShowCOMException(e, "Can't create file " + fd.FileName);
                        }
                        catch (Exception e)
                        {
                            MessageBox.Show(e.Message, "Exception caught while setting output file name " + fd.FileName);
                        }
                    }
                    else
                    if (Program.mainform.suggestURLs)
                    {
                        using (var rf = new RenderURLForm("Open URL"))
                        {
                            rf.ShowDialog();
                            if (rf.selectedURL != null)
                            {
                                try
                                {
                                    int hr = fdst.SetFileName(rf.selectedURL, null);
                                    DsError.ThrowExceptionForHR(hr);
                                    ret = rf.selectedURL;
                                }
                                catch (COMException e)
                                {
                                    Graph.ShowCOMException(e, "Can't set " + rf.selectedURL);
                                }
                                catch (Exception e)
                                {
                                    MessageBox.Show(e.Message, "Exception caught while setting URL " + rf.selectedURL);
                                }
                            }
                        }    //using rf
                    }
                }//using fd
            }
            return(ret);
        }
Ejemplo n.º 2
0
        /// <summary>
        /// This method must be called to initialize the network sink. Make sure the SinkURL is properly populated before calling this method.
        /// </summary>
        protected void InitializeSink()
        {
            _sinkControl.StartChangingAttributes();
            IFileSinkFilter fileSink = (IFileSinkFilter)_sink;

            if (fileSink == null)
            {
                throw new Exception("IFileSourceFilter not found on DVR Sink");
            }
            AMMediaType mediaType = new AMMediaType();

            mediaType.majorType = DirectShowLib.MediaType.Stream;
            mediaType.subType   = MediaSubType.Null;
            String sinkFolderPath = null;

            sinkFolderPath = Settings.RootFolder + SourceConfig.SourceName + @"/";
            if (Directory.Exists(sinkFolderPath) == false)
            {
                Directory.CreateDirectory(sinkFolderPath);
            }
            int hr = fileSink.SetFileName(sinkFolderPath + "Stream.LBL", mediaType);

            DsError.ThrowExceptionForHR(hr);
            _sinkControl.SetBufferSize(0, Settings.NumberOfFiles, Settings.FileSize);
            Debug.WriteLine(String.Format("DVR for {0} is writing to {1}--{2} files with {3} bytes per file", SourceConfig.SourceName,
                                          sinkFolderPath, Settings.NumberOfFiles, Settings.FileSize));
            _sinkControl.StopChangingAttributes(false);
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Constructs a new OggWriter
        /// </summary>
        public OggWriter() : base()
        {
            oggMux = FilterGraphTools.AddFilterByName(this.graph, FilterCategory.LegacyAmFilterCategory, "LEAD Ogg Multiplexer");
            if (oggMux == null)
            {
                throw new Exception("Could not instantiate OGG Mux!");
            }

            fileWriter = FilterGraphTools.AddFilterByName(this.graph, FilterCategory.LegacyAmFilterCategory, "File writer");
            if (fileWriter == null)
            {
                throw new Exception("File writer could not be instantiated");
            }

            IFileSinkFilter fs = fileWriter as IFileSinkFilter;

            if (fs == null)
            {
                throw new Exception(@"Can't get IFileSinkFilter interface!");
            }

            string datetime = DateTime.Now.ToString("yyMMdd HHmmss");

            int hr = fs.SetFileName(@"C:\temp\" + datetime + " oggwriter.ogm", null);

            DsError.ThrowExceptionForHR(hr);
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Builds a recording graph that saves the incoming H264 stream to an Ogg container to add
        /// support for seeking.
        /// </summary>
        /// <param name="filename">file to record to</param>
        /// <remarks>
        /// Since this recording graph does not recompress or decompress any data, it performs its job
        /// with little overhead.
        /// </remarks>
        protected void CreateRecordingGraph(string filename)
        {
            lock (instanceMutex)
            {
                //create file recording graph
                _fileSinkGraphBuilder        = (IGraphBuilder) new FilterGraph();
                _fileSinkCaptureGraphBuilder = (ICaptureGraphBuilder2) new CaptureGraphBuilder2();
                _fileSinkMediaControl        = (IMediaControl)_fileSinkGraphBuilder;

                //attach filter graph to capture graph, for recording
                int hr = _fileSinkCaptureGraphBuilder.SetFiltergraph(_fileSinkGraphBuilder);
                DsError.ThrowExceptionForHR(hr);

                //add bridge source to the recording graph, linked to the bridge sink
                _bridgeSource = (IBaseFilter)_bridgeController.InsertSourceFilter(_bridgeSink, _fileSinkGraphBuilder);

                _muxer = AddFilterByName(_fileSinkGraphBuilder, FilterCategory.LegacyAmFilterCategory, "LEAD MPEG2 Multiplexer (2.0)");
                //add the File Writer
                _fileSink       = AddFilterByName(_fileSinkGraphBuilder, FilterCategory.LegacyAmFilterCategory, "File writer");
                _fileSinkFilter = (IFileSinkFilter)_fileSink;
                hr = _fileSinkFilter.SetFileName(filename, null);
                DsError.ThrowExceptionForHR(hr);
                ConnectFilters(_fileSinkGraphBuilder, _bridgeSource, "Output 1", _muxer, "Input 01", true);
                ConnectFilters(_fileSinkGraphBuilder, _muxer, "Output 01", _fileSink, "in", false);
            }
        }
Ejemplo n.º 5
0
        public override void RenderCapture(string fileName)
        {
            int hr;



            if (_encoderDevice == null)
            {
                throw new Exception("Encoder device \"" + GraphConfig[FilterType.VideoEncoder].Name + "\" could not be loaded!");
            }
            if (_writerDevice == null)
            {
                throw new Exception("Writer device \"" + GraphConfig[FilterType.Writer].Name + "\" could not be loaded!");
            }

            _videoEncoder = AddFilterByDevicePath(_encoderDevice.DevicePath, _encoderDevice.Name);
            _fileWriter   = AddFilterByDevicePath(_writerDevice.DevicePath, _writerDevice.Name);

            SetVideoBitRate(GraphConfig.VideoBitrate.MinBitRate, GraphConfig.VideoBitrate.MaxBitRate, GraphConfig.VideoIsVBR);
            ConnectFilters(_captureFilter, "656", _videoEncoder, "656", true);
            ConnectFilters(_videoEncoder, "MPEG", _fileWriter, "Input", true);

            IFileSinkFilter fileSinkControl = (IFileSinkFilter)_fileWriter;

            hr = fileSinkControl.SetFileName(fileName + ".mpg", _emptyAMMediaType);
            DsError.ThrowExceptionForHR(hr);

            StartDVRWriter(_fileWriter);
        }
Ejemplo n.º 6
0
        public void StartRecording()
        {
            AppLogger.Message("StreamingAndRecording.StartRecording");
            string filename = _filenamePrefix + @"-" + _sequenceNumber + ".lts";

            _recordSinkFilter.SetFileName(filename, new AMMediaType());
            int hr = _dvrWriter.StartRecording();

            DsError.ThrowExceptionForHR(hr);
            _sequenceNumber++;
        }
Ejemplo n.º 7
0
        public StreamingAndRecording(StreamSourceInfo sourceConfig, OpenGraphRequest openGraphRequest) : base(sourceConfig, openGraphRequest)
        {
            InitializeNetworkSink();

            int hr;

            _tee = (IBaseFilter) new InfTee();
            hr   = _graphBuilder.AddFilter(_tee, "Inf Tee");
            DsError.ThrowExceptionForHR(hr);

            _recordSink       = AddFilterByName(FilterCategory.LegacyAmFilterCategory, "DVR Writer");
            _recordSinkFilter = (IFileSinkFilter)_recordSink;
            _recordSinkFilter.SetFileName(@"c:\test.lts", new AMMediaType());
            _dvrWriter = (IDVRWriterApi)_recordSink;
        }
Ejemplo n.º 8
0
        /// <summary>
        /// This method must be called to initialize the network sink. Make sure the SinkURL is properly populated before calling this method.
        /// </summary>
        protected void InitializeSink()
        {
            IFileSinkFilter fileSink = (IFileSinkFilter)_sink;

            if (fileSink == null)
            {
                throw new Exception("IFileSourceFilter not found on DVR Sink");
            }
            AMMediaType mediaType = new AMMediaType();

            mediaType.majorType = DirectShowLib.MediaType.Stream;
            mediaType.subType   = MediaSubType.Null;
            int hr = fileSink.SetFileName(SourceConfig.SinkAddress, mediaType);

            DsError.ThrowExceptionForHR(hr);
        }
        //
        // This method convert the input file to an wmv file
        //
        void Convert2Wmv(string fileName)
        {
            try
            {
                progressText.Text = "Dönüstürme islemi 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);

                    // here we use the asf writer to create wmv files
                    WMAsfWriter     asf_filter = new WMAsfWriter();
                    IFileSinkFilter fs         = (IFileSinkFilter)asf_filter;
                    hr = fs.SetFileName(saveFile.FileName + ".wmv", null);
                    string[] fileNewName = saveFile.FileName.Split('\\');
                    outPutText.Text = fileNewName[fileNewName.Length - 1].ToString() + ".wmv";
                    DsError.ThrowExceptionForHR(hr);

                    hr = gb.AddFilter((IBaseFilter)asf_filter, "WM Asf Writer");
                    DsError.ThrowExceptionForHR(hr);

                    hr = gb.RenderFile(fileName + fExt, null);
                    DsError.ThrowExceptionForHR(hr);

                    hr = mc.Run();
                    DsError.ThrowExceptionForHR(hr);
                }
                else
                {
                    convert.Enabled = true;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Wmv ye çevirilirken hata olustu " + ex.Message);
                timerThread.Stop();
                topProgressBar.Value = 0;
                fileName.Text        = "";
                outPutText.Text      = "";
                start.Enabled        = true;
                convert.Enabled      = true;
                progressText.Text    = "Hata oluþtu, dönüþtürme iþlemi devam ettirilemiyor";
            }
        }
Ejemplo n.º 10
0
        /// <summary>
        /// This method must be called to initialize the network sink. Make sure the SinkURL is properly populated before calling this method.
        /// </summary>
        protected void InitializeNetworkSink()
        {
            IFileSinkFilter fileSink = (IFileSinkFilter)_netSnk;

            if (fileSink == null)
            {
                throw new Exception("IFileSourceFilter not found on LMNetSink");
            }
            _lmNetSnk = (ILMNetSnk)_netSnk;
            AMMediaType mediaType = new AMMediaType();

            mediaType.majorType = DirectShowLib.MediaType.Stream;
            mediaType.subType   = MediaSubType.Null;
            int hr = fileSink.SetFileName(ClientURL, mediaType);

            DsError.ThrowExceptionForHR(hr);
        }
Ejemplo n.º 11
0
        /// <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);
        }
Ejemplo n.º 12
0
        /// <summary>
        /// initializes the sink
        /// </summary>
        protected virtual void InitializeNetworkSink()
        {
            IFileSinkFilter fileSink = (IFileSinkFilter)netSnk;

            if (fileSink == null)
            {
                throw new Exception("IFileSourceFilter not found on LMNetSink");
            }
            lmNetSnk = (LMNetSnk)netSnk;
            AMMediaType mediaType = new AMMediaType();

            mediaType.majorType = MediaType.Stream;
            mediaType.subType   = MediaSubType.Null;
            int hr = fileSink.SetFileName(this.SinkURL, mediaType);

            DsError.ThrowExceptionForHR(hr);
        }
Ejemplo n.º 13
0
        /// <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 source filter for the dvr-ms file
            IBaseFilter DvrmsSourceFilter = graph.AddSourceFilter(InputFilePath, null);

            DisposalCleanup.Add(DvrmsSourceFilter);

            // Add the file writer to the graph
            IBaseFilter wavFilter = (IBaseFilter)ClassId.CoCreateInstance(ClassId.FileWriter);

            DisposalCleanup.Add(wavFilter);
            graph.AddFilter(wavFilter, null);
            IFileSinkFilter sinkFilter = (IFileSinkFilter)wavFilter;

            sinkFilter.SetFileName(OutputFilePath, null);

            // Add the Wav Dest filter to the graph
            IBaseFilter wavDest = (IBaseFilter)ClassId.CoCreateInstance(ClassId.WavDest);

            DisposalCleanup.Add(wavDest);
            graph.AddFilter(wavDest, null);

            // Add the decrypter node to the graph
            IBaseFilter decrypter = (IBaseFilter)ClassId.CoCreateInstance(ClassId.DecryptTag);

            DisposalCleanup.Add(decrypter);
            graph.AddFilter(decrypter, null);

            // Connect the dvr-ms source to the decrypter, the decrypter to the wav dest,
            // and the wav dest to the file writer
            Connect(graph, DvrmsSourceFilter, "DVR Out - 1", decrypter, "In(Enc/Tag)");
            Connect(graph, decrypter, "Out", wavDest, "In");
            Connect(graph, wavDest, "Out", wavFilter, "in");

            // Run the graph to convert the audio to wav
            RunGraph(graph);

            return(null);
        }
Ejemplo n.º 14
0
        public override void RenderCapture(string fileName)
        {
            //AVerMedia Encoder
            //ITU Video--|
            //           |--MPEG2 Program
            //I2S Audio--|

            _encoderDevice = FindDevice(FilterCategory.WDMStreamingEncoderDevices, Config.FilterType.VideoEncoder);

            if (_encoderDevice == null)
            {
                throw new Exception("Encoder device \"" + GraphConfig[FilterType.VideoEncoder].Name + "\" could not be loaded!");
            }
            if (_writerDevice == null)
            {
                throw new Exception("Writer device \"" + GraphConfig[FilterType.Writer].Name + "\" could not be loaded!");
            }

            //get filters from devices
            _videoEncoder = AddFilterByDevicePath(_encoderDevice.DevicePath, _encoderDevice.Name);
            _fileWriter   = AddFilterByDevicePath(_writerDevice.DevicePath, _writerDevice.Name);

            ConnectFilters(_captureFilter, "ITU Video", _videoEncoder, "ITU Video", false);
            ConnectFilters(_captureFilter, "I2S Audio", _videoEncoder, "I2S Audio", false);

            ConnectFilters(_videoEncoder, "MPEG2 Program", _fileWriter, "Input", false);

            //configure File Sink / File Writer
            IFileSinkFilter fileSink = (IFileSinkFilter)_fileWriter;
            int             hr       = fileSink.SetFileName(fileName + ".mpg", _emptyAMMediaType);

            if (hr != 0)
            {
                this.CaptureRequiresNewGraph = true;
            }

            DsError.ThrowExceptionForHR(hr);

            StartDVRWriter(_fileWriter);

            this.SaveGraphFile();
        }
Ejemplo n.º 15
0
        public override void RenderCapture(string fileName)
        {
            //add new filters
            r_oggMux = FilterGraphTools.AddFilterByName(_graphBuilder, FilterCategory.LegacyAmFilterCategory, "LEAD Ogg Multiplexer");
            if (r_oggMux == null)
            {
                throw new Exception("Could not instantiate OGG Multiplexer!");
            }
            _fileWriter = FilterGraphTools.AddFilterByName(_graphBuilder, FilterCategory.LegacyAmFilterCategory, GraphConfig[FilterType.Writer].Name);
            if (_fileWriter == null)
            {
                throw new Exception("Could not instatiate \"" + GraphConfig[FilterType.Writer].Name + "\"!");
            }

            //and path to OGG mux
            ConnectFilters(r_videoTee, VideoTeeOutputName, r_oggMux, "Stream 0", false);

            //path to OGG mux
            ConnectFilters(r_audioTee, AudioTeeOutputName, r_oggMux, "Stream 1", false);

            //configure File Sink / File Writer
            IFileSinkFilter fileSink = (IFileSinkFilter)_fileWriter;
            int             hr       = fileSink.SetFileName(fileName + ".ogm", _emptyAMMediaType);

            if (hr != 0)
            {
                this.CaptureRequiresNewGraph = true;
            }

            DsError.ThrowExceptionForHR(hr);

            StartDVRWriter(_fileWriter);


            ConnectFilters(r_oggMux, "Ogg Stream", _fileWriter, GraphConfig[FilterType.Writer].InPin[0], false);

            CaptureRequiresNewGraph = false;

            this.SaveGraphFile();
        }
Ejemplo n.º 16
0
        void TestFileName()
        {
            int         hr;
            string      fn;
            AMMediaType pmt = new AMMediaType();

            hr = m_ppsink.GetCurFile(out fn, pmt);
            DsError.ThrowExceptionForHR(hr);

            Debug.Assert(fn == FileName, "GetCurFile");
            Debug.Assert(pmt.majorType == MediaType.Stream, "GetCurFile type");

            Marshal.AddRef(pmt.unkPtr);

            hr = m_ppsink.SetFileName(@"c:\foo2.out", pmt);
            DsError.ThrowExceptionForHR(hr);

            hr = m_ppsink.GetCurFile(out fn, pmt);
            DsError.ThrowExceptionForHR(hr);

            Debug.Assert(fn == @"c:\foo2.out", "GetCurFile2");
        }
Ejemplo n.º 17
0
        /// <summary>
        /// Build the graph and connect filters
        /// </summary>
        private void BuildGraph()
        {
            ///Create a graph builder.
            this._graphBuilder = (IGraphBuilder) new FilterGraph();

            ///Create a sample grabber filter. Sample grabber filter provides callback
            ///for application to grab video frames on the fly.
            this._sampleGrabber = (ISampleGrabber) new SampleGrabber();
            ///Configure the sample grabber
            this.ConfigureSampleGrabber(this._sampleGrabber);


            ///Create the file reader filter.
            this._fileReaderFilter = ComGuids.GetFilterFromGuid(ComGuids.FileReaderFilterGuid);
            ///Add the filter to graph. This function only adds filter to graph but
            ///do not connect it
            this._graphBuilder.AddFilter(this._fileReaderFilter, "File Source");

            ///Get source filter, this will let you load an AVI file
            IFileSourceFilter sourceFilter = this._fileReaderFilter as IFileSourceFilter;

            ///Load the file
            sourceFilter.Load(this._srcFile, null);


            ///Create AVI splitter. This filter splits the AVI file into video and audio or other
            ///components that form the video (e.g text)
            this._aviSplitter = ComGuids.GetFilterFromGuid(ComGuids.AviSplitterGuid);
            ///Add the filter to graph
            this._graphBuilder.AddFilter(this._aviSplitter, "AVI Splitter");


            ///Add the sample grabber filter to graph
            this._graphBuilder.AddFilter((IBaseFilter)this._sampleGrabber, "SampleGrabber");


            ///Create AVI mux filter. This filter will combine the audio and video in one stream.
            ///We will use this filter to combine audio and video streams after hiding
            ///data in ISampleGrabber's BufferCB callback.
            this._aviMultiplexer = ComGuids.GetFilterFromGuid(ComGuids.AviMultiplexerGuid);
            ///Add filter to graph
            this._graphBuilder.AddFilter(this._aviMultiplexer, "AVI multiplexer");


            ///Create a file writer filter. This filter will be used to write the AVI stream
            ///to a file
            this._rendererFilter = ComGuids.GetFilterFromGuid(ComGuids.FileWriterFilterGuid);

            ///Add renderer filter to graph
            this._graphBuilder.AddFilter(this._rendererFilter, "File writer");

            ///Get the file sink filter
            IFileSinkFilter sinkFilter = this._rendererFilter as IFileSinkFilter;

            ///Set the output file name
            sinkFilter.SetFileName(this._dcFile, null);


            ///Connect the filter that are added to graph
            DirectShowUtil.ConnectFilters(this._graphBuilder, this._fileReaderFilter, this._aviSplitter);
            DirectShowUtil.ConnectFilters(this._graphBuilder, this._aviSplitter, (IBaseFilter)this._sampleGrabber);
            DirectShowUtil.ConnectFilters(this._graphBuilder, (IBaseFilter)this._sampleGrabber, this._aviMultiplexer);
            DirectShowUtil.ConnectFilters(this._graphBuilder, this._aviMultiplexer, this._rendererFilter);

            IEnumFilters enu = null;

            _graphBuilder.EnumFilters(out enu);

            if (enu != null)
            {
                IBaseFilter[] filters = new IBaseFilter[1];
                while (enu.Next(1, filters, IntPtr.Zero) == 0)
                {
                    FilterInfo info;
                    filters[0].QueryFilterInfo(out info);

                    if (info.achName.Equals("AVI multiplexer", StringComparison.OrdinalIgnoreCase))
                    {
                        IBaseFilter temp = filters[0];
                        IEnumPins   penum;
                        IPin[]      pins = new IPin[1];
                        temp.EnumPins(out penum);
                        while (penum.Next(1, pins, IntPtr.Zero) == 0)
                        {
                            PinDirection    direction;
                            PinInfo         pinfo;
                            FilterInfo      finfo;
                            IEnumMediaTypes enuM;
                            AMMediaType[]   types = new AMMediaType[1];
                            pins[0].QueryDirection(out direction);
                            pins[0].EnumMediaTypes(out enuM);
                            while (enuM.Next(1, types, IntPtr.Zero) == 0)
                            {
                            }
                            pins[0].QueryPinInfo(out pinfo);
                            IBaseFilter pinFilter = pinfo.filter;
                            pinFilter.QueryFilterInfo(out finfo);
                        }
                    }

                    string name = info.achName;
                }
            }
        }
Ejemplo n.º 18
0
        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);
        }
Ejemplo n.º 19
0
        DSStreamResultCodes InitWithStreamBufferFile(WTVStreamingVideoRequest strq)
        {
            // Init variables
            //IPin[] pin = new IPin[1];
            IBaseFilter DecFilterAudio   = null;
            IBaseFilter DecFilterVideo   = null;
            IBaseFilter MainAudioDecoder = null;
            IBaseFilter MainVideoDecoder = null;
            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;

                // Add the DVRMS/WTV file / filter to the graph
                SendDebugMessage("Add SBE Source Filter", 0);

                hr = graphbuilder.AddSourceFilter(fiInputFile.FullName, "SBE Filter", out currentSBEfilter); // class variable
                DsError.ThrowExceptionForHR(hr);
                dc.Add(currentSBEfilter);

                // Get the SBE audio and video out pins
                IPin SBEVidOutPin, SBEAudOutPin;
                SBEAudOutPin = FilterGraphTools.FindPinByMediaType(currentSBEfilter, PinDirection.Output, MediaType.Audio, MediaSubType.Null);
                SBEVidOutPin = FilterGraphTools.FindPinByMediaType(currentSBEfilter, PinDirection.Output, MediaType.Video, MediaSubType.Null);

                // Set up two decrypt filters according to file extension (assume audio and video both present )
                if (fiInputFile.Extension.ToLowerInvariant().Equals(".dvr-ms"))
                {
                    // Add DVR-MS decrypt filters
                    SendDebugMessage("Add DVRMS (bda) decryption", 0);
                    DecFilterAudio = (IBaseFilter) new DTFilter();  // THESE ARE FOR DVR-MS (BDA DTFilters)
                    DecFilterVideo = (IBaseFilter) new DTFilter();
                    graphbuilder.AddFilter(DecFilterAudio, "Decrypt / Tag");
                    graphbuilder.AddFilter(DecFilterVideo, "Decrypt / Tag 0001");
                }
                else  // Add WTV decrypt filters
                {
                    SendDebugMessage("Add WTV (pbda) decryption", 0);
                    DecFilterAudio = FilterDefinition.AddToFilterGraph(FilterDefinitions.Decrypt.DTFilterPBDA, ref graphbuilder);
                    DecFilterVideo = FilterDefinition.AddToFilterGraph(FilterDefinitions.Decrypt.DTFilterPBDA, ref graphbuilder, "PBDA DTFilter 0001");
                }
                dc.Add(DecFilterAudio);
                dc.Add(DecFilterVideo);

                // Make the first link in the graph: SBE => Decrypts
                SendDebugMessage("Connect SBE => Decrypt filters", 0);
                IPin DecVideoInPin = DsFindPin.ByDirection(DecFilterVideo, PinDirection.Input, 0);
                FilterGraphTools.ConnectFilters(graphbuilder, SBEVidOutPin, DecVideoInPin, false);
                IPin DecAudioInPin = DsFindPin.ByDirection(DecFilterAudio, PinDirection.Input, 0);
                if (DecAudioInPin == null)
                {
                    SendDebugMessage("WARNING: No Audio Input to decrypt filter.");
                }
                else
                {
                    FilterGraphTools.ConnectFilters(graphbuilder, SBEAudOutPin, DecAudioInPin, false);
                }

                // Get Dec Audio Out pin
                IPin DecAudioOutPin = DsFindPin.ByDirection(DecFilterAudio, PinDirection.Output, 0);

                // Examine Dec Audio out for audio format
                SendDebugMessage("Examining source audio", 0);
                AMMediaType AudioMediaType = null;
                getPinMediaType(DecAudioOutPin, MediaType.Audio, Guid.Empty, Guid.Empty, ref AudioMediaType);
                SendDebugMessage("Audio media subtype: " + AudioMediaType.subType.ToString());
                SendDebugMessage("Examining Audio StreamInfo");
                StreamInfo si         = FileInformation.GetStreamInfo(AudioMediaType);
                bool       AudioIsAC3 = (si.SimpleType == "AC-3");
                if (AudioIsAC3)
                {
                    SendDebugMessage("Audio type is AC3");
                }
                else
                {
                    SendDebugMessage("Audio type is not AC3");
                }
                si = null;
                DsUtils.FreeAMMediaType(AudioMediaType);

                // Add an appropriate audio decoder
                if (AudioIsAC3)
                {
                    if (!FilterGraphTools.IsThisComObjectInstalled(FilterDefinitions.Audio.AudioDecoderMPCHC.CLSID))
                    {
                        SendDebugMessage("Missing AC3 Audio Decoder, and AC3 audio detected.");
                        return(DSStreamResultCodes.ErrorAC3CodecNotFound);
                    }
                    else
                    {
                        MainAudioDecoder = FilterDefinition.AddToFilterGraph(FilterDefinitions.Audio.AudioDecoderMPCHC, ref graphbuilder);   //MainAudioDecoder = FatAttitude.WTVTranscoder.FilterDefinitions.Audio.AudioDecoderFFDShow.AddToFilterGraph(ref graph);
                        Guid tmpGuid; MainAudioDecoder.GetClassID(out tmpGuid);
                        SendDebugMessage("Main Audio decoder CLSID is " + tmpGuid.ToString());
                    }
                }
                else
                {
                    MainAudioDecoder = FilterDefinition.AddToFilterGraph(FilterDefinitions.Audio.AudioDecoderMSDTV, ref graphbuilder);
                }

                // Add a video decoder
                SendDebugMessage("Add DTV decoder", 0);
                MainVideoDecoder = FilterDefinition.AddToFilterGraph(FilterDefinitions.Video.VideoDecoderMSDTV, ref graphbuilder);
                dc.Add(MainAudioDecoder);
                dc.Add(MainVideoDecoder);

                //SetAudioDecoderOutputToPCMStereo(MainAudioDecoder);

                // Add a null renderer
                SendDebugMessage("Add null renderer", 0);
                NullRenderer MyNullRenderer = new NullRenderer();
                dc.Add(MyNullRenderer);
                hr = graphbuilder.AddFilter((IBaseFilter)MyNullRenderer, @"Null Renderer");
                DsError.ThrowExceptionForHR(hr);

                // Link up video through to null renderer
                SendDebugMessage("Connect video to null renderer", 0);
                // Make the second link:  Decrypts => DTV
                IPin DecVideoOutPin = DsFindPin.ByDirection(DecFilterVideo, PinDirection.Output, 0);
                IPin DTVVideoInPin  = DsFindPin.ByName(MainVideoDecoder, @"Video Input"); // IPin DTVVideoInPin = DsFindPin.ByDirection(DTVVideoDecoder, PinDirection.Input, 0);  // first one should be video input?  //
                FilterGraphTools.ConnectFilters(graphbuilder, DecVideoOutPin, DTVVideoInPin, false);
                // 3. DTV => Null renderer
                IPin NullRInPin     = DsFindPin.ByDirection((IBaseFilter)MyNullRenderer, PinDirection.Input, 0);
                IPin DTVVideoOutPin = FilterGraphTools.FindPinByMediaType(MainVideoDecoder, PinDirection.Output, MediaType.Video, MediaSubType.Null);
                FilterGraphTools.ConnectFilters(graphbuilder, DTVVideoOutPin, NullRInPin, false);
                Marshal.ReleaseComObject(NullRInPin); NullRInPin = 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());
                DsError.ThrowExceptionForHR(tempControl.Run());
                EventCode pEventCode;
                hr = tempEvent.WaitForCompletion(1000, out pEventCode);
                //DsError.ThrowExceptionForHR(hr);  // DO *NOT* DO THIS HERE!  THERE MAY WELL BE AN ERROR DUE TO EVENTS RAISED BY THE STREAM BUFFER ENGINE, THIS IS A DELIBERATE TEST RUN OF THE GRAPH
                // Stop graph if necessary
                FilterState pFS;
                hr = tempControl.GetState(1000, out pFS);
                if (pFS == FilterState.Running)
                {
                    DsError.ThrowExceptionForHR(tempControl.Stop());
                }

                // Remove null renderer
                hr = graphbuilder.RemoveFilter((IBaseFilter)MyNullRenderer);

                // Now graph has been run and stopped we can get the video width and height from the output pin of the main video decoder
                AMMediaType pmt = null;
                getPinMediaType(DTVVideoOutPin, MediaType.Video, MediaSubType.YUY2, Guid.Empty, ref pmt);
                FrameSize SourceFrameSize;
                if (pmt.formatType == FormatType.VideoInfo2)
                {
                    VideoInfoHeader2 pvih2 = new VideoInfoHeader2();
                    Marshal.PtrToStructure(pmt.formatPtr, pvih2);
                    int VideoWidth  = pvih2.BmiHeader.Width;
                    int VideoHeight = pvih2.BmiHeader.Height;
                    SourceFrameSize = new FrameSize(VideoWidth, VideoHeight);
                }
                else
                {
                    SourceFrameSize = new FrameSize(320, 240);
                }

                // Free up
                DsUtils.FreeAMMediaType(pmt); pmt = null;

                // Link up audio
                // 2. Audio Decrypt -> Audio decoder
                IPin MainAudioInPin = DsFindPin.ByDirection(MainAudioDecoder, PinDirection.Input, 0);
                FilterGraphTools.ConnectFilters(graphbuilder, DecAudioOutPin, MainAudioInPin, false);

                // Add ASF Writer
                // 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
                IFileSinkFilter sinkFilter = (IFileSinkFilter)asf_filter;
                string          destPathFN = fiInputFile.FullName + ".wmv";
                hr = sinkFilter.SetFileName(destPathFN, null);
                DsError.ThrowExceptionForHR(hr);

                // Make the final links:  DTV => writer
                SendDebugMessage("Linking audio/video through to decoder and writer", 0);
                IPin DTVAudioOutPin   = DsFindPin.ByDirection(MainAudioDecoder, PinDirection.Output, 0);
                IPin ASFAudioInputPin = FilterGraphTools.FindPinByMediaType((IBaseFilter)asf_filter, PinDirection.Input, MediaType.Audio, MediaSubType.Null);
                IPin ASFVideoInputPin = FilterGraphTools.FindPinByMediaType((IBaseFilter)asf_filter, PinDirection.Input, MediaType.Video, MediaSubType.Null);
                FilterGraphTools.ConnectFilters(graphbuilder, DTVAudioOutPin, ASFAudioInputPin, false);
                if (ASFVideoInputPin != null)
                {
                    FilterGraphTools.ConnectFilters(graphbuilder, DTVVideoOutPin, ASFVideoInputPin, false);
                }

                // Configure ASFWriter
                ConfigureASFWriter(asf_filter, strq, SourceFrameSize);

                // Release pins
                SendDebugMessage("Releasing COM objects (pins)", 0);
                // dec
                Marshal.ReleaseComObject(DecAudioInPin); DecAudioInPin   = null;
                Marshal.ReleaseComObject(DecVideoInPin); DecVideoInPin   = null;
                Marshal.ReleaseComObject(DecVideoOutPin); DecVideoOutPin = null;
                Marshal.ReleaseComObject(DecAudioOutPin); DecAudioOutPin = null;
                // dtv
                Marshal.ReleaseComObject(MainAudioInPin); MainAudioInPin = null;
                Marshal.ReleaseComObject(DTVVideoInPin); DTVVideoInPin   = null;
                Marshal.ReleaseComObject(DTVVideoOutPin); DTVVideoOutPin = null;
                Marshal.ReleaseComObject(DTVAudioOutPin); DTVAudioOutPin = null;
                // asf
                Marshal.ReleaseComObject(ASFAudioInputPin); ASFAudioInputPin = null;
                Marshal.ReleaseComObject(ASFVideoInputPin); ASFVideoInputPin = null;
            }
            catch (Exception ex)
            {
                SendDebugMessageWithException(ex.Message, ex);
                return(DSStreamResultCodes.ErrorExceptionOccurred);
            }

            return(DSStreamResultCodes.OK);
        }
Ejemplo n.º 20
0
        public void SetupGraph()
        {
            GraphBuilder = (IGraphBuilder) new FilterGraph();

            // Get ICaptureGraphBuilder2 to build the graph
            CaptureGraphBuilder2 = new CaptureGraphBuilder2() as ICaptureGraphBuilder2;

            try
            {
                ReturnHR = CaptureGraphBuilder2.SetFiltergraph(GraphBuilder);

                IBaseFilter source_filter = null;

                ReturnHR = GraphBuilder.AddSourceFilter(InputFile, "Source Filter", out source_filter);

                IBaseFilter       wmv_video_decoder_dmo = (IBaseFilter) new DMOWrapperFilter();
                IDMOWrapperFilter dmo_wrapper_filter_v  = (IDMOWrapperFilter)wmv_video_decoder_dmo;

                ReturnHR = dmo_wrapper_filter_v.Init(new Guid("{82D353DF-90BD-4382-8BC2-3F6192B76E34}"), DMOCategory.VideoDecoder);
                ReturnHR = GraphBuilder.AddFilter(wmv_video_decoder_dmo, "Wmv Video Decoder DMO");

                IBaseFilter       wmv_audio_decoder_dmo = (IBaseFilter) new DMOWrapperFilter();
                IDMOWrapperFilter dmo_wrapper_filter_a  = (IDMOWrapperFilter)wmv_audio_decoder_dmo;

                ReturnHR = dmo_wrapper_filter_a.Init(new Guid("{2EEB4ADF-4578-4D10-BCA7-BB955F56320A}"), DMOCategory.AudioDecoder);
                ReturnHR = GraphBuilder.AddFilter(wmv_audio_decoder_dmo, "Wmv Audio Decoder DMO");

                IBaseFilter vp8_encoder = (IBaseFilter) new VP8Encoder();
                ReturnHR = GraphBuilder.AddFilter(vp8_encoder, "VP8 Encoder");

                IVP8Encoder vp8_encoder_interface = (IVP8Encoder)vp8_encoder;
                if (target_bitrate != 0)
                {
                    vp8_encoder_interface.SetTargetBitrate(target_bitrate);
                }

                IBaseFilter webm_muxer = (IBaseFilter) new WebMMuxer();
                ReturnHR = GraphBuilder.AddFilter(webm_muxer, "WebM Muxer");

                IBaseFilter vorbis_encoder = (IBaseFilter) new VorbisEncoder();
                ReturnHR = GraphBuilder.AddFilter(vorbis_encoder, "Vorbis Encoder");

                IBaseFilter file_writer = (IBaseFilter) new FileWriter();
                ReturnHR = GraphBuilder.AddFilter(file_writer, "file writer");
                IFileSinkFilter filewriter_sink = file_writer as IFileSinkFilter;
                ReturnHR = filewriter_sink.SetFileName(OutputFile, null);

                ReturnHR = GraphBuilder.ConnectDirect(FindPin("Raw Video 1", source_filter), FindPin("in0", wmv_video_decoder_dmo), null);
                ReturnHR = GraphBuilder.ConnectDirect(FindPin("Raw Audio 0", source_filter), FindPin("in0", wmv_audio_decoder_dmo), null);
                ReturnHR = GraphBuilder.ConnectDirect(FindPin("out0", wmv_audio_decoder_dmo), FindPin("PCM In", vorbis_encoder), null);
                ReturnHR = GraphBuilder.ConnectDirect(FindPin("out0", wmv_video_decoder_dmo), FindPin("YUV", vp8_encoder), null);
                ReturnHR = GraphBuilder.ConnectDirect(FindPin("Vorbis Out", vorbis_encoder), FindPin("audio", webm_muxer), null);
                ReturnHR = GraphBuilder.ConnectDirect(FindPin("VP80", vp8_encoder), FindPin("video", webm_muxer), null);
                ReturnHR = GraphBuilder.ConnectDirect(FindPin("outpin", webm_muxer), FindPin("in", file_writer), null);
            }
            catch (Exception)
            {
                LogError("Failed to initialize FilterGraph.");
            }
            finally
            {
                if (CaptureGraphBuilder2 != null)
                {
                    Marshal.ReleaseComObject(CaptureGraphBuilder2);
                    CaptureGraphBuilder2 = null;
                }
            }
        }
Ejemplo n.º 21
0
        public void Init(Hashtable config = null)
        {
            //m_FilterGraph = (IFilterGraph2)new FilterGraph();
            m_FilterGraph = (IGraphBuilder)Activator.CreateInstance(Type.GetTypeFromCLSID(Clsid.FilterGraph, true));

            // Get the ICaptureGraphBuilder2
            Guid clsid = Clsid.CaptureGraphBuilder2;
            Guid riid  = typeof(ICaptureGraphBuilder2).GUID;
            ICaptureGraphBuilder2 capGraph        = (ICaptureGraphBuilder2)DsBugWO.CreateDsInstance(ref clsid, ref riid);
            IBaseFilter           capVideoFilter  = null;
            IBaseFilter           capAudioFilter  = null;
            IBaseFilter           asfWriter       = null;
            IServiceProvider      serviceProvider = null;
            int    hr;
            object iwmWriter2;

            try
            {
                // Start building the graph
                hr = capGraph.SetFiltergraph(m_FilterGraph);
                Marshal.ThrowExceptionForHR(hr);

                // Add the video device to the graph
                if (videoDevChosen != null)
                {
                    capVideoFilter = GetCapFilter(ref videoDevChosen);
                    hr             = m_FilterGraph.AddFilter(capVideoFilter, "Video Capture Device");
                    Marshal.ThrowExceptionForHR(hr);
                }

                // Add the audio device to the graph
                if (audioDevChosen != null)
                {
                    capAudioFilter = GetCapFilter(ref audioDevChosen);
                    hr             = m_FilterGraph.AddFilter(capAudioFilter, "Audio Capture Device");
                    Marshal.ThrowExceptionForHR(hr);
                }
                // if we need some shitty quality
                if (config.Contains("shitty"))
                {
                    InitAsfWriter(out asfWriter, true);
                }
                else
                {
                    InitAsfWriter(out asfWriter);
                }


                //GEtting IWMAdvancedWriter2;
                serviceProvider = (IServiceProvider)asfWriter;
                Guid IID_IWMWriterAdvanced2 = new Guid("{962dc1ec-c046-4db8-9cc7-26ceae500817}");
                hr = serviceProvider.QueryService(IID_IWMWriterAdvanced2, IID_IWMWriterAdvanced2, out iwmWriter2);
                Marshal.ThrowExceptionForHR(hr);

                m_writerAdvanced2 = (IWMWriterAdvanced2)iwmWriter2;
                m_writerAdvanced2.SetLiveSource(true);

                if (config.ContainsKey("cap"))
                {
                    outputFilename = config["cap"] as string;
                    Console.WriteLine("[MODE] Capturing to a local file: {0}", outputFilename);
                }
                IFileSinkFilter cap = (IFileSinkFilter)asfWriter;
                cap.SetFileName(outputFilename, null);

                if (!config.ContainsKey("cap"))
                {
                    //deleting useless sink (writer to a file on a disk).
                    IWMWriterSink uselessSink = null;
                    m_writerAdvanced2.GetSink(0, out uselessSink);
                    m_writerAdvanced2.RemoveSink(uselessSink);
                    if (uselessSink != null)
                    {
                        Marshal.ReleaseComObject(uselessSink);
                        uselessSink = null;
                    }
                }

                if (config.Contains("send"))
                {
                    string url = config["send"] as string;
                    Console.WriteLine("[MODE] Streaming to a remote server: {0}", url);
                    WriterNetworkSink sender = new WriterNetworkSink(url);
                    m_writerAdvanced2.AddSink(sender);
                }
                if (config.Contains("share"))
                {
                    int port = (int)config["share"];
                    WriterNetworkSink listener = new WriterNetworkSink(port);
                    Console.WriteLine("[MODE] Started listening on port {0}", port);
                    m_writerAdvanced2.AddSink(listener);
                }
                //Connecting VideoDev to asfWriter
                if (videoDevChosen != null)
                {
                    hr = capGraph.RenderStream(PinCategory.Capture, MediaType.Video, capVideoFilter, null, asfWriter);
                    //hr = capGraph.RenderStream(null, null, capVideoFilter, null, asfWriter);
                    Marshal.ThrowExceptionForHR(hr);
                }
                //Connecting AudioDev to asfWriter
                if (audioDevChosen != null)
                {
                    hr = capGraph.RenderStream(PinCategory.Capture, MediaType.Audio, capAudioFilter, null, asfWriter);
                    //hr = capGraph.RenderStream(null, null, capAudioFilter, null, asfWriter);
                    Marshal.ThrowExceptionForHR(hr);
                }
                m_mediaCtrl = m_FilterGraph as IMediaControl;
                //debug, dumps graph
                //DirectShowLib.Utils.FilterGraphTools.SaveGraphFile(m_FilterGraph, ".\\mygraph.grf");
            }
            finally
            {
                if (capVideoFilter != null)
                {
                    Marshal.ReleaseComObject(capVideoFilter);
                    capVideoFilter = null;
                }
                if (capAudioFilter != null)
                {
                    Marshal.ReleaseComObject(capAudioFilter);
                    capAudioFilter = null;
                }
                if (asfWriter != null)
                {
                    Marshal.ReleaseComObject(asfWriter);
                    asfWriter = null;
                }
                if (capGraph != null)
                {
                    Marshal.ReleaseComObject(capGraph);
                    capGraph = null;
                }
                if (serviceProvider != null)
                {
                    Marshal.ReleaseComObject(serviceProvider);
                    serviceProvider = null;
                }
            }
            Console.WriteLine("INIT done");
        }
Ejemplo n.º 22
0
        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.ToLowerInvariant() != ".dvr-ms" && ext.ToLowerInvariant() != ".sbe")
            {
                return(false);
            }

            //Type comtype = null;
            //object comobj = null;
            try
            {
                Log.Info("DVR2MPG: create graph");
                graphBuilder = (IGraphBuilder) new FilterGraph();

                _rotEntry = new DsROTEntry((IFilterGraph)graphBuilder);

                Log.Info("DVR2MPG: add streambuffersource");
                bufferSource = (IStreamBufferSource) new StreamBufferSource();


                IBaseFilter filter = (IBaseFilter)bufferSource;
                graphBuilder.AddFilter(filter, "SBE SOURCE");

                Log.Info("DVR2MPG: load file:{0}", info.file);
                IFileSourceFilter fileSource = (IFileSourceFilter)bufferSource;
                int hr = fileSource.Load(info.file, null);


                Log.Info("DVR2MPG: Add Cyberlink MPEG2 multiplexer to graph");
                string monikerPowerDvdMuxer =
                    @"@device:sw:{083863F1-70DE-11D0-BD40-00A0C911CE86}\{7F2BBEAF-E11C-4D39-90E8-938FB5A86045}";
                powerDvdMuxer = Marshal.BindToMoniker(monikerPowerDvdMuxer) as IBaseFilter;
                if (powerDvdMuxer == null)
                {
                    Log.Warn("DVR2MPG: FAILED:Unable to create Cyberlink MPEG Muxer (PowerDVD)");
                    Cleanup();
                    return(false);
                }

                hr = graphBuilder.AddFilter(powerDvdMuxer, "PDR MPEG Muxer");
                if (hr != 0)
                {
                    Log.Warn("DVR2MPG: FAILED:Add Cyberlink MPEG Muxer to filtergraph :0x{0:X}", hr);
                    Cleanup();
                    return(false);
                }

                //add filewriter
                Log.Info("DVR2MPG: Add FileWriter to graph");
                string monikerFileWrite =
                    @"@device:sw:{083863F1-70DE-11D0-BD40-00A0C911CE86}\{3E8868CB-5FE8-402C-AA90-CB1AC6AE3240}";
                IBaseFilter fileWriterbase = Marshal.BindToMoniker(monikerFileWrite) as IBaseFilter;
                if (fileWriterbase == null)
                {
                    Log.Warn("DVR2MPG: FAILED:Unable to create FileWriter");
                    Cleanup();
                    return(false);
                }


                fileWriterFilter = fileWriterbase as IFileSinkFilter;
                if (fileWriterFilter == null)
                {
                    Log.Warn("DVR2MPG: FAILED:Add unable to get IFileSinkFilter for filewriter");
                    Cleanup();
                    return(false);
                }

                hr = graphBuilder.AddFilter(fileWriterbase, "FileWriter");
                if (hr != 0)
                {
                    Log.Warn("DVR2MPG: FAILED:Add FileWriter to filtergraph :0x{0:X}", hr);
                    Cleanup();
                    return(false);
                }


                //connect output #0 of streambuffer source->powerdvd audio in
                //connect output #1 of streambuffer source->powerdvd video in
                Log.Info("DVR2MPG: connect streambuffer->multiplexer");
                IPin pinOut0, pinOut1;
                IPin pinIn0, pinIn1;
                pinOut0 = DsFindPin.ByDirection((IBaseFilter)bufferSource, PinDirection.Output, 0);
                pinOut1 = DsFindPin.ByDirection((IBaseFilter)bufferSource, PinDirection.Output, 1);

                pinIn0 = DsFindPin.ByDirection(powerDvdMuxer, PinDirection.Input, 0);
                pinIn1 = DsFindPin.ByDirection(powerDvdMuxer, PinDirection.Input, 1);
                if (pinOut0 == null || pinOut1 == null || pinIn0 == null || pinIn1 == null)
                {
                    Log.Warn("DVR2MPG: FAILED:unable to get pins of muxer&source");
                    Cleanup();
                    return(false);
                }

                bool        usingAc3 = false;
                AMMediaType amAudio  = new AMMediaType();
                amAudio.majorType = MediaType.Audio;
                amAudio.subType   = MediaSubType.Mpeg2Audio;
                hr = pinOut0.Connect(pinIn1, amAudio);
                if (hr != 0)
                {
                    amAudio.subType = MediaSubType.DolbyAC3;
                    hr       = pinOut0.Connect(pinIn1, amAudio);
                    usingAc3 = true;
                }
                if (hr != 0)
                {
                    Log.Warn("DVR2MPG: FAILED: unable to connect audio pins: 0x{0:X}", hr);
                    Cleanup();
                    return(false);
                }

                if (usingAc3)
                {
                    Log.Info("DVR2MPG: using AC3 audio");
                }
                else
                {
                    Log.Info("DVR2MPG: using MPEG audio");
                }

                AMMediaType amVideo = new AMMediaType();
                amVideo.majorType = MediaType.Video;
                amVideo.subType   = MediaSubType.Mpeg2Video;
                hr = pinOut1.Connect(pinIn0, amVideo);
                if (hr != 0)
                {
                    Log.Warn("DVR2MPG: FAILED: unable to connect video pins: 0x{0:X}", hr);
                    Cleanup();
                    return(false);
                }


                //connect output of powerdvd muxer->input of filewriter
                Log.Info("DVR2MPG: connect multiplexer->filewriter");
                IPin pinOut, pinIn;
                pinOut = DsFindPin.ByDirection(powerDvdMuxer, PinDirection.Output, 0);
                if (pinOut == null)
                {
                    Log.Warn("DVR2MPG: FAILED:cannot get output pin of Cyberlink MPEG muxer :0x{0:X}", hr);
                    Cleanup();
                    return(false);
                }
                pinIn = DsFindPin.ByDirection(fileWriterbase, PinDirection.Input, 0);
                if (pinIn == null)
                {
                    Log.Warn("DVR2MPG: FAILED:cannot get input pin of Filewriter :0x{0:X}", hr);
                    Cleanup();
                    return(false);
                }
                AMMediaType mt = new AMMediaType();
                hr = pinOut.Connect(pinIn, mt);
                if (hr != 0)
                {
                    Log.Warn("DVR2MPG: FAILED:connect muxer->filewriter :0x{0:X}", hr);
                    Cleanup();
                    return(false);
                }

                //set output filename
                string outputFileName = System.IO.Path.ChangeExtension(info.file, ".mpg");
                Log.Info("DVR2MPG: set output file to :{0}", outputFileName);
                mt.majorType = MediaType.Stream;
                mt.subType   = MediaSubTypeEx.MPEG2;

                hr = fileWriterFilter.SetFileName(outputFileName, mt);
                if (hr != 0)
                {
                    Log.Warn("DVR2MPG: FAILED:unable to set filename for filewriter :0x{0:X}", hr);
                    Cleanup();
                    return(false);
                }
                mediaControl = graphBuilder as IMediaControl;
                mediaSeeking = graphBuilder as IMediaSeeking;
                mediaEvt     = graphBuilder as IMediaEventEx;
                Log.Info("DVR2MPG: start transcoding");
                hr = mediaControl.Run();
                if (hr != 0)
                {
                    Log.Warn("DVR2MPG: FAILED:unable to start graph :0x{0:X}", hr);
                    Cleanup();
                    return(false);
                }
            }
            catch (Exception ex)
            {
                Log.Error("DVR2MPG: Unable create graph: {0}", ex.Message);
                Cleanup();
                return(false);
            }
            return(true);
        }
Ejemplo n.º 23
0
        public void convert(object obj)
        {
            string[] pair       = obj as string[];
            string   srcfile    = pair[0];
            string   targetfile = pair[1];
            int      hr;

            ibfSrcFile = (IBaseFilter) new AsyncReader();
            hr         = gb.AddFilter(ibfSrcFile, "Reader");
            DsError.ThrowExceptionForHR(hr);
            IFileSourceFilter ifileSource = (IFileSourceFilter)ibfSrcFile;

            hr = ifileSource.Load(srcfile, null);
            DsError.ThrowExceptionForHR(hr);
            // the guid is the one from ffdshow
            Type   fftype  = Type.GetTypeFromCLSID(new Guid("0F40E1E5-4F79-4988-B1A9-CC98794E6B55"));
            object ffdshow = Activator.CreateInstance(fftype);

            hr = gb.AddFilter((IBaseFilter)ffdshow, "ffdshow");
            DsError.ThrowExceptionForHR(hr);
            // the guid is the one from the WAV Dest sample in the SDK
            Type   type     = Type.GetTypeFromCLSID(new Guid("3C78B8E2-6C4D-11d1-ADE2-0000F8754B99"));
            object wavedest = Activator.CreateInstance(type);

            hr = gb.AddFilter((IBaseFilter)wavedest, "WAV Dest");
            DsError.ThrowExceptionForHR(hr);
            // manually tell the graph builder to try to hook up the pin that is left
            IPin pWaveDestOut = null;

            hr = icgb.FindPin(wavedest, PinDirection.Output, null, null, true, 0, out pWaveDestOut);
            DsError.ThrowExceptionForHR(hr);
            // render step 1
            hr = icgb.RenderStream(null, null, ibfSrcFile, (IBaseFilter)ffdshow, (IBaseFilter)wavedest);
            DsError.ThrowExceptionForHR(hr);
            // Configure the sample grabber
            IBaseFilter baseGrabFlt = sg as IBaseFilter;

            ConfigSampleGrabber(sg);
            IPin pGrabberIn  = DsFindPin.ByDirection(baseGrabFlt, PinDirection.Input, 0);
            IPin pGrabberOut = DsFindPin.ByDirection(baseGrabFlt, PinDirection.Output, 0);

            hr = gb.AddFilter((IBaseFilter)sg, "SampleGrabber");
            DsError.ThrowExceptionForHR(hr);
            AMMediaType mediatype = new AMMediaType();

            sg.GetConnectedMediaType(mediatype);
            hr = gb.Connect(pWaveDestOut, pGrabberIn);
            DsError.ThrowExceptionForHR(hr);
            // file writer
            FileWriter      file_writer = new FileWriter();
            IFileSinkFilter fs          = (IFileSinkFilter)file_writer;

            fs.SetFileName(targetfile, null);
            hr = gb.AddFilter((DirectShowLib.IBaseFilter)file_writer, "File Writer");
            DsError.ThrowExceptionForHR(hr);
            // render step 2
            AMMediaType mediatype2 = new AMMediaType();

            pWaveDestOut.ConnectionMediaType(mediatype2);
            gb.Render(pGrabberOut);
            // alternatively to the file writer use the NullRenderer() to just discard the rest
            // assign control
            m_mediaCtrl = gb as IMediaControl;
            // run
            hr = m_mediaCtrl.Run();
            DsError.ThrowExceptionForHR(hr);
        }
Ejemplo n.º 24
0
        static void BuildGraph(IGraphBuilder pGraph, string dstFile1)
        {
            int hr = 0;
            //graph builder
            ICaptureGraphBuilder2 pBuilder = (ICaptureGraphBuilder2) new CaptureGraphBuilder2();

            hr = pBuilder.SetFiltergraph(pGraph); checkHR(hr, "Can't SetFiltergraph");
            Guid CLSID_GenericNetworkProvider = new Guid("{B2F3A67C-29DA-4C78-8831-091ED509A475}");             //MSNP.ax

            Guid CLSID_AVerMediaBDADVBSTuner              = new Guid("{17CCA71B-ECD7-11D0-B908-00A0C9223196}"); //ksproxy.ax
            Guid CLSID_AVerMediaBDADigitalCapture         = new Guid("{17CCA71B-ECD7-11D0-B908-00A0C9223196}"); //ksproxy.ax
            Guid CLSID_MPEG2SectionsandTables             = new Guid("{C666E115-BB62-4027-A113-82D643FE2D99}"); //Mpeg2Data.ax
            Guid CLSID_BDAMPEG2TransportInformationFilter = new Guid("{FC772AB0-0C7F-11D3-8FF2-00A0C9224CF4}"); //psisrndr.ax
            Guid CLSID_MicrosoftDTVDVDAudioDecoder        = new Guid("{E1F1A0B8-BEEE-490D-BA7C-066C40B5E2B9}"); //msmpeg2adec.d11

            Guid CLSID_MicrosoftDTVDVDVideoDecoder = new Guid("{212690FB-83E5-4526-8FD7-74478B7939CD}");        //msmpeg2vdec.d11

            IBaseFilter pMicrosoftDTVDVDAudioDecoder2 = (IBaseFilter)Activator.CreateInstance(Type.GetTypeFromCLSID(CLSID_MicrosoftDTVDVDAudioDecoder));

            hr = pGraph.AddFilter(pMicrosoftDTVDVDAudioDecoder2, "Microsoft DTV-DVD Audio Decoder"); checkHR(hr, "Can't add Microsoft DTV-DVD Audio Decoder to graph");

            //add Generic Network Provider
            IBaseFilter pGenericNetworkProvider = (IBaseFilter)Activator.CreateInstance(Type.GetTypeFromCLSID(CLSID_GenericNetworkProvider));

            hr = pGraph.AddFilter(pGenericNetworkProvider, "Generic Network Provider");
            checkHR(hr, "Can't add Generic Network Provider to graph");
            //add AVerMedia BDA DVBS Tuner
            IBaseFilter pAVerMediaBDADVBSTuner = (IBaseFilter)Activator.CreateInstance(Type.GetTypeFromCLSID(CLSID_AVerMediaBDADVBSTuner));

            hr = pGraph.AddFilter(pAVerMediaBDADVBSTuner, "AVerMedia BDA DVBS Tuner"); checkHR(hr, "Can't add AVerMedia BDA DVBS Tuner to graph");
            //connect Generic Network Provider and AVerMedia BDA DVBS Tuner
            hr = pGraph.ConnectDirect(GetPin(pGenericNetworkProvider, "Antenna Out"), GetPin(pAVerMediaBDADVBSTuner, "Input0"), null);
            checkHR(hr, "Can't connect Generic Network Provider and AVerMedia BDA DVBS Tuner");
            //add AVerMedia BDA Digital Capture
            IBaseFilter pAVerMediaBDADigitalCapture = (IBaseFilter)Activator.CreateInstance(Type.GetTypeFromCLSID(CLSID_AVerMediaBDADigitalCapture));

            hr = pGraph.AddFilter(pAVerMediaBDADigitalCapture, "AVerMedia BDA Digital Capture"); checkHR(hr, "Can't add AVerMedia BDA Digital Capture to graph");
            //connect AVerMedia BDA DVBS Tuner and AVerMedia BDA Digital Capture
            hr = pGraph.ConnectDirect(GetPin(pAVerMediaBDADVBSTuner, "MPEG2 Transport"), GetPin(pAVerMediaBDADigitalCapture, "MPEG2 Transport"), null); checkHR(hr, "Can't connect AVerMedia BDA DVBS Tuner and AVerMedia BDA Digital Capture");
            //add MPEG-2 Demultiplexer
            IBaseFilter pMPEG2Demultiplexer = (IBaseFilter) new MPEG2Demultiplexer();

            hr = pGraph.AddFilter(pMPEG2Demultiplexer, "MPEG-2 Demultiplexer");
            checkHR(hr, "Can't add MPEG-2 Demultiplexer to graph");
            //connect AVerMedia BDA Digital Capture and MPEG-2 Demultiplexer
            hr = pGraph.ConnectDirect(GetPin(pAVerMediaBDADigitalCapture, "MPEG2 Transport"), GetPin(pMPEG2Demultiplexer, "MPEG-2 Stream"), null);
            checkHR(hr, "Can't connect AVerMedia BDA Digital Capture and MPEG-2 Demultiplexer");
            //add MPEG-2 Sections and Tables
            IBaseFilter pMPEG2SectionsandTables = (IBaseFilter)Activator.CreateInstance(Type.GetTypeFromCLSID(CLSID_MPEG2SectionsandTables));

            hr = pGraph.AddFilter(pMPEG2SectionsandTables, "MPEG-2 Sections and Tables");
            checkHR(hr, "Can't add MPEG-2 Sections and Tables to graph");
            //add BDA MPEG2 Transport Information Filter
            IBaseFilter pBDAMPEG2TransportInformationFilter = (IBaseFilter)Activator.CreateInstance(Type.GetTypeFromCLSID(CLSID_BDAMPEG2TransportInformationFilter));

            hr = pGraph.AddFilter(pBDAMPEG2TransportInformationFilter, "BDA MPEG2 Transport Information Filter"); checkHR(hr, "Can't add BDA MPEG2 Transport Information Filter to graph");
            //connect MPEG-2 Demultiplexer and BDA MPEG2 Transport Information Filter
            hr = pGraph.ConnectDirect(GetPin(pMPEG2Demultiplexer, "001"), GetPin(pBDAMPEG2TransportInformationFilter, "IB Input"), null);
            checkHR(hr, "Can't connect MPEG-2 Demultiplexer and BDA MPEG2 Transport Information Filter");
            //connect MPEG-2 Demultiplexer and MPEG-2 Sections and Tables
            hr = pGraph.ConnectDirect(GetPin(pMPEG2Demultiplexer, "002"), GetPin(pMPEG2SectionsandTables, "In"), null);
            checkHR(hr, "Can't connect MPEG-2 Demultiplexer and MPEG-2 Sections and Tables");



            //add Microsoft DTV-DVD Audio Decoder
            IBaseFilter pMicrosoftDTVDVDAudioDecoder = (IBaseFilter)Activator.CreateInstance(Type.GetTypeFromCLSID(CLSID_MicrosoftDTVDVDAudioDecoder));

            hr = pGraph.AddFilter(pMicrosoftDTVDVDAudioDecoder, "Microsoft DTV-DVD Audio Decoder"); checkHR(hr, "Can't add Microsoft DTV-DVD Audio Decoder to graph");

            //connect MPEG-2 Demultiplexer and Microsoft DTV-DVD Audio Decoder
            hr = pGraph.ConnectDirect(GetPin(pMPEG2Demultiplexer, "007"), GetPin(pMicrosoftDTVDVDAudioDecoder, "XForm In"), null);
            checkHR(hr, "Can't connect MPEG-2 Demultiplexer and Microsoft DTV-DVD Audio Decoder");

            //add WM ASF Writer
            IBaseFilter pWMASFWriter = (IBaseFilter) new WMAsfWriter();

            hr = pGraph.AddFilter(pWMASFWriter, "WM ASF Writer");
            checkHR(hr, "Can't add WM ASF Writer to graph");
            //set destination filename
            IFileSinkFilter pWMASFWriter_sink = pWMASFWriter as IFileSinkFilter;

            if (pWMASFWriter_sink == null)
            {
                checkHR(unchecked ((int)0x80004002), "Can't get IFileSinkFilter");
            }
            hr = pWMASFWriter_sink.SetFileName(dstFile1, null);
            checkHR(hr, "Can'i set filename");
            //connect Microsoft DTV-DVD Audio Decoder and WM ASF Writer
            hr = pGraph.ConnectDirect(GetPin(pMicrosoftDTVDVDAudioDecoder, "XFrom Out"), GetPin(pWMASFWriter, "Audio Input 01"), null);
            checkHR(hr, "Can't connect Microsoft DTV-DVD Audio Decoder and WM ASF Writer");
            //add Microsoft DTV-DVD Video Decoder
            IBaseFilter pMicrosoftDTVDVDVideoDecoder = (IBaseFilter)Activator.CreateInstance(Type.GetTypeFromCLSID(CLSID_MicrosoftDTVDVDVideoDecoder));

            hr = pGraph.AddFilter(pMicrosoftDTVDVDVideoDecoder, "Microsoft DTV-DVD Video Decoder"); checkHR(hr, "Can't add Microsoft DTV-DVD Video Decoder to graph");
            //connect MPEG-2 Demultiplexer and Microsoft DTV-DVD Video Decoder
            hr = pGraph.ConnectDirect(GetPin(pMPEG2Demultiplexer, "006"), GetPin(pMicrosoftDTVDVDVideoDecoder, "Video Input"), null);
            checkHR(hr, "Can't connect MPEG-2 Demultiplexer and Microsoft DTV-DVD Video Decoder");
            //connect Microsoft DTV-DVD Video Decoder and WM ASF Writer
            hr = pGraph.ConnectDirect(GetPin(pMicrosoftDTVDVDVideoDecoder, "Video Output 1"), GetPin(pWMASFWriter, "Video Input 01"), null);
            checkHR(hr, "Can't connect Microsoft DTV-DVD Video Decoder and WM ASF Writer");
        }
        //
        // 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";
            }
        }
Ejemplo n.º 26
0
        private void SetSaveFile(string filename)
        {
            fileDump = FilterGraphTools.FindFilterByName(graphBuilder, dumpFilterName);
            if (object.Equals(fileDump, null))
                throw new System.Exception("Couldn't find dump filter in filter graph: " + dumpFilterName);


            sink = fileDump as IFileSinkFilter;

            AMMediaType media = new AMMediaType();
            media.majorType = MediaType.Video;
            media.subType = MediaSubType.Mpeg2Transport;
            media.formatType = FormatType.VideoInfo;


            int hr = sink.SetFileName(filename, media);
            DsError.ThrowExceptionForHR(hr);
        }
Ejemplo n.º 27
0
    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") return false;

      //Type comtype = null;
      //object comobj = null;
      try
      {
        Log.Info("DVR2MPG: create graph");
        graphBuilder = (IGraphBuilder)new FilterGraph();

        _rotEntry = new DsROTEntry((IFilterGraph)graphBuilder);

        Log.Info("DVR2MPG: add streambuffersource");
        bufferSource = (IStreamBufferSource)new StreamBufferSource();


        IBaseFilter filter = (IBaseFilter)bufferSource;
        graphBuilder.AddFilter(filter, "SBE SOURCE");

        Log.Info("DVR2MPG: load file:{0}", info.file);
        IFileSourceFilter fileSource = (IFileSourceFilter)bufferSource;
        int hr = fileSource.Load(info.file, null);


        Log.Info("DVR2MPG: Add Cyberlink MPEG2 multiplexer to graph");
        string monikerPowerDvdMuxer =
          @"@device:sw:{083863F1-70DE-11D0-BD40-00A0C911CE86}\{7F2BBEAF-E11C-4D39-90E8-938FB5A86045}";
        powerDvdMuxer = Marshal.BindToMoniker(monikerPowerDvdMuxer) as IBaseFilter;
        if (powerDvdMuxer == null)
        {
          Log.Warn("DVR2MPG: FAILED:Unable to create Cyberlink MPEG Muxer (PowerDVD)");
          Cleanup();
          return false;
        }

        hr = graphBuilder.AddFilter(powerDvdMuxer, "PDR MPEG Muxer");
        if (hr != 0)
        {
          Log.Warn("DVR2MPG: FAILED:Add Cyberlink MPEG Muxer to filtergraph :0x{0:X}", hr);
          Cleanup();
          return false;
        }

        //add filewriter 
        Log.Info("DVR2MPG: Add FileWriter to graph");
        string monikerFileWrite =
          @"@device:sw:{083863F1-70DE-11D0-BD40-00A0C911CE86}\{3E8868CB-5FE8-402C-AA90-CB1AC6AE3240}";
        IBaseFilter fileWriterbase = Marshal.BindToMoniker(monikerFileWrite) as IBaseFilter;
        if (fileWriterbase == null)
        {
          Log.Warn("DVR2MPG: FAILED:Unable to create FileWriter");
          Cleanup();
          return false;
        }


        fileWriterFilter = fileWriterbase as IFileSinkFilter;
        if (fileWriterFilter == null)
        {
          Log.Warn("DVR2MPG: FAILED:Add unable to get IFileSinkFilter for filewriter");
          Cleanup();
          return false;
        }

        hr = graphBuilder.AddFilter(fileWriterbase, "FileWriter");
        if (hr != 0)
        {
          Log.Warn("DVR2MPG: FAILED:Add FileWriter to filtergraph :0x{0:X}", hr);
          Cleanup();
          return false;
        }


        //connect output #0 of streambuffer source->powerdvd audio in
        //connect output #1 of streambuffer source->powerdvd video in
        Log.Info("DVR2MPG: connect streambuffer->multiplexer");
        IPin pinOut0, pinOut1;
        IPin pinIn0, pinIn1;
        pinOut0 = DsFindPin.ByDirection((IBaseFilter)bufferSource, PinDirection.Output, 0);
        pinOut1 = DsFindPin.ByDirection((IBaseFilter)bufferSource, PinDirection.Output, 1);

        pinIn0 = DsFindPin.ByDirection(powerDvdMuxer, PinDirection.Input, 0);
        pinIn1 = DsFindPin.ByDirection(powerDvdMuxer, PinDirection.Input, 1);
        if (pinOut0 == null || pinOut1 == null || pinIn0 == null || pinIn1 == null)
        {
          Log.Warn("DVR2MPG: FAILED:unable to get pins of muxer&source");
          Cleanup();
          return false;
        }

        bool usingAc3 = false;
        AMMediaType amAudio = new AMMediaType();
        amAudio.majorType = MediaType.Audio;
        amAudio.subType = MediaSubType.Mpeg2Audio;
        hr = pinOut0.Connect(pinIn1, amAudio);
        if (hr != 0)
        {
          amAudio.subType = MediaSubType.DolbyAC3;
          hr = pinOut0.Connect(pinIn1, amAudio);
          usingAc3 = true;
        }
        if (hr != 0)
        {
          Log.Warn("DVR2MPG: FAILED: unable to connect audio pins: 0x{0:X}", hr);
          Cleanup();
          return false;
        }

        if (usingAc3)
          Log.Info("DVR2MPG: using AC3 audio");
        else
          Log.Info("DVR2MPG: using MPEG audio");

        AMMediaType amVideo = new AMMediaType();
        amVideo.majorType = MediaType.Video;
        amVideo.subType = MediaSubType.Mpeg2Video;
        hr = pinOut1.Connect(pinIn0, amVideo);
        if (hr != 0)
        {
          Log.Warn("DVR2MPG: FAILED: unable to connect video pins: 0x{0:X}", hr);
          Cleanup();
          return false;
        }


        //connect output of powerdvd muxer->input of filewriter
        Log.Info("DVR2MPG: connect multiplexer->filewriter");
        IPin pinOut, pinIn;
        pinOut = DsFindPin.ByDirection(powerDvdMuxer, PinDirection.Output, 0);
        if (pinOut == null)
        {
          Log.Warn("DVR2MPG: FAILED:cannot get output pin of Cyberlink MPEG muxer :0x{0:X}", hr);
          Cleanup();
          return false;
        }
        pinIn = DsFindPin.ByDirection(fileWriterbase, PinDirection.Input, 0);
        if (pinIn == null)
        {
          Log.Warn("DVR2MPG: FAILED:cannot get input pin of Filewriter :0x{0:X}", hr);
          Cleanup();
          return false;
        }
        AMMediaType mt = new AMMediaType();
        hr = pinOut.Connect(pinIn, mt);
        if (hr != 0)
        {
          Log.Warn("DVR2MPG: FAILED:connect muxer->filewriter :0x{0:X}", hr);
          Cleanup();
          return false;
        }

        //set output filename
        string outputFileName = System.IO.Path.ChangeExtension(info.file, ".mpg");
        Log.Info("DVR2MPG: set output file to :{0}", outputFileName);
        mt.majorType = MediaType.Stream;
        mt.subType = MediaSubTypeEx.MPEG2;

        hr = fileWriterFilter.SetFileName(outputFileName, mt);
        if (hr != 0)
        {
          Log.Warn("DVR2MPG: FAILED:unable to set filename for filewriter :0x{0:X}", hr);
          Cleanup();
          return false;
        }
        mediaControl = graphBuilder as IMediaControl;
        mediaSeeking = graphBuilder as IMediaSeeking;
        mediaEvt = graphBuilder as IMediaEventEx;
        Log.Info("DVR2MPG: start transcoding");
        hr = mediaControl.Run();
        if (hr != 0)
        {
          Log.Warn("DVR2MPG: FAILED:unable to start graph :0x{0:X}", hr);
          Cleanup();
          return false;
        }
      }
      catch (Exception ex)
      {
        Log.Error("DVR2MPG: Unable create graph: {0}", ex.Message);
        Cleanup();
        return false;
      }
      return true;
    }
Ejemplo n.º 28
0
 public int SetFileName(string fileName)
 {
     return(dumpIface.SetFileName(fileName, System.IntPtr.Zero));
 }
Ejemplo n.º 29
0
        public DSFilterNode(IBaseFilter filter, bool manualAdded)
        {
            _filter      = filter;
            _manualAdded = manualAdded;

            AssociatedUINode = typeof(DSFilterNodeUI).AssemblyQualifiedName;

            // if it's a filesource filter, get the filename for it
            IFileSourceFilter fs = filter as IFileSourceFilter;

            if (fs != null)
            {
                IAMOpenProgress op = filter as IAMOpenProgress;
                if (op != null)
                {
                    // it wants a URL (thought you were being sneaky huh?)
                    string      url   = string.Empty;
                    AMMediaType mtype = new AMMediaType();
                    fs.GetCurFile(out url, mtype);
                    if (url == null)
                    {
                        URLDialog ud = new URLDialog();
                        if (ud.ShowDialog() == DialogResult.OK)
                        {
                            fs.Load(ud.URL, null);
                        }
                        ud.Dispose();
                        ud = null;
                    }
                    fs = null;
                }
                else
                {
                    // it wants a filename
                    string      filename = string.Empty;
                    AMMediaType mtype    = new AMMediaType();
                    fs.GetCurFile(out filename, mtype);
                    if (filename == null)
                    {
                        OpenFileDialog ofd = new OpenFileDialog();
                        if (ofd.ShowDialog() == DialogResult.OK)
                        {
                            fs.Load(ofd.FileName, null);
                        }
                        ofd.Dispose();
                        ofd = null;
                    }
                    fs = null;
                }
            }

            // if it's a filewriter, get the filename for it
            IFileSinkFilter fw = filter as IFileSinkFilter;

            if (fw != null)
            {
                string      filename = string.Empty;
                AMMediaType mtype    = new AMMediaType();
                fw.GetCurFile(out filename, mtype);
                if (filename == null)
                {
                    SaveFileDialog sfd = new SaveFileDialog();
                    if (sfd.ShowDialog() == DialogResult.OK)
                    {
                        fw.SetFileName(sfd.FileName, null);
                    }
                }
                fw = null;
            }

            // create and add all DaggerPins for this filter
            SyncPins();
        }
Ejemplo n.º 30
0
        /// <summary>
        /// Build the graph and connect filters
        /// </summary>
        /// <param name="outputPath">Path of stego video file</param>
        private void BuildGraph(string outputPath)
        {
            ///Create a graph builder.
            this._graphBuilder = (IGraphBuilder) new FilterGraph();

            ///Create a sample grabber filter. Sample grabber filter provides callback
            ///for application to grab video frames on the fly.
            this._sampleGrabber = (ISampleGrabber) new SampleGrabber();
            ///Configure the sample grabber
            this.ConfigureSampleGrabber(this._sampleGrabber, MediaSubType.RGB24);


            ///Create the file reader filter.
            this._fileReaderFilter = ComGuids.GetFilterFromGuid(ComGuids.FileReaderFilterGuid);
            ///Add the filter to graph. This function only adds filter to graph but
            ///do not connect it
            this._graphBuilder.AddFilter(this._fileReaderFilter, "File Source");

            ///Get source filter, this will let you load an AVI file
            IFileSourceFilter sourceFilter = this._fileReaderFilter as IFileSourceFilter;

            ///Load the file
            sourceFilter.Load(this._sourcePath, null);


            ///Create AVI splitter. This filter splits the AVI file into video and audio or other
            ///components that form the video (e.g text)
            this._aviSplitter = ComGuids.GetFilterFromGuid(ComGuids.AviSplitterGuid);
            ///Add the filter to graph
            this._graphBuilder.AddFilter(this._aviSplitter, "AVI Splitter");


            ///Add the sample grabber filter to graph
            this._graphBuilder.AddFilter((IBaseFilter)this._sampleGrabber, "SampleGrabber");


            ///Create AVI mux filter. This filter will combine the audio and video in one stream.
            ///We will use this filter to combine audio and video streams after hiding
            ///data in ISampleGrabber's BufferCB callback.
            this._aviMultiplexer = ComGuids.GetFilterFromGuid(ComGuids.AviMultiplexerGuid);
            ///Add filter to graph
            this._graphBuilder.AddFilter(this._aviMultiplexer, "AVI multiplexer");

            ///We will add file writer, only then we will add file writer
            if (this._processing == ProcessingType.Hide)
            {
                ///Create a file writer filter. This filter will be used to write the AVI stream
                ///to a file
                this._rendererFilter = ComGuids.GetFilterFromGuid(ComGuids.FileWriterFilterGuid);

                ///Add renderer filter to graph
                this._graphBuilder.AddFilter(this._rendererFilter, "File writer");

                ///Get the file sink filter
                IFileSinkFilter sinkFilter = this._rendererFilter as IFileSinkFilter;
                ///Set the output file name
                sinkFilter.SetFileName(outputPath, null);
            }
            else
            {
                ///Create a null renderer
                this._rendererFilter = ComGuids.GetFilterFromGuid(ComGuids.NullRendererGuid);

                ///Add renderer filter to graph
                this._graphBuilder.AddFilter(this._rendererFilter, "Null renderer");
            }

            DirectShowUtil.ConnectFilters(this._graphBuilder, this._fileReaderFilter, this._aviSplitter);
            DirectShowUtil.ConnectFilters(this._graphBuilder, this._aviSplitter, (IBaseFilter)this._sampleGrabber);
            DirectShowUtil.ConnectFilters(this._graphBuilder, (IBaseFilter)this._sampleGrabber, this._aviMultiplexer);
            DirectShowUtil.ConnectFilters(this._graphBuilder, this._aviMultiplexer, this._rendererFilter);
        }