Example #1
0
        // 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;
        }
Example #2
0
 protected override void SetupFilterGraph(IFilterGraph graph)
 {
     _audioEngine = new X3DAudioEngine();
     _graph = graph as IGraphBuilder;
     base.SetupFilterGraph(graph);
     SetupAudio();
 }
Example #3
0
        public static IBaseFilter CreateAudioCompressor(DisposalCleanup dc, IGraphBuilder graph, IPin outPin,
                                                        AudioFormat settings)
        {
            if (dc == null) throw new ArgumentNullException("dc");
            if (graph == null) throw new ArgumentNullException("graph");
            if (outPin == null) throw new ArgumentNullException("outPin");
            if (settings == null) throw new ArgumentNullException("settings");

            int hr = 0;

            using (AudioCompressor compressor = AudioCompressorFactory.Create(settings))
            {
                IBaseFilter compressorFilter = compressor.Filter;
                dc.Add(compressorFilter);

                hr = graph.AddFilter(compressorFilter, settings.AudioCompressor);
                DsError.ThrowExceptionForHR(hr);

                FilterGraphTools.ConnectFilters(graph, outPin, compressorFilter, true);

                // set the media type on the output pin of the compressor
                if (compressor.MediaType != null)
                {
                    FilterGraphTools.SetFilterFormat(compressor.MediaType, compressorFilter);
                }

                return compressorFilter;
            }
        }
Example #4
0
        /// <summary>Adds a graph to the ROT.</summary>
        /// <param name="graph">The graph to be added.</param>
        /// <returns>A cookie that can be used to remove this graph from the ROT.</returns>
        private static RunningObjectTableCookie AddGraphToRot(IGraphBuilder graph)
        {
            if (graph == null) throw new ArgumentNullException("graph");
            IRunningObjectTable rot = null;
            IMoniker moniker = null;
            try
            {
                // Get the ROT.
                rot = GetRunningObjectTable(0);

                // Create a moniker for the grpah
                int pid;
                using (Process p = Process.GetCurrentProcess())
                {
                    pid = p.Id;
                }
                IntPtr unkPtr = Marshal.GetIUnknownForObject(graph);
                string item = string.Format("FilterGraph {0} pid {1}", ((int)unkPtr).ToString("x8"), pid.ToString("x8"));
                Marshal.Release(unkPtr);
                moniker = CreateItemMoniker("!", item);

                // Registers the graph in the running object table
                int cookieValue = rot.Register(ROTFLAGS_REGISTRATIONKEEPSALIVE, graph, moniker);
                return new RunningObjectTableCookie(cookieValue);
            }
            finally
            {
                // Releases the COM objects
                if (moniker != null) while (Marshal.ReleaseComObject(moniker) > 0) ;
                if (rot != null) while (Marshal.ReleaseComObject(rot) > 0) ;
            }
        }
Example #5
0
        public static IBaseFilter RenderAsfWriterWithProfile(DisposalCleanup dc, IGraphBuilder graph, string profileData,
                                                             string outputFile)
        {
            if (dc == null) throw new ArgumentNullException("dc");
            if (graph == null) throw new ArgumentNullException("graph");
            if (string.IsNullOrEmpty(profileData)) throw new ArgumentNullException("profileData");
            if (string.IsNullOrEmpty(outputFile)) throw new ArgumentNullException("outputFile");

            int hr = 0;

            var asfWriterFilter = (IBaseFilter) new WMAsfWriter();
            dc.Add(asfWriterFilter);
            hr = graph.AddFilter(asfWriterFilter, Resources.DefaultAsfWriterName);
            DsError.ThrowExceptionForHR(hr);

            // Create an appropriate IWMProfile from the data
            IWMProfileManager profileManager = ProfileManager.CreateInstance();
            dc.Add(profileManager);

            IntPtr wmProfile = profileManager.LoadProfileByData(profileData);
            dc.Add(wmProfile);

            // Set the profile on the writer
            var configWriter = (IConfigAsfWriter2) asfWriterFilter;
            configWriter.ConfigureFilterUsingProfile(wmProfile);

            hr = ((IFileSinkFilter) asfWriterFilter).SetFileName(outputFile, null);
            DsError.ThrowExceptionForHR(hr);

            return asfWriterFilter;
        }
 public ProfileAndMachineParser(IGraphBuilder graphBuilder, XmlNode structureMapNode, XmlMementoCreator creator)
 {
     _profileBuilder = graphBuilder.GetProfileBuilder();
     _graphBuilder = graphBuilder;
     _structureMapNode = structureMapNode;
     _creator = creator;
 }
        private void GetInterface()
        {
            object o;
            int hr;

            m_pGraph = (IGraphBuilder)new FilterGraph();
            IBaseFilter pSource;
            hr = m_pGraph.AddSourceFilter(@"C:\SourceForge\mflib\Test\Media\AspectRatio4x3.wmv", null, out pSource);
            DsError.ThrowExceptionForHR(hr);
            IBaseFilter pEVR = (IBaseFilter)new EnhancedVideoRenderer();
            hr = m_pGraph.AddFilter(pEVR, "EVR");
            DsError.ThrowExceptionForHR(hr);

            ICaptureGraphBuilder2 cgb;
            cgb = (ICaptureGraphBuilder2)new CaptureGraphBuilder2();

            hr = cgb.SetFiltergraph(m_pGraph);
            DsError.ThrowExceptionForHR(hr);
            hr = cgb.RenderStream(null, MediaType.Video, pSource, null, pEVR);
            DsError.ThrowExceptionForHR(hr);

            IMFGetService gs = pEVR as IMFGetService;
            hr = gs.GetService(MFServices.MR_VIDEO_MIXER_SERVICE, typeof(IMFVideoProcessor).GUID, out o);
            MFError.ThrowExceptionForHR(hr);

            m_vp = o as IMFVideoProcessor;
        }
Example #8
0
        public static IBaseFilter AddFilterById(IGraphBuilder graph, Guid guid, string name)
        {
            Ensure.IsNotNull(Log, graph, "graph is null");

            IBaseFilter filter = null;

            try
            {
                var type = Type.GetTypeFromCLSID(guid);
                filter = (IBaseFilter)Activator.CreateInstance(type);

                var hr = graph.AddFilter(filter, name);
                DsError.ThrowExceptionForHR(hr);
            }
            catch (Exception ex)
            {
                if (filter != null)
                {
                    graph.RemoveFilter(filter);
                    Marshal.ReleaseComObject(filter);
                    filter = null;
                }

                Log.Fatal(string.Format("Filter {0} is not added to the graph", name) + ex);
            }

            return filter;
        }
        public static IBaseFilter AddFilterFromClsid(IGraphBuilder graphBuilder, Guid clsid, string name)
        {
            int hr = 0;
            IBaseFilter filter = null;

            if (graphBuilder == null)
                throw new ArgumentNullException("graphBuilder");

            try
            {
                Type type = Type.GetTypeFromCLSID(clsid);
                filter = (IBaseFilter)Activator.CreateInstance(type);

                hr = graphBuilder.AddFilter(filter, name);
                DsError.ThrowExceptionForHR(hr);
            }
            catch
            {
                if (filter != null)
                {
                    Marshal.ReleaseComObject(filter);
                    filter = null;
                }
            }

            return filter;
        }
    public static void EnableFFDShowSubtitles(IGraphBuilder graphBuilder)
    {
      // no instance of engine yet created or no ffdshow api, try to find it
      IBaseFilter baseFilter = null;
      DirectShowUtil.FindFilterByClassID(graphBuilder, FFDShowAPI.FFDShowVideoGuid, out baseFilter);
      if (baseFilter == null)
        DirectShowUtil.FindFilterByClassID(graphBuilder, FFDShowAPI.FFDShowVideoDXVAGuid, out baseFilter);
      if (baseFilter == null)
        DirectShowUtil.FindFilterByClassID(graphBuilder, FFDShowAPI.FFDShowVideoRawGuid, out baseFilter);

      if (baseFilter != null)
      {
        IffdshowDec ffdshowDec = baseFilter as IffdshowDec;
        if (ffdshowDec != null)
        {
          // use a temporary instance of the API, as it is only used here, to disable subs
          FFDShowAPI tempffdshowAPI = new FFDShowAPI((object)baseFilter);
          tempffdshowAPI.DoShowSubtitles = true;
          Log.Info("FFDshow interfaces found -> Subtitles disabled");
          tempffdshowAPI.Dispose();
        }
        else
        {
          DirectShowUtil.ReleaseComObject(baseFilter);
        }
      }
    } 
Example #11
0
        public static int ConnectFilter(IGraphBuilder graph, IBaseFilter up, IBaseFilter down)
        {
            IPin pinSrc  = null;
            int i = 0;
            while ( (pinSrc = DsFindPin.ByDirection(up, PinDirection.Output, i++) ) != null )
            {
                IPin pinDest = null;
                int j = 0;
                while((pinDest = DsFindPin.ByDirection(down, PinDirection.Input, j++)) != null)
                {
                    try
                    {
                        ConnectFilters(graph, pinSrc, pinDest, true);
                    }
                    catch(Exception e)
                    {
                        Marshal.FinalReleaseComObject(pinDest);
                        continue;
                    }
                    //�ɹ�
                    Marshal.FinalReleaseComObject(pinSrc);
                    Marshal.FinalReleaseComObject(pinDest);
                    return 0;
                }
                Marshal.FinalReleaseComObject(pinSrc);
            }

            return -1;
        }
Example #12
0
 public override void Build(IGraphBuilder builder)
 {
     foreach(var v in this)
       {
     v.Build(builder); //thats it :)
       }
       //get the last item
 }
 public override void Build(IGraphBuilder builder)
 {
     //we already gave the proper links so just act as a forwarder
     Condition.Build(builder);
     OnTrue.Build(builder);
     OnFalse.Build(builder);
     //OnTrue and OnFalse
 }
            public void Init()
            {
                //arrange
                _graphBuilder = new UndirectedGraphBuilder("kargerMinCut02.txt");

                //act
                _graph = _graphBuilder.Build();
            }
Example #15
0
 private void attachInstances(PluginFamily family, XmlElement familyElement, IGraphBuilder builder)
 {
     familyElement.ForEachChild(INSTANCE_NODE).Do(element =>
     {
         InstanceMemento memento = _mementoCreator.CreateMemento(element);
         family.AddInstance(memento);
     });
 }
Example #16
0
		/// <summary>
		/// Divides the supplied graph to its connected subgraphs.
		/// </summary>
		public static IGraph[] Split(IGraph initial, IGraphBuilder builder)
		{
			// A list with the nodes awaiting to be processed
			NodeCollection nodes = initial.Nodes.Clone() as NodeCollection;

			// A list with the subgraphs
			IGraph subgraph = null;
			ArrayList subgraphs = new ArrayList();

			while (nodes.Count > 0)
			{
				INode node = nodes[0];
				nodes.RemoveAt(0);

				subgraph = builder.Create();
				subgraph.Nodes.Add(node);

				int i = 0;
				while (i < subgraph.Nodes.Count)
				{
					node = subgraph.Nodes[i];

					foreach (ILink link in node.InLinks)
					{
						if (!subgraph.Nodes.Contains(link.Origin))
						{
							subgraph.Nodes.Add(link.Origin);
							nodes.Remove(link.Origin);
						}

						if (!subgraph.Links.Contains(link))
							subgraph.Links.Add(link);
					}

					foreach (ILink link in node.OutLinks)
					{
						if (!subgraph.Nodes.Contains(link.Destination))
						{
							subgraph.Nodes.Add(link.Destination);
							nodes.Remove(link.Destination);
						}

						if (!subgraph.Links.Contains(link))
							subgraph.Links.Add(link);
					}

					i++;
				}

				subgraphs.Add(subgraph);
			}

			IGraph[] result = new IGraph[subgraphs.Count];
			for (int i = 0; i < subgraphs.Count; i++)
				result[i] = subgraphs[i] as IGraph;

			return result;
		}
Example #17
0
 public ResultController(IUserProfileBusinessLogic userProfileBusinessLogic, IUserIngredientBusinessLogic userIngredientBusinessLogic, IUserContext userContext, IGraphBuilder graphBuilder, IUserWeightBusinessLogic userWeightBusinessLogic, IGraphLineOptionViewTypeConverter graphLineOptionViewTypeConverter)
 {
     this.graphLineOptionViewTypeConverter = graphLineOptionViewTypeConverter;
     this.userIngredientBusinessLogic = userIngredientBusinessLogic;
     this.userContext = userContext;
     this.graphBuilder = graphBuilder;
     this.userWeightBusinessLogic = userWeightBusinessLogic;
     this.userProfileBusinessLogic = userProfileBusinessLogic;
 }
        public void Parse(IGraphBuilder builder)
        {
            var familyParser = new FamilyParser(builder);

            forEachNode(DEFAULT_INSTANCE).Do(familyParser.ParseDefaultElement);
            forEachNode(ADD_INSTANCE_NODE).Do(familyParser.ParseInstanceElement);

            ParseProfiles(builder);
        }
Example #19
0
 public override void Build(IGraphBuilder builder)
 {
     //do nothing
       //we can do the linkage here
       if(OnFalseHook != null)
     builder.Link(Index, OnFalseHook.First().Index, "[label = \"f\"]");
       if(OnTrueHook != null)
     builder.Link(Index, OnTrueHook.First().Index, "[label = \"t\"]");
 }
Example #20
0
        public void Open(string file)
        {
            /* Creates the GraphBuilder COM object */
            m_graph = new FilterGraphNoThread() as IGraphBuilder;

            if (m_graph == null)
                throw new Exception("Could not create a graph");


            IBaseFilter renderer = CreateVideoMixingRenderer9(m_graph, 1);

            var filterGraph = m_graph as IFilterGraph2;

            
            if (filterGraph == null)
                throw new Exception("Could not QueryInterface for the IFilterGraph2");

            IBaseFilter sourceFilter;

            /* Have DirectShow find the correct source filter for the Uri */
            int hr = filterGraph.AddSourceFilter(file, file, out sourceFilter);
            DsError.ThrowExceptionForHR(hr);

            /* We will want to enum all the pins on the source filter */
            IEnumPins pinEnum;

            hr = sourceFilter.EnumPins(out pinEnum);
            DsError.ThrowExceptionForHR(hr);

            IntPtr fetched = IntPtr.Zero;
            IPin[] pins = { null };

            /* Counter for how many pins successfully rendered */
            int pinsRendered = 0;


            /* Loop over each pin of the source filter */
            while (pinEnum.Next(pins.Length, pins, fetched) == 0)
            {
                if (filterGraph.RenderEx(pins[0],
                                         AMRenderExFlags.None,
                                         IntPtr.Zero) >= 0)
                    pinsRendered++;

                Marshal.ReleaseComObject(pins[0]);
            }

            Marshal.ReleaseComObject(pinEnum);
            Marshal.ReleaseComObject(sourceFilter);

            if (pinsRendered == 0)
                throw new Exception("Could not render any streams from the source Uri");

            m_mediaControl = m_graph as IMediaControl;
        }
Example #21
0
        public static IBaseFilter RenderWavDestination(DisposalCleanup dc, IGraphBuilder graph)
        {
            if (dc == null) throw new ArgumentNullException("dc");
            if (graph == null) throw new ArgumentNullException("graph");

            IBaseFilter wavDest =
                FilterGraphTools.AddFilterFromClsid(graph, WavDestinationFilterId, Resources.DefaultWavDestinationName);
            dc.Add(wavDest);

            return wavDest;
        }
Example #22
0
        /// <summary>
        /// Create an instance of the BlackListManager
        /// </summary>
        /// <param name="graphBuilder">The Filter Graph to register on.</param>
        public BlackListManager(IGraphBuilder graphBuilder)
        {
            if (graphBuilder == null)
            throw new ArgumentNullException("graphBuilder");

              IObjectWithSite ows = (IObjectWithSite)graphBuilder;

              int hr = ows.SetSite(this);
              DsError.ThrowExceptionForHR(hr);

              this.blackList = new List<Guid>();
        }
Example #23
0
 public static void AddSourceFilterOverride(Action fallbackAction, IResourceAccessor resourceAccessor, IGraphBuilder graphBuilder)
 {
   string sourceFilterName = GetSourceFilterName(resourceAccessor.ResourcePathName);
   if (string.IsNullOrEmpty(sourceFilterName))
   {
     fallbackAction();
   }
   else
   {
     AddStreamSourceFilter(sourceFilterName, resourceAccessor, graphBuilder);
   }
 }
 public IEnumerable<IBaseFilter> InitFilters(IGraphBuilder graphBuilder)
 {
     filterBuilders.Clear();
     foreach (var filter in filterTypes.Select(CreateFilter))
     {
         var builder = new FilterBuilder(filter);
         filterBuilders.Add(builder);
         builder.Init(graphBuilder);
         var baseFilter = CompressorFilter = builder.Build();
         yield return baseFilter;
     }
 }
Example #25
0
 public void CloseInterfaces()
 {
     if (mediaEvent != null)
     {
         hresult = mediaControl.Stop();
         Marshal.ThrowExceptionForHR(hresult);
     }
     mediaControl = null;
     mediaEvent = null;
     graphBuilder = null;
     if (filterGraph != null) Marshal.ReleaseComObject(filterGraph);
     filterGraph = null;
 }
Example #26
0
 public override void Build(IGraphBuilder builder)
 {
     //alright so we need to create links
     //Console.WriteLine("We have {0} elements", Count);
     Operation v0 = this[0];
     Operation v1 = this[1];
     //	if(v0 is BinaryOperation)
     //		BuildCondition(v0, builder);
     v0.Build(builder);
     //	if(v1 is BinaryOperation)
     //		BuildCondition(v1, builder);
     v1.Build(builder);
 }
Example #27
0
        public MainForm()
        {
            InitializeComponent();
            graphbuilder = (IGraphBuilder)new FilterGraph();
            samplegrabber = (ISampleGrabber)new SampleGrabber();
            graphbuilder.AddFilter((IBaseFilter)samplegrabber, "samplegrabber");

            mt = new AMMediaType();
            mt.majorType = MediaType.Video;
            mt.subType = MediaSubType.RGB24;
            mt.formatType = FormatType.VideoInfo;
            samplegrabber.SetMediaType(mt);
            PrintSeconds();
        }
Example #28
0
        public CaptureForm()
        {
            InitializeComponent();

            graph_builder = (IGraphBuilder)new FilterGraph();
            media_control = (IMediaControl)graph_builder;
            events = (IMediaEventEx)graph_builder;
            grabber = (ISampleGrabber)new SampleGrabber();

            AMMediaType media_type = new AMMediaType();
            media_type.majorType = MediaType.Video;
            media_type.subType = MediaSubType.RGB24;
            grabber.SetMediaType( media_type );
            grabber.SetCallback( this, 1 );

            cbDevices.Items.AddRange( GetDevices( FilterCategory.VideoInputDevice ) );
        }
Example #29
0
    /// <summary>
    /// Add VMR7 filter to graph and configure it
    /// </summary>
    /// <param name="graphBuilder"></param>
    public void AddVMR7(IGraphBuilder graphBuilder)
    {
      Log.Info("VMR7Helper:AddVMR7");
      if (vmr7intialized)
      {
        return;
      }

      VMR7Filter = (IBaseFilter)new VideoMixingRenderer();
      if (VMR7Filter == null)
      {
        Error.SetError("Unable to play movie", "VMR7 is not installed");
        Log.Error("VMR7Helper:Failed to get instance of VMR7 ");
        return;
      }

      int hr;
      IVMRFilterConfig config = VMR7Filter as IVMRFilterConfig;
      if (config != null)
      {
        hr = config.SetNumberOfStreams(1);
        if (hr != 0)
        {
          Log.Error("VMR7Helper:Failed to set number of streams:0x{0:X}", hr);
          DirectShowUtil.ReleaseComObject(VMR7Filter);
          VMR7Filter = null;
          return;
        }
      }

      hr = graphBuilder.AddFilter(VMR7Filter, "Video Mixing Renderer");
      if (hr != 0)
      {
        Error.SetError("Unable to play movie", "Unable to initialize VMR7");
        Log.Error("VMR7Helper:Failed to add VMR7 to filtergraph");
        DirectShowUtil.ReleaseComObject(VMR7Filter);
        VMR7Filter = null;
        return;
      }
      m_graphBuilder = graphBuilder;
      m_mixerBitmap = VMR7Filter as IVMRMixerBitmap;
      quality = VMR7Filter as IQualProp;
      g_vmr7 = this;
      vmr7intialized = true;
    }
Example #30
0
        //Метод CleanUp (Зачистка графов)
        public void CleanUp()
        {
            if (mediaControl != null) mediaControl.Stop();
            CurrentStatus = mStatus.Stop;

            if (videoWindow != null)
            {
                videoWindow.put_Visible(0);
                videoWindow.put_Owner(new IntPtr(0));
            }
            if (mediaControl != null)  mediaControl  = null;
            if (mediaPosition != null) mediaPosition = null;
            if (mediaEventEx != null)  mediaEventEx  = null;
            if (mediaEvent != null)    mediaEvent    = null;
            if (videoWindow != null)   videoWindow   = null;
            if (basicAudio != null)    basicAudio    = null;
            if (graphBuilder != null)  graphBuilder  = null;
        }
Example #31
0
        /// <summary>
        /// Create our RTSP source filter and load the
        /// RTSP source url
        /// </summary>
        /// <param name="pGraph">The graph the filter will live in</param>
        /// <param name="url">The URL to load into the filter</param>
        /// <returns></returns>
        private IBaseFilter CreateSourceFilter(IGraphBuilder pGraph, string url)
        {
            //var clsidRTSPFilter = new Guid("{B3F5D418-CDB1-441C-9D6D-2063D5538962}"); //RTSPSource.ax
            //var pRTSPFilter2 = (IBaseFilter)Activator.CreateInstance(Type.GetTypeFromCLSID(clsidRTSPFilter));
            //int hr = pGraph.AddFilter(pRTSPFilter2, "RTSP Filter");
            //CheckHr(hr, "Can't add RTSP Filter to graph");
            ////set source filename
            //var pRTSPFilter2Src = pRTSPFilter2 as IFileSourceFilter;
            //if (pRTSPFilter2Src == null)
            //    CheckHr(unchecked((int)0x80004002), "Can't get IFileSourceFilter");

            //if (pRTSPFilter2Src != null)
            //    hr = pRTSPFilter2Src.Load(url, null);

            //CheckHr(hr, "Can't load file");
            //Filter = true;
            IBaseFilter pSourceFilter2;

            int hr = pGraph.AddSourceFilter(url, "SourceFilter", out pSourceFilter2);

            CheckHr(hr, "Can't add source Filter to graph for url=" + url);
            return(pSourceFilter2);
        }
Example #32
0
        public static IBaseFilter CreateAudioCompressor(DisposalCleanup dc, IGraphBuilder graph, IPin outPin,
                                                        AudioFormat settings)
        {
            int hr = 0;

            AudioCompressor compressor       = AudioCompressorFactory.Create(settings);
            IBaseFilter     compressorFilter = compressor.Filter;

            dc.Add(compressorFilter);

            hr = graph.AddFilter(compressorFilter, settings.AudioCompressor);
            DsError.ThrowExceptionForHR(hr);

            FilterGraphTools.ConnectFilters(graph, outPin, compressorFilter, true);

            // set the media type on the output pin of the compressor
            if (compressor.MediaType != null)
            {
                FilterGraphTools.SetFilterFormat(compressor.MediaType, compressorFilter);
            }

            return(compressorFilter);
        }
Example #33
0
        private static IBaseFilter AddFilterByDevice(IGraphBuilder graphBuilder, DsDevice device)
        {
            if (graphBuilder == null)
            {
                throw new ArgumentNullException("graphBuilder");
            }

            var filterGraph = graphBuilder as IFilterGraph2;

            if (filterGraph == null)
            {
                return(null);
            }

            IBaseFilter filter = null;

            if (device != null)
            {
                int hr = filterGraph.AddSourceFilterForMoniker(device.Mon, null, device.Name, out filter);
                DsError.ThrowExceptionForHR(hr);
            }
            return(filter);
        }
Example #34
0
        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);
            }
        }
Example #35
0
        public static void RemoveAllFilters(IGraphBuilder graphBuilder)
        {
            int          hr = 0;
            IEnumFilters enumFilters;
            ArrayList    filtersArray = new ArrayList();

            if (graphBuilder == null)
            {
                throw new ArgumentNullException("graphBuilder");
            }

            hr = graphBuilder.EnumFilters(out enumFilters);
            DsError.ThrowExceptionForHR(hr);

            IntPtr fetched = Marshal.AllocCoTaskMem(4);

            try
            {
                IBaseFilter[] filters = new IBaseFilter[1];

                while (enumFilters.Next(filters.Length, filters, fetched) == 0)
                {
                    filtersArray.Add(filters[0]);
                }
            }
            finally
            {
                Marshal.FreeCoTaskMem(fetched);
                Marshal.ReleaseComObject(enumFilters);
            }

            foreach (IBaseFilter filter in filtersArray)
            {
                hr = graphBuilder.RemoveFilter(filter);
                Marshal.ReleaseComObject(filter);
            }
        }
        void CloseInterfaces()
        {
            if (me != null)
            {
                hr = mc.Stop();
                DsError.ThrowExceptionForHR(hr);

                hr = me.SetNotifyWindow(IntPtr.Zero, WM_GRAPHNOTIFY, IntPtr.Zero);
                DsError.ThrowExceptionForHR(hr);
            }
            mc = null;
            me = null;
            gb = null;
            if (matroska_mux != null)
            {
                Marshal.ReleaseComObject(matroska_mux);
            }
            matroska_mux = null;
            if (fg != null)
            {
                Marshal.ReleaseComObject(fg);
            }
            fg = null;
        }
Example #37
0
        public static void ConnectFilters(IGraphBuilder graphBuilder, IPin sourcePin, IBaseFilter downFilter,
                                          bool useIntelligentConnect)
        {
            if (graphBuilder == null)
            {
                throw new ArgumentNullException("graphBuilder");
            }

            if (sourcePin == null)
            {
                throw new ArgumentNullException("sourcePin");
            }

            if (downFilter == null)
            {
                throw new ArgumentNullException("downFilter");
            }

            IPin destPin;

            destPin = DsFindPin.ByDirection(downFilter, PinDirection.Input, 0);

            if (destPin == null)
            {
                throw new ArgumentException("The downstream filter has no input pin");
            }

            try
            {
                ConnectFilters(graphBuilder, sourcePin, destPin, useIntelligentConnect);
            }
            finally
            {
                Marshal.ReleaseComObject(destPin);
            }
        }
        public static IBaseFilter FindFilterByClsid(IGraphBuilder graphBuilder, Guid filterClsid)
        {
            int          hr          = 0;
            IBaseFilter  filter      = null;
            IEnumFilters enumFilters = null;

            if (graphBuilder == null)
            {
                throw new ArgumentNullException("graphBuilder");
            }

            hr = graphBuilder.EnumFilters(out enumFilters);
            if (hr == 0)
            {
                var    filters = new IBaseFilter[1];
                IntPtr fetched = IntPtr.Zero;

                while (enumFilters.Next(filters.Length, filters, fetched) == 0)
                {
                    Guid clsid;

                    hr = filters[0].GetClassID(out clsid);

                    if ((hr == 0) && (clsid == filterClsid))
                    {
                        filter = filters[0];
                        break;
                    }

                    Marshal.ReleaseComObject(filters[0]);
                }
                Marshal.ReleaseComObject(enumFilters);
            }

            return(filter);
        }
Example #39
0
        /// <summary>
        /// Adds a filter to a DirectShow graph based on it's name and filter category
        /// </summary>
        /// <param name="graphBuilder">The graph builder to add the filter to</param>
        /// <param name="deviceCategory">The category the filter belongs to</param>
        /// <param name="friendlyName">The friendly name of the filter</param>
        /// <returns>Reference to the IBaseFilter that was added to the graph or returns null if unsuccessful</returns>
        protected static IBaseFilter AddFilterByName(IGraphBuilder graphBuilder, Guid deviceCategory, string friendlyName)
        {
            var devices = DsDevice.GetDevicesOfCat(deviceCategory);

            var deviceList = (from d in devices
                              where d.Name == friendlyName
                              select d);
            DsDevice device = null;

            if (deviceList.Count() > 0)
            {
                device = deviceList.Take(1).Single();
            }

            foreach (var item in deviceList)
            {
                if (item != device)
                {
                    item.Dispose();
                }
            }

            return(AddFilterByDevice(graphBuilder, device));
        }
Example #40
0
        public Graph(string url, Control hostControl)
        {
            int hr = 0;

            _hostControl = hostControl;
            // An exception is thrown if cast fail
            _graphBuilder        = (IGraphBuilder) new FilterGraph();
            _captureGraphBuilder = (ICaptureGraphBuilder2) new CaptureGraphBuilder2();
            _mediaControl        = (IMediaControl)_graphBuilder;

            // Attach the filter graph to the capture graph
            hr = _captureGraphBuilder.SetFiltergraph(_graphBuilder);
            DsError.ThrowExceptionForHR(hr);

            AddLeadNetSrc(url);
            AddLeadNetDemux();
            ConnectFilters(_netSrc, "Output", _netDmx, "Input 01", true);
            AddLeadVideoTextOverlay();
            RenderNetDemux();

            SaveGraphFile("ZViewer.GRF");
            _readMsgTimer          = new System.Timers.Timer(2000);
            _readMsgTimer.Elapsed += new ElapsedEventHandler(readMsgTimer_Elapsed);
        }
Example #41
0
        /// <summary>
        /// The background thread entry point
        /// this is where the graph is created and run from
        /// </summary>
        /// <param name="arg"></param>
        private void StartAsync(object arg)
        {
            try
            {
                Trace("Starting ...");
                _url = arg.ToString();
                Trace(_url);

                Trace("Checking Status");
                CheckSystemStatus();

                Trace("Create Sample Grabber Callback");
                _capGrabber = new SampleGrabberCallback();

                Trace("Building Graph");
                _graph = (IGraphBuilder) new FilterGraph();


                BuildGraph(Graph, _url);

                InitializeSampleGrabber();

                //debug
                rot = new DsROTEntry(Graph);

                Trace("Running Graph");
                int hr = MediaControl.Run();
                CheckHr(hr, "Can't run the graph");
                RunGraph();
            }
            catch (Exception ex)
            {
                ExceptionHelper.HandleException(ex);
                Trace("ERROR: Creating Graph");
            }
        }
Example #42
0
        IDvdGraphBuilder GetDvdGraph()
        {
            int               hr;
            DvdGraphBuilder   dgb = null;
            IGraphBuilder     gb  = null;
            AMDvdRenderStatus drs;
            IDvdGraphBuilder  idgb = null;

            // Get a dvd graph object
            dgb = new DvdGraphBuilder();
            Debug.Assert(dgb != null, "new DvdGraphBuilder");

            // Get the IDvdGraphBuilder interface
            idgb = dgb as IDvdGraphBuilder;

            hr = idgb.RenderDvdVideoVolume(MyDisk, AMDvdGraphFlags.HWDecPrefer, out drs);
            DsError.ThrowExceptionForHR(hr);

            // If there is no dvd in the player, you get hr == S_FALSE (1)
            Debug.Assert(hr == 0, "Can't find dvd");

            // Get an IFilterGraph interface
            hr = idgb.GetFiltergraph(out gb);
            DsError.ThrowExceptionForHR(hr);

            Debug.Assert(gb != null, "GetFiltergraph");
            m_ROT = new DsROTEntry(gb);

            m_imc = gb as IMediaControl;

            m_mediaEvent = gb as IMediaEventEx;
            hr           = m_mediaEvent.SetNotifyWindow(this.Handle, WM_GRAPHNOTIFY, IntPtr.Zero);
            DsError.ThrowExceptionForHR(hr);

            return(idgb);
        }
Example #43
0
        protected virtual void Dispose(bool disposeManaged)
        {
            GC.SuppressFinalize(this);
            Process currentProc = Process.GetCurrentProcess();

            currentProc.PriorityClass = ProcessPriorityClass.Normal;

            _hostControl.Paint  -= new PaintEventHandler(PaintHandler);
            _hostControl.Resize -= new EventHandler(ResizeMoveHandler);
            _hostControl.Move   -= new EventHandler(ResizeMoveHandler);

            ForceReleaseComObject(_captureFilter);
            _captureFilter = null;
            ForceReleaseComObject(_fileWriter);
            _fileWriter = null;

            ForceReleaseComObject(_mediaControl);
            _mediaControl = null;
            ForceReleaseComObject(_graphBuilder);
            _graphBuilder = null;
            ForceReleaseComObject(_captureGraphBuilder);
            _captureGraphBuilder = null;

            ForceReleaseComObject(_videoRender);
            _videoRender = null;
            ForceReleaseComObject(_audioRender);
            _audioRender = null;
            ForceReleaseComObject(_audioVolumeFilter);
            _audioVolumeFilter          = null;
            _audioVolumeFilterInterface = null;

            ForceReleaseComObject(_vmrWindowlessControl);
            _vmrWindowlessControl = null;

            DsUtils.FreeAMMediaType(_emptyAMMediaType);
        }
Example #44
0
        public static IBaseFilter AddFilterToGraph(IGraphBuilder graphBuilder, string strFilterName, Guid clsid)
        {
            try
            {
                IBaseFilter NewFilter = null;
                foreach (Filter filter in Filters.LegacyFilters)
                {
                    if (String.Compare(filter.Name, strFilterName, true) == 0 && (clsid == Guid.Empty || filter.CLSID == clsid))
                    {
                        NewFilter = (IBaseFilter)Marshal.BindToMoniker(filter.MonikerString);

                        int hr = graphBuilder.AddFilter(NewFilter, strFilterName);
                        if (hr < 0)
                        {
                            //Log.Error("Failed: Unable to add filter: {0} to graph", strFilterName);
                            NewFilter = null;
                        }
                        else
                        {
                            //Log.Info("Added filter: {0} to graph", strFilterName);
                        }
                        break;
                    }
                }
                if (NewFilter == null)
                {
                    //Log.Error("Failed filter: {0} not found", strFilterName);
                }
                return(NewFilter);
            }
            catch (Exception ex)
            {
                //Log.Error("Failed filter: {0} not found {0}", strFilterName, ex.Message);
                return(null);
            }
        }
Example #45
0
        public ExtractWithGraph(string SourceFile, string workPath, ExtractMediaType mediaType, JobStatus jobStatus, Log jobLog)
        {
            _jobStatus        = jobStatus;
            _extractMediaType = mediaType;
            _SourceFile       = SourceFile;
            _workPath         = workPath;
            _jobLog           = jobLog;

            _Ext = FilePaths.CleanExt(SourceFile).Replace(".", "");

            //Set the decryptor type depending on the file type DVR-MS or WTV or TIVO
            if (_Ext == "dvr-ms")
            {
                _CLSI_Decryptor = CLSID_DVRMSDecryptTag;
            }
            else if (_Ext == "wtv")
            {
                _CLSI_Decryptor = CLSID_WTVDecryptTag;
            }

            // Set up base graph
            _fg = new FilterGraph();
            _gb = (IGraphBuilder)_fg;
        }
        public void Close()
        {
            try
            {
                mediaControl.Stop();

                if (m_ElecardAVCDecoderFilter != null)
                {
                    Marshal.ReleaseComObject(m_ElecardAVCDecoderFilter);
                }
                m_ElecardAVCDecoderFilter = null;

                if (m_UdpFilter != null)
                {
                    Marshal.ReleaseComObject(m_UdpFilter);
                }
                m_UdpFilter = null;


                if (m_ElecardPushMPEGDemuxFilter != null)
                {
                    Marshal.ReleaseComObject(m_ElecardPushMPEGDemuxFilter);
                }
                m_ElecardPushMPEGDemuxFilter = null;

                if (m_graphBuilder != null)
                {
                    Marshal.ReleaseComObject(m_graphBuilder);
                }
                m_graphBuilder = null;
            }
            catch (Exception err)
            {
                throw (new SystemException(err.Message));
            }
        }
Example #47
0
        private void CloseGraph()
        {
            FilterState state;

            if (mediaControl != null)
            {
                do
                {
                    mediaControl.Stop();
                    mediaControl.GetState(0, out state);
                } while (state != FilterState.Stopped);

                mediaControl = null;
            }

            if (allocator != null)
            {
                allocator.Dispose();
                allocator = null;
            }

            if (filter != null)
            {
                Marshal.ReleaseComObject(filter);
                filter = null;
            }


            if (graph != null)
            {
                RemoveAllFilters();

                Marshal.ReleaseComObject(graph);
                graph = null;
            }
        }
Example #48
0
            public RarFileSource(RarFileSourceFilter rarFileSourceFilter, IGraphBuilder graph, string filename)
            {
                m_Filter   = rarFileSourceFilter.CreateInstance();
                m_Splitter = (IBaseFilter) new LavSplitter();

                var sourceFilter = (IFileSourceFilter)m_Filter;

                DsError.ThrowExceptionForHR(sourceFilter.Load(filename, null));

                DsError.ThrowExceptionForHR(graph.AddFilter(m_Filter, "RAR File Source Filter"));
                DsError.ThrowExceptionForHR(graph.AddFilter(m_Splitter, "LAV Splitter"));

                var outpins = GetPins(m_Filter, "Output");

                ConnectPins(graph, outpins[0], m_Splitter, "Input");
                VideoOutputPin     = DsFindPin.ByName(m_Splitter, "Video");
                AudioOutputPin     = DsFindPin.ByName(m_Splitter, "Audio");
                SubtitleOutputPins = GetPins(m_Splitter, "Subtitle");

                ExtendedSeeking      = (IAMExtendedSeeking)m_Splitter;
                VideoStreamSelect    = (IAMStreamSelect)m_Splitter;
                AudioStreamSelect    = (IAMStreamSelect)m_Splitter;
                SubtitleStreamSelect = null;
            }
Example #49
0
        private static ISampleGrabber AddSampleGrabber(IGraphBuilder graph, string filterName, Guid majorType, Guid minorType)
        {
            ISampleGrabber isg = (ISampleGrabber) new SampleGrabber();

            int hr = graph.AddFilter((IBaseFilter)isg, filterName);

            DsError.ThrowExceptionForHR(hr);

            AMMediaType mt = new AMMediaType();

            mt.majorType = majorType;
            mt.subType   = minorType;

            hr = isg.SetMediaType(mt);
            DsError.ThrowExceptionForHR(hr);

            hr = isg.SetBufferSamples(true);
            DsError.ThrowExceptionForHR(hr);

            hr = isg.SetOneShot(true);
            DsError.ThrowExceptionForHR(hr);

            return(isg);
        }
Example #50
0
 public virtual void Dispose(bool disposing)
 {
     lock (_graphStateLock)
     {
         GC.SuppressFinalize(this);
         if (disposing)
         {
             FilterGraphTools.RemoveAllFilters(_graphBuilder);
             if (_graphBuilder != null)
             {
                 int refCount;
                 do
                 {
                     refCount = Marshal.ReleaseComObject(_graphBuilder);
                 } while (refCount > 0);
                 _graphBuilder = null;
                 _mediaControl = null;
             }
             if (_captureGraphBuilder != null)
             {
                 int refCount;
                 do
                 {
                     refCount = Marshal.ReleaseComObject(_captureGraphBuilder);
                 } while (refCount > 0);
                 _captureGraphBuilder = null;
             }
             if (_abortTimer != null)
             {
                 _abortTimer.Elapsed -= new System.Timers.ElapsedEventHandler(AbortTimer_Elapsed);
                 _abortTimer.Dispose();
                 _abortTimer = null;
             }
         }
     }
 }
Example #51
0
        /// <summary>フィルタグラフを再生・停止・一時停止する。</summary>
        public static void PlayGraph(IGraphBuilder graph, FILTER_STATE state)
        {
            var mediaControl = graph as IMediaControl;

            if (mediaControl == null)
            {
                return;
            }

            switch (state)
            {
            case FILTER_STATE.Paused:
                mediaControl.Pause();
                break;

            case FILTER_STATE.Stopped:
                mediaControl.Stop();
                break;

            default:
                mediaControl.Run();
                break;
            }
        }
Example #52
0
        /// <summary>
        /// Worker thread.
        /// </summary>
        ///
        private void WorkerThread( )
        {
            ReasonToFinishPlaying reasonToStop = ReasonToFinishPlaying.StoppedByUser;

            // grabber
            Grabber grabber = new Grabber(this);

            // objects
            object graphObject   = null;
            object grabberObject = null;

            // interfaces
            IGraphBuilder  graph         = null;
            IBaseFilter    sourceBase    = null;
            IBaseFilter    grabberBase   = null;
            ISampleGrabber sampleGrabber = null;
            IMediaControl  mediaControl  = null;

            IMediaEventEx mediaEvent = null;

            try
            {
                // get type for filter graph
                Type type = Type.GetTypeFromCLSID(Clsid.FilterGraph);
                if (type == null)
                {
                    throw new ApplicationException("Failed creating filter graph");
                }

                // create filter graph
                graphObject = Activator.CreateInstance(type);
                graph       = (IGraphBuilder)graphObject;

                // create source device's object
                graph.AddSourceFilter(fileName, "source", out sourceBase);
                if (sourceBase == null)
                {
                    throw new ApplicationException("Failed creating source filter");
                }

                // get type for sample grabber
                type = Type.GetTypeFromCLSID(Clsid.SampleGrabber);
                if (type == null)
                {
                    throw new ApplicationException("Failed creating sample grabber");
                }

                // create sample grabber
                grabberObject = Activator.CreateInstance(type);
                sampleGrabber = (ISampleGrabber)grabberObject;
                grabberBase   = (IBaseFilter)grabberObject;

                // add grabber filters to graph
                graph.AddFilter(grabberBase, "grabber");

                // set media type
                AMMediaType mediaType = new AMMediaType( );
                mediaType.MajorType = MediaType.Video;
                mediaType.SubType   = MediaSubType.RGB24;
                sampleGrabber.SetMediaType(mediaType);

                // connect pins
                int pinToTry = 0;

                IPin inPin  = Tools.GetInPin(grabberBase, 0);
                IPin outPin = null;

                // find output pin acceptable by sample grabber
                while (true)
                {
                    outPin = Tools.GetOutPin(sourceBase, pinToTry);

                    if (outPin == null)
                    {
                        Marshal.ReleaseComObject(inPin);
                        throw new ApplicationException("Did not find acceptable output video pin in the given source");
                    }

                    if (graph.Connect(outPin, inPin) < 0)
                    {
                        Marshal.ReleaseComObject(outPin);
                        outPin = null;
                        pinToTry++;
                    }
                    else
                    {
                        break;
                    }
                }

                Marshal.ReleaseComObject(outPin);
                Marshal.ReleaseComObject(inPin);

                // get media type
                if (sampleGrabber.GetConnectedMediaType(mediaType) == 0)
                {
                    VideoInfoHeader vih = (VideoInfoHeader)Marshal.PtrToStructure(mediaType.FormatPtr, typeof(VideoInfoHeader));

                    grabber.Width  = vih.BmiHeader.Width;
                    grabber.Height = vih.BmiHeader.Height;
                    mediaType.Dispose( );
                }

                // let's do rendering, if we don't need to prevent freezing
                if (!preventFreezing)
                {
                    // render pin
                    graph.Render(Tools.GetOutPin(grabberBase, 0));

                    // configure video window
                    IVideoWindow window = (IVideoWindow)graphObject;
                    window.put_AutoShow(false);
                    window = null;
                }

                // configure sample grabber
                sampleGrabber.SetBufferSamples(false);
                sampleGrabber.SetOneShot(false);
                sampleGrabber.SetCallback(grabber, 1);

                // disable clock, if someone requested it
                if (!referenceClockEnabled)
                {
                    IMediaFilter mediaFilter = (IMediaFilter)graphObject;
                    mediaFilter.SetSyncSource(null);
                }

                // get media control
                mediaControl = (IMediaControl)graphObject;

                // get media events' interface
                mediaEvent = (IMediaEventEx)graphObject;
                IntPtr   p1, p2;
                DsEvCode code;

                // run
                mediaControl.Run( );

                do
                {
                    if (mediaEvent != null)
                    {
                        if (mediaEvent.GetEvent(out code, out p1, out p2, 0) >= 0)
                        {
                            mediaEvent.FreeEventParams(code, p1, p2);

                            if (code == DsEvCode.Complete)
                            {
                                reasonToStop = ReasonToFinishPlaying.EndOfStreamReached;
                                break;
                            }
                        }
                    }
                }while (!stopEvent.WaitOne(100, false));

                mediaControl.Stop( );
            }
            catch (Exception exception)
            {
                // provide information to clients
                if (VideoSourceError != null)
                {
                    VideoSourceError(this, new VideoSourceErrorEventArgs(exception.Message));
                }
            }
            finally
            {
                // release all objects
                graph         = null;
                grabberBase   = null;
                sampleGrabber = null;
                mediaControl  = null;
                mediaEvent    = null;

                if (graphObject != null)
                {
                    Marshal.ReleaseComObject(graphObject);
                    graphObject = null;
                }
                if (sourceBase != null)
                {
                    Marshal.ReleaseComObject(sourceBase);
                    sourceBase = null;
                }
                if (grabberObject != null)
                {
                    Marshal.ReleaseComObject(grabberObject);
                    grabberObject = null;
                }
            }

            if (PlayingFinished != null)
            {
                PlayingFinished(this, reasonToStop);
            }
        }
Example #53
0
 public bool Transcode(TranscodeInfo info, VideoFormat format, Quality quality, Standard standard)
 {
     try
     {
         if (!Supports(format))
         {
             return(false);
         }
         string ext = System.IO.Path.GetExtension(info.file);
         if (ext.ToLower() != ".dvr-ms" && ext.ToLower() != ".sbe")
         {
             Log.Info("DVRMS2WMV: wrong file format");
             return(false);
         }
         Log.Info("DVRMS2WMV: create graph");
         graphBuilder = (IGraphBuilder) new FilterGraph();
         _rotEntry    = new DsROTEntry((IFilterGraph)graphBuilder);
         Log.Info("DVRMS2WMV: add streambuffersource");
         bufferSource = (IStreamBufferSource) new StreamBufferSource();
         IBaseFilter filter = (IBaseFilter)bufferSource;
         graphBuilder.AddFilter(filter, "SBE SOURCE");
         Log.Info("DVRMS2WMV: load file:{0}", info.file);
         IFileSourceFilter fileSource = (IFileSourceFilter)bufferSource;
         int hr = fileSource.Load(info.file, null);
         //add mpeg2 audio/video codecs
         string strVideoCodec = "";
         string strAudioCodec = "";
         using (MediaPortal.Profile.Settings xmlreader = new MediaPortal.Profile.MPSettings())
         {
             strVideoCodec = xmlreader.GetValueAsString("mytv", "videocodec", "MPC - MPEG-2 Video Decoder (Gabest)");
             strAudioCodec = xmlreader.GetValueAsString("mytv", "audiocodec", "MPC - MPA Decoder Filter");
         }
         Log.Info("DVRMS2WMV: add mpeg2 video codec:{0}", strVideoCodec);
         Mpeg2VideoCodec = DirectShowUtil.AddFilterToGraph(graphBuilder, strVideoCodec);
         if (hr != 0)
         {
             Log.Error("DVRMS2WMV:FAILED:Add mpeg2 video  to filtergraph :0x{0:X}", hr);
             Cleanup();
             return(false);
         }
         Log.Info("DVRMS2WMV: add mpeg2 audio codec:{0}", strAudioCodec);
         Mpeg2AudioCodec = DirectShowUtil.AddFilterToGraph(graphBuilder, strAudioCodec);
         if (Mpeg2AudioCodec == null)
         {
             Log.Error("DVRMS2WMV:FAILED:unable to add mpeg2 audio codec");
             Cleanup();
             return(false);
         }
         Log.Info("DVRMS2WMV: connect streambufer source->mpeg audio/video decoders");
         //connect output #0 of streambuffer source->mpeg2 audio codec pin 1
         //connect output #1 of streambuffer source->mpeg2 video codec pin 1
         IPin pinOut0, pinOut1;
         IPin pinIn0, pinIn1;
         pinOut0 = DsFindPin.ByDirection((IBaseFilter)bufferSource, PinDirection.Output, 0); //audio
         pinOut1 = DsFindPin.ByDirection((IBaseFilter)bufferSource, PinDirection.Output, 1); //video
         if (pinOut0 == null || pinOut1 == null)
         {
             Log.Error("DVRMS2WMV:FAILED:unable to get pins of source");
             Cleanup();
             return(false);
         }
         pinIn0 = DsFindPin.ByDirection(Mpeg2VideoCodec, PinDirection.Input, 0); //video
         pinIn1 = DsFindPin.ByDirection(Mpeg2AudioCodec, PinDirection.Input, 0); //audio
         if (pinIn0 == null || pinIn1 == null)
         {
             Log.Error("DVRMS2WMV:FAILED:unable to get pins of mpeg2 video/audio codec");
             Cleanup();
             return(false);
         }
         hr = graphBuilder.Connect(pinOut0, pinIn1);
         if (hr != 0)
         {
             Log.Error("DVRMS2WMV:FAILED:unable to connect audio pins :0x{0:X}", hr);
             Cleanup();
             return(false);
         }
         hr = graphBuilder.Connect(pinOut1, pinIn0);
         if (hr != 0)
         {
             Log.Error("DVRMS2WMV:FAILED:unable to connect video pins :0x{0:X}", hr);
             Cleanup();
             return(false);
         }
         string outputFilename = System.IO.Path.ChangeExtension(info.file, ".wmv");
         if (!AddWmAsfWriter(outputFilename, quality, standard))
         {
             return(false);
         }
         Log.Info("DVRMS2WMV: start pre-run");
         mediaControl = graphBuilder as IMediaControl;
         mediaSeeking = bufferSource as IStreamBufferMediaSeeking;
         mediaEvt     = graphBuilder as IMediaEventEx;
         mediaPos     = graphBuilder as IMediaPosition;
         //get file duration
         long lTime = 5 * 60 * 60;
         lTime *= 10000000;
         long pStop = 0;
         hr = mediaSeeking.SetPositions(new DsLong(lTime), AMSeekingSeekingFlags.AbsolutePositioning, new DsLong(pStop),
                                        AMSeekingSeekingFlags.NoPositioning);
         if (hr == 0)
         {
             long lStreamPos;
             mediaSeeking.GetCurrentPosition(out lStreamPos); // stream position
             m_dDuration = lStreamPos;
             lTime       = 0;
             mediaSeeking.SetPositions(new DsLong(lTime), AMSeekingSeekingFlags.AbsolutePositioning, new DsLong(pStop),
                                       AMSeekingSeekingFlags.NoPositioning);
         }
         double duration = m_dDuration / 10000000d;
         Log.Info("DVRMS2WMV: movie duration:{0}", Util.Utils.SecondsToHMSString((int)duration));
         hr = mediaControl.Run();
         if (hr != 0)
         {
             Log.Error("DVRMS2WMV:FAILED:unable to start graph :0x{0:X}", hr);
             Cleanup();
             return(false);
         }
         int maxCount = 20;
         while (true)
         {
             long lCurrent;
             mediaSeeking.GetCurrentPosition(out lCurrent);
             double dpos = (double)lCurrent;
             dpos /= 10000000d;
             System.Threading.Thread.Sleep(100);
             if (dpos >= 2.0d)
             {
                 break;
             }
             maxCount--;
             if (maxCount <= 0)
             {
                 break;
             }
         }
         Log.Info("DVRMS2WMV: pre-run done");
         Log.Info("DVRMS2WMV: Get duration of movie");
         mediaControl.Stop();
         FilterState state;
         mediaControl.GetState(500, out state);
         GC.Collect();
         GC.Collect();
         GC.Collect();
         GC.WaitForPendingFinalizers();
         Log.Info("DVRMS2WMV: reconnect mpeg2 video codec->ASF WM Writer");
         graphBuilder.RemoveFilter(fileWriterbase);
         if (!AddWmAsfWriter(outputFilename, quality, standard))
         {
             return(false);
         }
         Log.Info("DVRMS2WMV: Start transcoding");
         hr = mediaControl.Run();
         if (hr != 0)
         {
             Log.Error("DVRMS2WMV:FAILED:unable to start graph :0x{0:X}", hr);
             Cleanup();
             return(false);
         }
     }
     catch (Exception e)
     {
         // TODO: Handle exceptions.
         Log.Error("unable to transcode file:{0} message:{1}", info.file, e.Message);
         return(false);
     }
     return(true);
 }
Example #54
0
 private bool EncoderSet(IGraphBuilder graphBuilder, TranscodeInfo info)
 {
     //Add methods here to set encoder parameters
     return(true);
 }
Example #55
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() != ".ts" && ext.ToLower() != ".mpg")
            {
                Log.Info("TSReader2MP4: wrong file format");
                return(false);
            }
            try
            {
                graphBuilder = (IGraphBuilder) new FilterGraph();
                _rotEntry    = new DsROTEntry((IFilterGraph)graphBuilder);
                Log.Info("TSReader2MP4: add filesource");
                TsReader reader = new TsReader();
                tsreaderSource = (IBaseFilter)reader;
                IBaseFilter filter = (IBaseFilter)tsreaderSource;
                graphBuilder.AddFilter(filter, "TSReader Source");
                IFileSourceFilter fileSource = (IFileSourceFilter)tsreaderSource;
                Log.Info("TSReader2MP4: load file:{0}", info.file);
                int hr = fileSource.Load(info.file, null);
                //add audio/video codecs
                string strVideoCodec     = "";
                string strH264VideoCodec = "";
                string strAudioCodec     = "";
                string strAACAudioCodec  = "";
                using (MediaPortal.Profile.Settings xmlreader = new MediaPortal.Profile.MPSettings())
                {
                    strVideoCodec     = xmlreader.GetValueAsString("mytv", "videocodec", "");
                    strAudioCodec     = xmlreader.GetValueAsString("mytv", "audiocodec", "");
                    strAACAudioCodec  = xmlreader.GetValueAsString("mytv", "aacaudiocodec", "");
                    strH264VideoCodec = xmlreader.GetValueAsString("mytv", "h264videocodec", "");
                }
                //Find the type of decoder required for the output video & audio pins on TSReader.
                Log.Info("TSReader2MP4: find tsreader compatible audio/video decoders");
                IPin pinOut0, pinOut1;
                IPin pinIn0, pinIn1;
                pinOut0 = DsFindPin.ByDirection((IBaseFilter)tsreaderSource, PinDirection.Output, 0); //audio
                pinOut1 = DsFindPin.ByDirection((IBaseFilter)tsreaderSource, PinDirection.Output, 1); //video
                if (pinOut0 == null || pinOut1 == null)
                {
                    Log.Error("TSReader2MP4: FAILED: unable to get output pins of tsreader");
                    Cleanup();
                    return(false);
                }
                bool            usingAAC = false;
                IEnumMediaTypes enumMediaTypes;
                hr = pinOut0.EnumMediaTypes(out enumMediaTypes);
                while (true)
                {
                    AMMediaType[] mediaTypes = new AMMediaType[1];
                    int           typesFetched;
                    hr = enumMediaTypes.Next(1, mediaTypes, out typesFetched);
                    if (hr != 0 || typesFetched == 0)
                    {
                        break;
                    }
                    if (mediaTypes[0].majorType == MediaType.Audio && mediaTypes[0].subType == MediaSubType.LATMAAC)
                    {
                        Log.Info("TSReader2MP4: found LATM AAC audio out pin on tsreader");
                        usingAAC = true;
                    }
                }
                bool usingH264 = false;
                hr = pinOut1.EnumMediaTypes(out enumMediaTypes);
                while (true)
                {
                    AMMediaType[] mediaTypes = new AMMediaType[1];
                    int           typesFetched;
                    hr = enumMediaTypes.Next(1, mediaTypes, out typesFetched);
                    if (hr != 0 || typesFetched == 0)
                    {
                        break;
                    }
                    if (mediaTypes[0].majorType == MediaType.Video && mediaTypes[0].subType == AVC1)
                    {
                        Log.Info("TSReader2MP4: found H.264 video out pin on tsreader");
                        usingH264 = true;
                    }
                }
                //Add the type of decoder required for the output video & audio pins on TSReader.
                Log.Info("TSReader2MP4: add audio/video decoders to graph");
                if (usingH264 == false)
                {
                    Log.Info("TSReader2MP4: add mpeg2 video decoder:{0}", strVideoCodec);
                    VideoCodec = DirectShowUtil.AddFilterToGraph(graphBuilder, strVideoCodec);
                    if (VideoCodec == null)
                    {
                        Log.Error("TSReader2MP4: unable to add mpeg2 video decoder");
                        Cleanup();
                        return(false);
                    }
                }
                else
                {
                    Log.Info("TSReader2MP4: add h264 video codec:{0}", strH264VideoCodec);
                    VideoCodec = DirectShowUtil.AddFilterToGraph(graphBuilder, strH264VideoCodec);
                    if (VideoCodec == null)
                    {
                        Log.Error("TSReader2MP4: FAILED:unable to add h264 video codec");
                        Cleanup();
                        return(false);
                    }
                }
                if (usingAAC == false)
                {
                    Log.Info("TSReader2MP4: add mpeg2 audio codec:{0}", strAudioCodec);
                    AudioCodec = DirectShowUtil.AddFilterToGraph(graphBuilder, strAudioCodec);
                    if (AudioCodec == null)
                    {
                        Log.Error("TSReader2MP4: FAILED:unable to add mpeg2 audio codec");
                        Cleanup();
                        return(false);
                    }
                }
                else
                {
                    Log.Info("TSReader2MP4: add aac audio codec:{0}", strAACAudioCodec);
                    AudioCodec = DirectShowUtil.AddFilterToGraph(graphBuilder, strAACAudioCodec);
                    if (AudioCodec == null)
                    {
                        Log.Error("TSReader2MP4: FAILED:unable to add aac audio codec");
                        Cleanup();
                        return(false);
                    }
                }
                Log.Info("TSReader2MP4: connect tsreader->audio/video decoders");
                //connect output #0 (audio) of tsreader->audio decoder input pin 0
                //connect output #1 (video) of tsreader->video decoder input pin 0
                pinIn0 = DsFindPin.ByDirection(AudioCodec, PinDirection.Input, 0); //audio
                pinIn1 = DsFindPin.ByDirection(VideoCodec, PinDirection.Input, 0); //video
                if (pinIn0 == null || pinIn1 == null)
                {
                    Log.Error("TSReader2MP4: FAILED: unable to get pins of video/audio codecs");
                    Cleanup();
                    return(false);
                }
                hr = graphBuilder.Connect(pinOut0, pinIn0);
                if (hr != 0)
                {
                    Log.Error("TSReader2MP4: FAILED: unable to connect audio pins :0x{0:X}", hr);
                    Cleanup();
                    return(false);
                }
                hr = graphBuilder.Connect(pinOut1, pinIn1);
                if (hr != 0)
                {
                    Log.Error("TSReader2MP4: FAILED: unable to connect video pins :0x{0:X}", hr);
                    Cleanup();
                    return(false);
                }
                //add encoders, muxer & filewriter
                if (!AddCodecs(graphBuilder, info))
                {
                    return(false);
                }
                //setup graph controls
                mediaControl = graphBuilder as IMediaControl;
                mediaSeeking = tsreaderSource as IMediaSeeking;
                mediaEvt     = graphBuilder as IMediaEventEx;
                mediaPos     = graphBuilder as IMediaPosition;
                //get file duration
                Log.Info("TSReader2MP4: Get duration of recording");
                long lTime = 5 * 60 * 60;
                lTime *= 10000000;
                long pStop = 0;
                hr = mediaSeeking.SetPositions(new DsLong(lTime), AMSeekingSeekingFlags.AbsolutePositioning, new DsLong(pStop),
                                               AMSeekingSeekingFlags.NoPositioning);
                if (hr == 0)
                {
                    long lStreamPos;
                    mediaSeeking.GetCurrentPosition(out lStreamPos); // stream position
                    m_dDuration = lStreamPos;
                    lTime       = 0;
                    mediaSeeking.SetPositions(new DsLong(lTime), AMSeekingSeekingFlags.AbsolutePositioning, new DsLong(pStop),
                                              AMSeekingSeekingFlags.NoPositioning);
                }
                double duration = m_dDuration / 10000000d;
                Log.Info("TSReader2MP4: recording duration: {0}", MediaPortal.Util.Utils.SecondsToHMSString((int)duration));
                //run the graph to initialize the filters to be sure
                hr = mediaControl.Run();
                if (hr != 0)
                {
                    Log.Error("TSReader2MP4: FAILED: unable to start graph :0x{0:X}", hr);
                    Cleanup();
                    return(false);
                }
                int maxCount = 20;
                while (true)
                {
                    long lCurrent;
                    mediaSeeking.GetCurrentPosition(out lCurrent);
                    double dpos = (double)lCurrent;
                    dpos /= 10000000d;
                    System.Threading.Thread.Sleep(100);
                    if (dpos >= 2.0d)
                    {
                        break;
                    }
                    maxCount--;
                    if (maxCount <= 0)
                    {
                        break;
                    }
                }
                mediaControl.Stop();
                FilterState state;
                mediaControl.GetState(500, out state);
                GC.Collect();
                GC.Collect();
                GC.Collect();
                GC.WaitForPendingFinalizers();
                graphBuilder.RemoveFilter(mp4Muxer);
                graphBuilder.RemoveFilter(h264Encoder);
                graphBuilder.RemoveFilter(aacEncoder);
                graphBuilder.RemoveFilter((IBaseFilter)fileWriterFilter);
                if (!AddCodecs(graphBuilder, info))
                {
                    return(false);
                }
                //Set Encoder quality & Muxer settings
                if (!EncoderSet(graphBuilder, info))
                {
                    return(false);
                }
                //start transcoding - run the graph
                Log.Info("TSReader2MP4: start transcoding");
                //setup flow control
                //need to leverage CBAsePin, CPullPin & IAsyncReader methods.
                IAsyncReader synchVideo = null;
                mediaSample = VideoCodec as IMediaSample;
                hr          = synchVideo.SyncReadAligned(mediaSample);
                //So we only parse decoder output whent the encoders are ready.
                hr = mediaControl.Run();
                if (hr != 0)
                {
                    Log.Error("TSReader2MP4: FAILED:unable to start graph :0x{0:X}", hr);
                    Cleanup();
                    return(false);
                }
            }
            catch (Exception ex)
            {
                Log.Error("TSReader2MP4: Unable create graph: {0}", ex.Message);
                Cleanup();
                return(false);
            }
            return(true);
        }
Example #56
0
        private bool AddCodecs(IGraphBuilder graphBuilder, TranscodeInfo info)
        {
            //TODO: Add de-interlacing probably by filter
            int hr;

            Log.Info("TSReader2MP4: add h264 video encoder to graph");
            //Lead H264 Encoder (4.0)
            string monikerH264 = @"@device:sw:{083863F1-70DE-11D0-BD40-00A0C911CE86}\{E2B7DF52-38C5-11D5-91F6-00104BDB8FF9}";

            h264Encoder = Marshal.BindToMoniker(monikerH264) as IBaseFilter;
            if (h264Encoder == null)
            {
                Log.Error("TSReader2MP4: FAILED: Unable to create h264 video encoder");
                Cleanup();
                return(false);
            }
            hr = graphBuilder.AddFilter(h264Encoder, "h264 video encoder");
            if (hr != 0)
            {
                Log.Error("TSReader2MP4: FAILED: h264 video encoder to filtergraph :0x{0:X}", hr);
                Cleanup();
                return(false);
            }
            Log.Info("TSReader2MP4: add aac audio encoder to graph");
            //Monograph AAC Encoder
            //string monikerAAC = @"@device:sw:{083863F1-70DE-11D0-BD40-00A0C911CE86}\{88F36DB6-D898-40B5-B409-466A0EECC26A}";
            //Lead AAC Encoder
            string monikerAAC = @"@device:sw:{083863F1-70DE-11D0-BD40-00A0C911CE86}\{E2B7DD70-38C5-11D5-91F6-00104BDB8FF9}";

            aacEncoder = Marshal.BindToMoniker(monikerAAC) as IBaseFilter;
            if (aacEncoder == null)
            {
                Log.Error("TSReader2MP4: FAILED: Unable to create aac audio encoder");
                Cleanup();
                return(false);
            }
            hr = graphBuilder.AddFilter(aacEncoder, "aac audio encoder");
            if (hr != 0)
            {
                Log.Error("TSReader2MP4: FAILED: Add aac audio encoder to filtergraph :0x{0:X}", hr);
                Cleanup();
                return(false);
            }
            // dump filter ????
            //add filewriter
            Log.Info("TSReader2MP4: add FileWriter to graph");
            string monikerFileWrite =
                @"@device:sw:{083863F1-70DE-11D0-BD40-00A0C911CE86}\{8596E5F0-0DA5-11D0-BD21-00A0C911CE86}";
            IBaseFilter fileWriterbase = Marshal.BindToMoniker(monikerFileWrite) as IBaseFilter;

            if (fileWriterbase == null)
            {
                Log.Error("TSReader2MP4: FAILED: Unable to create FileWriter");
                Cleanup();
                return(false);
            }
            fileWriterFilter = fileWriterbase as IFileSinkFilter2;
            if (fileWriterFilter == null)
            {
                Log.Error("TSReader2MP4: FAILED: Add unable to get IFileSinkFilter for filewriter");
                Cleanup();
                return(false);
            }

            hr = graphBuilder.AddFilter(fileWriterbase, "FileWriter");
            if (hr != 0)
            {
                Log.Error("TSReader2MP4: FAILED: Add FileWriter to filtergraph :0x{0:X}", hr);
                Cleanup();
                return(false);
            }
            //set output filename
            string outputFileName = System.IO.Path.ChangeExtension(info.file, ".mp4");

            Log.Info("TSReader2MP4: set output file to :{0}", outputFileName);
            hr = fileWriterFilter.SetFileName(outputFileName, null);
            if (hr != 0)
            {
                Log.Error("TSReader2MP4: FAILED: unable to set filename for filewriter :0x{0:X}", hr);
                Cleanup();
                return(false);
            }
            // add mp4 muxer
            Log.Info("TSReader2MP4: add MP4 Muxer to graph");
            //Lead ISO Multiplexer
            string monikermp4Muxer =
                @"@device:sw:{083863F1-70DE-11D0-BD40-00A0C911CE86}\{990D1978-E48D-43AF-B12D-24A7456EC89F}";

            mp4Muxer = Marshal.BindToMoniker(monikermp4Muxer) as IBaseFilter;
            if (mp4Muxer == null)
            {
                Log.Error("TSReader2MP4: FAILED: Unable to create MP4Mux");
                Cleanup();
                return(false);
            }
            hr = graphBuilder.AddFilter(mp4Muxer, "MP4Mux");
            if (hr != 0)
            {
                Log.Error("TSReader2MP4: FAILED: Add MP4Mux to filtergraph :0x{0:X}", hr);
                Cleanup();
                return(false);
            }
            //connect output of audio codec to aac encoder
            IPin pinOut, pinIn;

            Log.Info("TSReader2MP4: connect audio codec->aac encoder");
            pinIn = DsFindPin.ByDirection(aacEncoder, PinDirection.Input, 0);
            if (pinIn == null)
            {
                Log.Error("TSReader2MP4: FAILED: cannot get input pin of aac encoder:0x{0:X}", hr);
                Cleanup();
                return(false);
            }
            pinOut = DsFindPin.ByDirection(AudioCodec, PinDirection.Output, 0);
            if (pinOut == null)
            {
                Log.Error("TSReader2MP4: FAILED: cannot get output pin of audio codec :0x{0:X}", hr);
                Cleanup();
                return(false);
            }
            hr = graphBuilder.Connect(pinOut, pinIn);
            if (hr != 0)
            {
                Log.Error("TSReader2MP4: FAILED: unable to connect audio codec->aac encoder: 0x{0:X}", hr);
                Cleanup();
                return(false);
            }
            //connect output of video codec to h264 encoder
            Log.Info("TSReader2MP4: connect video codec->h264 encoder");
            pinIn = DsFindPin.ByDirection(h264Encoder, PinDirection.Input, 0);
            if (pinIn == null)
            {
                Log.Error("TSReader2MP4: FAILED: cannot get input pin of h264 encoder:0x{0:X}", hr);
                Cleanup();
                return(false);
            }
            pinOut = DsFindPin.ByDirection(VideoCodec, PinDirection.Output, 0);
            if (pinOut == null)
            {
                Log.Error("TSReader2MP4: FAILED: cannot get output pin of video codec :0x{0:X}", hr);
                Cleanup();
                return(false);
            }
            hr = graphBuilder.Connect(pinOut, pinIn);
            if (hr != 0)
            {
                Log.Error("TSReader2MP4: FAILED: unable to connect video codec->h264 encoder :0x{0:X}", hr);
                Cleanup();
                return(false);
            }
            //connect output of aac encoder to pin#0 of mp4mux
            Log.Info("TSReader2MP4: connect aac encoder->mp4mux");
            pinOut = DsFindPin.ByDirection(aacEncoder, PinDirection.Output, 0);
            if (pinOut == null)
            {
                Log.Error("TSReader2MP4: FAILED: cannot get input pin of aac encoder:0x{0:X}", hr);
                Cleanup();
                return(false);
            }
            pinIn = DsFindPin.ByDirection(mp4Muxer, PinDirection.Input, 0);
            if (pinIn == null)
            {
                Log.Error("TSReader2MP4: FAILED: cannot get input pin#1 of mp4 muxer :0x{0:X}", hr);
                Cleanup();
                return(false);
            }
            hr = graphBuilder.Connect(pinOut, pinIn);
            if (hr != 0)
            {
                Log.Error("TSReader2MP4: FAILED: unable to connect aac encoder->mp4mux: 0x{0:X}", hr);
                Cleanup();
                return(false);
            }
            //connect output of h264 encoder to pin#1 of mp4mux
            Log.Info("TSReader2MP4: connect h264 encoder->mp4mux");
            pinOut = DsFindPin.ByDirection(h264Encoder, PinDirection.Output, 0);
            if (pinOut == null)
            {
                Log.Error("TSReader2MP4: FAILED: cannot get input pin of h264 encoder :0x{0:X}", hr);
                Cleanup();
                return(false);
            }
            pinIn = DsFindPin.ByDirection(mp4Muxer, PinDirection.Input, 1);
            if (pinIn == null)
            {
                Log.Error("TSReader2MP4: FAILED: cannot get input#0 pin of mp4mux :0x{0:X}", hr);
                Cleanup();
                return(false);
            }
            hr = graphBuilder.Connect(pinOut, pinIn);
            if (hr != 0)
            {
                Log.Error("TSReader2MP4: FAILED: unable to connect h264 encoder->mp4mux :0x{0:X}", hr);
                Cleanup();
                return(false);
            }
            // dump filter??
            //connect mp4 muxer out->filewriter
            Log.Info("TSReader2MP4: connect mp4mux->filewriter");
            pinOut = DsFindPin.ByDirection(mp4Muxer, PinDirection.Output, 0);
            if (pinOut == null)
            {
                Log.Error("TSReader2MP4: FAILED: cannot get output pin of avimux:0x{0:X}", hr);
                Cleanup();
                return(false);
            }
            pinIn = DsFindPin.ByDirection(fileWriterbase, PinDirection.Input, 0);
            if (pinIn == null)
            {
                Log.Error("TSReader2MP4: FAILED: cannot get input pin of filewriter :0x{0:X}", hr);
                Cleanup();
                return(false);
            }
            hr = graphBuilder.Connect(pinOut, pinIn);
            if (hr != 0)
            {
                Log.Error("TSReader2MP4: FAILED: connect mp4 muxer->filewriter :0x{0:X}", hr);
                Cleanup();
                return(false);
            }
            return(true);
        }
Example #57
0
        /// <summary> do cleanup and release DirectShow. </summary>
        void CloseInterfaces()
        {
            int hr;

            try
            {
#if DEBUG
                if (rotCookie != 0)
                {
                    DsROT.RemoveGraphFromRot(ref rotCookie);
                }
#endif

                if (mediaCtrl != null)
                {
                    hr        = mediaCtrl.Stop();
                    mediaCtrl = null;
                }

                if (mediaEvt != null)
                {
                    hr       = mediaEvt.SetNotifyWindow(IntPtr.Zero, WM_GRAPHNOTIFY, IntPtr.Zero);
                    mediaEvt = null;
                }

                if (videoWin != null)
                {
                    hr       = videoWin.put_Visible(DsHlp.OAFALSE);
                    hr       = videoWin.put_Owner(IntPtr.Zero);
                    videoWin = null;
                }

                baseGrabFlt = null;
                if (sampGrabber != null)
                {
                    Marshal.ReleaseComObject(sampGrabber);
                }
                sampGrabber = null;

                if (capGraph != null)
                {
                    Marshal.ReleaseComObject(capGraph);
                }
                capGraph = null;

                if (graphBuilder != null)
                {
                    Marshal.ReleaseComObject(graphBuilder);
                }
                graphBuilder = null;

                if (capFilter != null)
                {
                    Marshal.ReleaseComObject(capFilter);
                }
                capFilter = null;

                if (capDevices != null)
                {
                    foreach (DsDevice d in capDevices)
                    {
                        d.Dispose();
                    }
                    capDevices = null;
                }
            }
            catch (Exception)
            { }
        }
Example #58
0
 public InstanceParser(IGraphBuilder builder)
 {
     _builder = builder;
 }
Example #59
0
        /// <summary>
        /// デバッグ
        /// </summary>
        /// <param name="graph"></param>
        private void DebugPrint(IGraphBuilder graph)
        {
            IEnumFilters filters = null;
            IBaseFilter  filter  = null;
            int          fetched = 0;

            int hr = graph.EnumFilters(ref filters);

            while (filters.Next(1, ref filter, ref fetched) == (int)DSLab.HRESULT.S_OK)
            {
                if (fetched == 0)
                {
                    break;
                }

                FILTER_INFO info = new FILTER_INFO();
                hr = filter.QueryFilterInfo(info);
                Console.WriteLine("{0}", info.achName);

                // フィルタ解放.
                Marshal.ReleaseComObject(filter);
                filter = null;
            }

            // 解放.
            Marshal.ReleaseComObject(filters);

            // サンプルグラバフィルタの入力形式設定.
            // majortype: http://msdn.microsoft.com/ja-jp/library/cc370108.aspx
            // subtype  : http://msdn.microsoft.com/ja-jp/library/cc371040.aspx
            AM_MEDIA_TYPE media_type = new AM_MEDIA_TYPE();

            SampleGrabber.GetConnectedMediaType(media_type);

            Debug.WriteLine("{0}:{1}", "majortype", media_type.majortype);
            Debug.WriteLine("{0}:{1}", "subtype", media_type.subtype);
            Debug.WriteLine("{0}:{1}", "formattype", media_type.formattype);
            Debug.WriteLine("{0}:{1}", "bFixedSizeSamples", media_type.bFixedSizeSamples);
            Debug.WriteLine("{0}:{1}", "bTemporalCompression", media_type.bTemporalCompression);
            Debug.WriteLine("{0}:{1}", "cbFormat", media_type.cbFormat);
            Debug.WriteLine("{0}:{1}", "lSampleSize", media_type.lSampleSize);
            Debug.WriteLine("{0}:{1}", "pbFormat", media_type.pbFormat);
            Debug.WriteLine("{0}:{1}", "pUnk", media_type.pUnk);

            // 映像形式の場合、サイズを取得する.
            if (GUID.Compare(media_type.formattype.ToString(), GUID.FORMAT_VideoInfo))
            {
                VIDEOINFOHEADER vinfo = new VIDEOINFOHEADER();
                vinfo = (VIDEOINFOHEADER)Marshal.PtrToStructure(media_type.pbFormat, typeof(VIDEOINFOHEADER));

                Debug.WriteLine("{0}:{1}", "Width", vinfo.bmiHeader.biWidth);
                Debug.WriteLine("{0}:{1}", "Height", vinfo.bmiHeader.biHeight);
                Debug.WriteLine("{0}:{1}", "BitCount", vinfo.bmiHeader.biBitCount);
                Debug.WriteLine("{0}:{1}", "Size", vinfo.bmiHeader.biSize);
                Debug.WriteLine("{0}:{1}", "ImageSize", vinfo.bmiHeader.biSizeImage);
                Debug.WriteLine("{0}:{1}", "ClrImportant", vinfo.bmiHeader.biClrImportant);
                Debug.WriteLine("{0}:{1}", "ClrUsed", vinfo.bmiHeader.biClrUsed);
                Debug.WriteLine("{0}:{1}", "Compression", vinfo.bmiHeader.biCompression);
                Debug.WriteLine("{0}:{1}", "Planes", vinfo.bmiHeader.biPlanes);
                Debug.WriteLine("{0}:{1}", "XPelsPerMeter", vinfo.bmiHeader.biXPelsPerMeter);
                Debug.WriteLine("{0}:{1}", "YPelsPerMeter", vinfo.bmiHeader.biYPelsPerMeter);
            }
        }
Example #60
0
        /// <summary>
        /// グラフの生成
        /// </summary>
        public virtual void Setup()
        {
            this.Dispose();

            try
            {
                // グラフ.
                // CoCreateInstance
                GraphBuilder = (IGraphBuilder)Activator.CreateInstance(Type.GetTypeFromCLSID(new Guid(GUID.CLSID_FilterGraph)));

                #region フィルタ追加.
                // ファイル入力.
                IBaseFilter capture = null;
                GraphBuilder.AddSourceFilter(SourceFile, "CaptureFilter", ref capture);
                if (capture == null)
                {
                    throw new System.IO.IOException();
                }

#if false
                // DMO ラッパーフィルタ.
                // https://msdn.microsoft.com/ja-jp/library/cc371140.aspx
                IBaseFilter dmo = (IBaseFilter)Activator.CreateInstance(Type.GetTypeFromCLSID(new Guid(GUID.CLSID_DMOWrapperFilter)));
                if (dmo != null)
                {
                    //// Mpeg4 Decoder DMO
                    //// F371728A-6052-4D47-827C-D039335DFE0A
                    //// 4A69B442-28BE-4991-969C-B500ADF5D8A8
                    //// mpg4decd.dll [C:\Windows\System32, C:\Windows\SysWOW64]

                    var idmo = (IDMOWrapperFilter)dmo;
                    idmo.Init(new Guid("F371728A-6052-4D47-827C-D039335DFE0A"), new Guid("4A69B442-28BE-4991-969C-B500ADF5D8A8"));
                    idmo = null;

                    this.GraphBuilder.AddFilter(dmo, "Mpeg4 Decoder DMO");
                }
#endif

#if false
                // Avi Splitter
                IBaseFilter splitter = (IBaseFilter)Activator.CreateInstance(Type.GetTypeFromCLSID(new Guid(GUID.CLSID_AVISplitter)));
                if (splitter == null)
                {
                    throw new System.IO.IOException();
                }
                this.GraphBuilder.AddFilter(splitter, "Avi Splitter");

                // Avi Decompressor
                IBaseFilter decompressor = (IBaseFilter)Activator.CreateInstance(Type.GetTypeFromCLSID(new Guid(GUID.CLSID_AVIDec)));
                if (decompressor == null)
                {
                    throw new System.IO.IOException();
                }
                this.GraphBuilder.AddFilter(decompressor, "Avi Decompressor");
#endif

                // サンプルグラバー.
                IBaseFilter grabber = (IBaseFilter)CreateSampleGrabber();
                if (grabber == null)
                {
                    throw new System.IO.IOException();
                }
                this.GraphBuilder.AddFilter(grabber, "SampleGrabber");

                // レンダラー.
                IBaseFilter renderer = (IBaseFilter)Activator.CreateInstance(Type.GetTypeFromCLSID(new Guid(GUID.CLSID_NullRenderer)));
                if (renderer == null)
                {
                    throw new System.IO.IOException();
                }
                this.GraphBuilder.AddFilter(renderer, "Renderer");
                #endregion

                #region ピンの取得.
                IPin capture_out = DSLab.Axi.FindPin(capture, 0, PIN_DIRECTION.PINDIR_OUTPUT);
                IPin grabber_in  = DSLab.Axi.FindPin(grabber, 0, PIN_DIRECTION.PINDIR_INPUT);
                IPin grabber_out = DSLab.Axi.FindPin(grabber, 0, PIN_DIRECTION.PINDIR_OUTPUT);
                IPin renderer_in = DSLab.Axi.FindPin(renderer, 0, PIN_DIRECTION.PINDIR_INPUT);
                #endregion

                #region ピンの接続.
                GraphBuilder.Connect(capture_out, grabber_in);
                GraphBuilder.Connect(grabber_out, renderer_in);
                #endregion

                #region 保管: インターフェース.
                CaptureFilter       = capture;
                CaptureOutPin       = capture_out;
                SampleGrabber       = (ISampleGrabber)grabber;
                SampleGrabberInPin  = grabber_in;
                SampleGrabberOutPin = grabber_out;
                Renderer            = renderer;
                RendererInPin       = renderer_in;
                #endregion

                #region 保管: フレームサイズ.
                VIDEOINFOHEADER vinfo = DSLab.Axi.GetVideoInfo(SampleGrabber);
                this.SampleGrabberCB.BitmapInfo = vinfo.bmiHeader;
                this.SampleGrabberCB.FrameSize  = new Size(
                    System.Math.Abs(this.SampleGrabberCB.BitmapInfo.biWidth),
                    System.Math.Abs(this.SampleGrabberCB.BitmapInfo.biHeight)
                    );
                #endregion

                #region インタフェースの抽出:
                {
                    DSLab.IGraphBuilder graph   = this.GraphBuilder;
                    DSLab.IEnumFilters  filters = null;
                    DSLab.IBaseFilter   filter  = null;
                    int fetched = 0;

                    int hr = graph.EnumFilters(ref filters);
                    while (filters.Next(1, ref filter, ref fetched) == (int)DSLab.HRESULT.S_OK)
                    {
                        if (fetched == 0)
                        {
                            break;
                        }

                        if (filter is DSLab.IMediaSeeking)
                        {
                            // シーク操作用.
                            Seeking = (DSLab.IMediaSeeking)filter;
                        }
                        else
                        {
                            // フィルタ解放.
                            Marshal.ReleaseComObject(filter);
                            filter = null;
                        }
                    }

                    // 解放.
                    Marshal.ReleaseComObject(filters);
                }
                #endregion

                // DEBUG
#if DEBUG
                DebugPrint(this.GraphBuilder);
#endif
            }
            catch (Exception ex)
            {
                throw new DSLab.CxDSException(ex);
            }
        }