示例#1
0
 private SerializationContext(ContextMode contextMode, IStreamSource streamSource, SerializerMode serializerMode, BackgroundStream parentStream)
 {
     ContextMode       = contextMode;
     StreamSource      = Argument.NotNull(streamSource, nameof(streamSource));
     SerializerMode    = Argument.NotNull(serializerMode, nameof(serializerMode));
     _backgroundStream = Argument.NotNull(parentStream, nameof(parentStream));
 }
示例#2
0
        public async Task <Task> Recovery(StreamMessage msg)
        {
            List <TopologyUnit> units = topology.GetAllTopologyUnits();

            msg.barrierOrCommitInfo         = new BarrierOrCommitMsgTrackingInfo(Guid.NewGuid(), units.Count);
            msg.barrierOrCommitInfo.BatchID = msg.BatchID;
            await batchTracker.TrackingRecoveryMessages(msg);

            foreach (TopologyUnit unit in units)
            {
                if (unit.OperatorType == OperatorType.Source)
                {
                    IStreamSource source = GrainFactory.GetGrain <IStreamSource>(unit.PrimaryKey);
                    source.Recovery(msg);
                }
                else if (unit.OperatorType == OperatorType.Stateful)
                {
                    IStatefulOperator statefulOperator = GrainFactory.GetGrain <IStatefulOperator>(unit.PrimaryKey, Constants.Stateful_Operator_Prefix);
                    statefulOperator.Recovery(msg);
                }
                else if (unit.OperatorType == OperatorType.Stateless)
                {
                    IStatelessOperator statelessOperator = GrainFactory.GetGrain <IStatelessOperator>(unit.PrimaryKey, Constants.Stateless_Operator_Prefix);
                    statelessOperator.Recovery(msg);
                }
                else
                {
                    throw new ArgumentException("Recovery: The operator type is in valid!");
                }
            }
            return(Task.CompletedTask);
        }
示例#3
0
 public SerializationContext(ContextMode contextMode, IStreamSource streamSource, SerializerMode serializerMode)
 {
     ContextMode       = contextMode;
     StreamSource      = Argument.NotNull(streamSource, nameof(streamSource));
     SerializerMode    = Argument.NotNull(serializerMode, nameof(serializerMode));
     _backgroundStream = new BackgroundStream();
 }
示例#4
0
        private void Close()
        {
            lock (lockObject)
            {
                if (streamSource != null)
                {
                    streamSource.Dispose();
                    streamSource = null;
                }

                if (this.configurator != null)
                {
                    this.configurator.Dispose();
                    this.configurator = null;
                }

                if (this.mediaControl != null)
                {
                    this.mediaControl.Stop();
                    this.mediaControl = null;
                }

                if (this.filterGraph != null)
                {
                    ((IMediaEventSink)this.filterGraph).Notify(EventCode.UserAbort, IntPtr.Zero, IntPtr.Zero);

                    Marshal.ReleaseComObject(this.filterGraph);
                    this.filterGraph = null;
                }
            }

            GC.Collect();
        }
示例#5
0
        IStreamSource IStreamResolver.ResolveInclude(IStreamSource baseStream, string includePath)
        {
            if (includePath == "%code%")
            {
                StringBuilder sb = new StringBuilder(4096);
                StringWriter  sw = new StringWriter(sb);

                sw.WriteLine();
                GenerateScriptCore(sw);

                string compiledCode = sb.ToString();
                return(new CodeStreamSource(compiledCode));
            }
            else
            {
                IStreamResolver resolver = baseStream as IStreamResolver;
                if (resolver != null)
                {
                    return(resolver.ResolveInclude(baseStream, includePath));
                }

                string resolvedPath = Path.Combine(Path.GetDirectoryName(Path.GetFullPath(baseStream.FullName)), includePath);
                return(new FileInputStreamSource(resolvedPath));
            }
        }
示例#6
0
        private void SetupGraph(Control hWin)
        {
            //streamSource = new UdpSource("127.0.0.1", 2001);
            streamSource = new UdpSource("224.0.0.1", 2002);
            //streamSource = new Core.Sources.FileSource("test.ts");

            streamSource.PacketLength = Constants.TSPacketSize;
            streamSource.SearchMethod = TSUtils.TSPacketSearch;

            streamSource.Configure();

            if (!streamSource.Require(10))
            {
                throw new Exception("Source is not ready. No data is received.");
            }

            Log.Info("Identify the A/V streams");
            var streamInfo = new TStreamInfo(streamSource);

            streamInfo.Configure();

            streamSource.Reset();

            filterGraph = new FilterGraph() as IFilterGraph2;
            Ensure.IsNotNull(Log, filterGraph, "graph is null");
            if (filterGraph == null)
            {
                return;
            }

            var pVideoRender = (IBaseFilter) new VideoRendererDefault();
            var hr           = filterGraph.AddFilter(pVideoRender, "Video Renderer");

            DsError.ThrowExceptionForHR(hr);

            var pAudioRender = (IBaseFilter) new DSoundRender();

            hr = filterGraph.AddFilter(pAudioRender, "Audio Render");
            DsError.ThrowExceptionForHR(hr);

            Log.Info("Configure the directshow graph.");
            configurator = new GraphConfigurator
            {
                Source       = streamSource,
                StreamInfo   = streamInfo,
                Graph        = filterGraph,
                VideoRender  = pVideoRender,
                AudioRender  = pAudioRender,
                VideoGrabber = null,
                AudioGrabber = null
            };

            configurator.Configure();

            var videoWindow = pVideoRender as IVideoWindow;

            ConfigureVideoWindow(videoWindow, hWin);

            this.mediaControl = this.filterGraph as IMediaControl;
        }
示例#7
0
        private void Dispose(bool disposing)
        {
            if (this.disposed)
            {
                return;
            }

            if (disposing)
            {
                this.source       = null;
                this.streamInfo   = null;
                this.graph        = null;
                this.videoRender  = null;
                this.audioRender  = null;
                this.videoGrabber = null;
                this.audioGrabber = null;

                if (this.sampleHandler != null)
                {
                    this.sampleHandler.Dispose();
                    this.sampleHandler = null;
                }

                this.isConfigured = false;
            }

            this.disposed = true;
        }
        public object Deserialize(IStreamSource target)
        {
            Argument.NotNull(target, nameof(target));

            using var stream = target.OpenStream(FileAccess.ReadWrite);
            return(_formatter.Deserialize(stream));
        }
示例#9
0
        private string PreprocessTemplate(string template)
        {
            if (options.IncludeResolver == null)
            {
                return(template);
            }

            Regex includePattern = new Regex("\\{include:([^\\}]+)\\}",
                                             RegexOptions.Multiline | RegexOptions.CultureInvariant);

            return(includePattern.Replace(template, delegate(Match include)
            {
                string includedScript = string.Empty;

                if (include.Groups.Count == 2)
                {
                    string includePath = include.Groups[1].Value;

                    IStreamSource includeSource = options.IncludeResolver.Resolve(includePath);

                    if (includeSource != null)
                    {
                        Stream includeStream = includeSource.GetStream();
                        StreamReader reader = new StreamReader(includeStream);

                        includedScript = reader.ReadToEnd();
                        includeSource.CloseStream(includeStream);
                    }
                }

                return includedScript;
            }));
        }
        public CompilationUnitNode BuildCodeModel(IStreamSource source)
        {
            _hasErrors = false;

            string filePath = source.FullName;

#if DEBUG
            if (_options.InternalTestMode)
            {
                // This ensures in file paths are just file names in test output.
                filePath = Path.GetFileName(filePath);
            }
#endif // DEBUG
            char[] buffer = GetBuffer(source);
            if (buffer == null)
            {
                _errorHandler.ReportError("Unable to read from file " + filePath, filePath);
                return(null);
            }

            IDictionary definesTable = new Hashtable();
            if ((_options.Defines != null) && (_options.Defines.Count != 0))
            {
                foreach (string s in _options.Defines)
                {
                    definesTable[s] = null;
                }
            }

            NameTable nameTable = new NameTable();
            LineMap   lineMap   = new LineMap(filePath);

            FileLexer lexer = new FileLexer(nameTable, filePath);
            lexer.OnError += new FileErrorEventHandler(OnError);
            Token[] tokens = lexer.Lex(buffer, definesTable, lineMap, /* includeComments */ false);

            if (_hasErrors == false)
            {
                FileParser parser = new FileParser(nameTable, filePath);
                parser.OnError += new FileErrorEventHandler(OnError);

                CompilationUnitNode compilationUnit = parser.Parse(tokens, lineMap);
                foreach (ParseNode node in compilationUnit.Members)
                {
                    NamespaceNode namespaceNode = node as NamespaceNode;
                    if (namespaceNode != null)
                    {
                        namespaceNode.IncludeCompilationUnitUsingClauses();
                    }
                }

                if (_hasErrors == false)
                {
                    return(compilationUnit);
                }
            }

            return(null);
        }
示例#11
0
        public WFQYDBServer(IStreamSource streamSource, byte[] SourceAddress, CancellationToken cancellationToken)
        {
            this.streamSource      = streamSource;
            this.ServerAddress     = SourceAddress;
            this.cancellationToken = cancellationToken;

            Task.Run(Monitor, cancellationToken).ConfigureAwait(false);
        }
        public virtual object Deserialize(IStreamSource target)
        {
            var garph = BuildObject();

            Progress(garph, target, SerializerMode.Deserialize);

            return(garph);
        }
示例#13
0
        public SimpleCompilation(string outputPath)
        {
            _references = new List <string>();
            _sources    = new List <IStreamSource>();
            _output     = new FileStreamSource(outputPath, writable: true);

            _options          = new CompilerOptions();
            _options.Minimize = false;
        }
        public SimpleCompilation(string outputPath)
        {
            _references = new List<string>();
            _sources = new List<IStreamSource>();
            _output = new FileStreamSource(outputPath, writable: true);

            _options = new CompilerOptions();
            _options.Minimize = false;
        }
        private void ProcessIncludeInstruction(string instructionLine, bool skipPreprocessing)
        {
            Debug.Assert(_includeStream == null);
            Debug.Assert(_includeTextReader == null);

            bool included        = false;
            int  beginQuoteIndex = instructionLine.IndexOf('"');
            int  endQuoteIndex   = 0;

            if (beginQuoteIndex > 0)
            {
                endQuoteIndex = instructionLine.IndexOf('"', beginQuoteIndex + 1);
            }

            if (endQuoteIndex > 0)
            {
                Exception resolveException = null;
                string    includePath      = instructionLine.Substring(beginQuoteIndex + 1, endQuoteIndex - beginQuoteIndex - 1);
                try {
                    _include = _includeResolver.ResolveInclude(_source, includePath);

                    if (_include != null)
                    {
                        _includeStream = _include.GetStream();
                        if (_includeStream != null)
                        {
                            _includeTextReader  = new StreamReader(_includeStream);
                            _includeLineCounter = 0;

                            if (skipPreprocessing)
                            {
                                string includeText = _includeTextReader.ReadToEnd();
                                _skipPreprocessingWriter.Write(includeText);

                                _include.CloseStream(_includeStream);
                                _includeTextReader = null;
                                _includeStream     = null;

                                included = true;
                            }
                        }
                    }
                }
                catch (Exception e) {
                    resolveException = e;
                }

                if ((included == false) && (_includeTextReader == null))
                {
                    RaiseError("Unable to resolve or open included file '" + includePath + "'", resolveException);
                }
            }
            else
            {
                RaiseError("Invalid #include instruction.");
            }
        }
示例#16
0
        private async Task <Task> DetectPossibleFailures(object org)
        {
            PrettyConsole.Line("Start Detect Failures");
            Dictionary <Guid, Task <int> > taskMap  = new Dictionary <Guid, Task <int> >();
            List <Task <int> >             taskList = new List <Task <int> >();
            var topologyManager = GrainFactory.GetGrain <ITopology>(Constants.Topology_Manager);
            var operatorUnits   = await topologyManager.GetAllUnits();

            foreach (TopologyUnit unit in operatorUnits)
            {
                if (unit.OperatorType == OperatorType.Source)
                {
                    IStreamSource source = GrainFactory.GetGrain <IStreamSource>(unit.PrimaryKey);
                    var           task   = source.DetectErrors();
                    taskMap.Add(unit.PrimaryKey, task);
                }
                else if (unit.OperatorType == OperatorType.Stateful)
                {
                    IStatefulOperator statefulOperator = GrainFactory.GetGrain <IStatefulOperator>(unit.PrimaryKey, Constants.Stateful_Operator_Prefix);
                    var task = statefulOperator.DetectErrors();
                    taskMap.Add(unit.PrimaryKey, task);
                }
                else if (unit.OperatorType == OperatorType.Stateless)
                {
                    IStatelessOperator statelessOperator = GrainFactory.GetGrain <IStatelessOperator>(unit.PrimaryKey, Constants.Stateless_Operator_Prefix);
                    var task = statelessOperator.DetectErrors();
                    taskMap.Add(unit.PrimaryKey, task);
                }
                else
                {
                    throw new ArgumentException("Commit: The operator type is in valid!");
                }
            }

            try
            {
                await Task.WhenAny(Task.WhenAll(taskMap.Values), Task.Delay(TimeSpan.FromSeconds(2)));
            }
            catch (Exception e)
            {
                PrettyConsole.Line(e.ToString());
            }

            foreach (var task in taskMap)
            {
                if (task.Value.Status != TaskStatus.RanToCompletion)
                {
                    PrettyConsole.Line("Replace!");
                    await topologyManager.ReplaceTheOldOperator(task.Key);

                    disposable.Dispose();
                    break;
                }
            }

            return(Task.CompletedTask);
        }
示例#17
0
        public CompilationUnitNode BuildCodeModel(IStreamSource source)
        {
            hasErrors = false;

            string filePath = source.FullName;

            char[] buffer = GetBuffer(source);

            if (buffer == null)
            {
                errorHandler.ReportInputError(filePath);

                return(null);
            }

            IDictionary definesTable = new Hashtable();

            if (options.Defines != null && options.Defines.Count != 0)
            {
                foreach (string s in options.Defines)
                {
                    definesTable[s] = null;
                }
            }

            NameTable nameTable = new NameTable();
            LineMap   lineMap   = new LineMap(filePath);

            FileLexer lexer = new FileLexer(nameTable, filePath);

            lexer.OnError += OnError;
            Token[] tokens = lexer.Lex(buffer, definesTable, lineMap, /* includeComments */ false);

            if (hasErrors == false)
            {
                FileParser parser = new FileParser(nameTable, filePath);
                parser.OnError += OnError;

                CompilationUnitNode compilationUnit = parser.Parse(tokens, lineMap);

                foreach (ParseNode node in compilationUnit.Members)
                {
                    if (node is NamespaceNode namespaceNode)
                    {
                        namespaceNode.IncludeCompilationUnitUsingClauses();
                    }
                }

                if (hasErrors == false)
                {
                    return(compilationUnit);
                }
            }

            return(null);
        }
示例#18
0
        public DictionaryStream(string name, IStreamSource streamSource)
        {
            if (string.IsNullOrWhiteSpace(name))
            {
                throw new System.ArgumentException("message", nameof(name));
            }

            Name = name;
            this.streamSource = streamSource ?? throw new System.ArgumentNullException(nameof(streamSource));
        }
        public CompressedDictionaryStream(string name, IStreamSource streamSource)
        {
            if (string.IsNullOrEmpty(name))
            {
                throw new ArgumentException("message", nameof(name));
            }

            Name = name;
            this.streamSource = streamSource ?? throw new ArgumentNullException(nameof(streamSource));
        }
        public void Serialize(IStreamSource target, object graph)
        {
            Argument.NotNull(target, nameof(target));
            Argument.NotNull(graph, nameof(graph));

            using (var stream = target.OpenStream(FileAccess.ReadWrite))
            {
                _formatter.Serialize(stream, graph);
            }
        }
示例#21
0
        public static IEnumerable <byte> ToIEnumerable(this IStreamSource input)
        {
            var stream = input.OpenStream();
            var ienum  = ToIEnumerator(stream);

            while (ienum.MoveNext())
            {
                yield return(ienum.Current);
            }
        }
示例#22
0
        private void BuildResources(IStreamSource source)
        {
            string resxMarkup = GetMarkup(source);
            List<ResXItem> resourceItems = ResXParser.ParseResxMarkup(resxMarkup);

            string resourceName = Utility.GetResourceFileName(source.Name);
            Dictionary<string, ResXItem> existingResourceItems = symbols.GetResources(resourceName);

            foreach (ResXItem item in resourceItems) existingResourceItems[item.Name] = item;
        }
示例#23
0
        public static IEnumerable <T> ToIEnumerable <T>(this IStreamSource input) where T : struct
        {
            var stream = input.OpenStream();
            var ienum  = ToIEnumerator <T>(stream);

            while (ienum.MoveNext())
            {
                yield return(ienum.Current);
            }
        }
示例#24
0
        private void BuildResources(IStreamSource source) {
            string resxMarkup = GetMarkup(source);
            List<ResXItem> resourceItems = ResXParser.ParseResxMarkup(resxMarkup);

            string resourceName = Utility.GetResourceFileName(source.Name);
            Dictionary<string, ResXItem> existingResourceItems = _symbols.GetResources(resourceName);

            foreach (ResXItem item in resourceItems) {
                existingResourceItems[item.Name] = item;
            }
        }
示例#25
0
        public void ConnectDependencies()
        {
            m_Sources.UnionWith(GetComponentsInChildren <IStreamSource>());
            foreach (var go in m_StreamSourceOverrides)
            {
                m_Sources.UnionWith(go.GetComponentsInChildren <IStreamSource>());
            }

            foreach (var source in m_Sources)
            {
                ConnectInterfaces(source);
                if (source is NetworkStream)
                {
                    streamSource = source;
                }
            }

            if (m_Character != null)
            {
                blendShapesController = m_BlendShapesControllerOverride != null
                    ? m_BlendShapesControllerOverride
                    : m_Character.GetComponentInChildren <BlendShapesController>();

                characterRigController = m_CharacterRigControllerOverride != null
                    ? m_CharacterRigControllerOverride
                    : m_Character.GetComponentInChildren <CharacterRigController>();

                headBone = m_HeadBoneOverride != null
                    ? m_HeadBoneOverride
                    : characterRigController != null
                        ? characterRigController.headBone
                        : null;
            }
            else
            {
                blendShapesController  = m_BlendShapesControllerOverride;
                characterRigController = m_CharacterRigControllerOverride;
                headBone = m_HeadBoneOverride;
            }

            cameraTransform = m_CameraOverride == null ? Camera.main.transform : m_CameraOverride.transform;

            if (blendShapesController != null)
            {
                ConnectInterfaces(blendShapesController);
            }

            if (characterRigController != null)
            {
                ConnectInterfaces(characterRigController);
            }
        }
示例#26
0
        private char[] GetBuffer(IStreamSource source) {
            char[] buffer = null;

            Stream stream = source.GetStream();
            if (stream != null) {
                StreamReader reader = new StreamReader(stream);
                string text = reader.ReadToEnd();

                buffer = text.ToCharArray();
                source.CloseStream(stream);
            }
            return buffer;
        }
示例#27
0
        public CompilationUnitNode BuildCodeModel(IStreamSource source)
        {
            _hasErrors = false;

            string filePath = source.FullName;
            #if DEBUG
            if (_options.InternalTestMode) {
                // This ensures in file paths are just file names in test output.
                filePath = Path.GetFileName(filePath);
            }
            #endif // DEBUG
            char[] buffer = GetBuffer(source);
            if (buffer == null) {
                _errorHandler.ReportError("Unable to read from file " + filePath, filePath);
                return null;
            }

            IDictionary definesTable = new Hashtable();
            if ((_options.Defines != null) && (_options.Defines.Count != 0)) {
                foreach (string s in _options.Defines) {
                    definesTable[s] = null;
                }
            }

            NameTable nameTable = new NameTable();
            LineMap lineMap = new LineMap(filePath);

            FileLexer lexer = new FileLexer(nameTable, filePath);
            lexer.OnError += new FileErrorEventHandler(OnError);
            Token[] tokens = lexer.Lex(buffer, definesTable, lineMap, /* includeComments */ false);

            if (_hasErrors == false) {
                FileParser parser = new FileParser(nameTable, filePath);
                parser.OnError += new FileErrorEventHandler(OnError);

                CompilationUnitNode compilationUnit = parser.Parse(tokens, lineMap);
                foreach (ParseNode node in compilationUnit.Members) {
                    NamespaceNode namespaceNode = node as NamespaceNode;
                    if (namespaceNode != null) {
                        namespaceNode.IncludeCompilationUnitUsingClauses();
                    }
                }

                if (_hasErrors == false) {
                    return compilationUnit;
                }
            }

            return null;
        }
示例#28
0
        private void Dispose(bool disposing)
        {
            if (this.disposed)
            {
                return;
            }

            if (disposing)
            {
                this.streamSource = null;
            }

            this.disposed = true;
        }
示例#29
0
        private void Dispose(bool disposing)
        {
            if (this.disposed)
            {
                return;
            }

            if (disposing)
            {
                this.source       = null;
                this.isConfigured = false;
            }

            this.disposed = true;
        }
示例#30
0
        private string GetMarkup(IStreamSource source) {
            string markup = null;

            Stream stream = source.GetStream();
            try {
                StreamReader reader = new StreamReader(stream);
                markup = reader.ReadToEnd();
            }
            finally {
                if (stream != null) {
                    source.CloseStream(stream);
                    stream = null;
                }
            }
            return markup;
        }
        private char[] GetBuffer(IStreamSource source)
        {
            char[] buffer = null;

            Stream stream = source.GetStream();

            if (stream != null)
            {
                StreamReader reader = new StreamReader(stream);
                string       text   = reader.ReadToEnd();

                buffer = text.ToCharArray();
                source.CloseStream(stream);
            }
            return(buffer);
        }
        private async Task <Task> SetUpSource2()
        {
            source2 = client.GetGrain <IStreamSource>(Guid.NewGuid());
            await source2.InitDeaultOperators();

            var streamId = await source2.Join(userName);

            var stream = client.GetStreamProvider(Constants.FaultTolerantStreamProvider)
                         .GetStream <StreamMessage>(streamId, Constants.FaultTolerantStreamNameSpace);
            //subscribe to the stream to receiver furthur messages sent to the chatroom
            Mock <ILogger> mockLogger = new Mock <ILogger>();

            statefulStreamObserver = new StatefulStreamObserver(mockLogger.Object);
            await stream.SubscribeAsync(statefulStreamObserver);

            return(Task.CompletedTask);
        }
        public PreprocessorTextReader(IStreamSource source, ICollection<string> predefinedVariables, IStreamResolver includeResolver, IScriptInfo scriptInfo) {
            Debug.Assert(source != null);

            _source = source;
            _includeResolver = includeResolver;
            _scriptInfo = scriptInfo;

            _definedVariables = new Dictionary<string, string>();
            _activeInstructions = new Stack<Instruction>();

            if ((predefinedVariables != null) && (predefinedVariables.Count != 0)) {
                foreach (string s in predefinedVariables) {
                    _definedVariables[s] = String.Empty;
                }
            }

            _currentLinePosition = -1;
        }
        private string GetMarkup(IStreamSource source)
        {
            string markup = null;

            Stream stream = source.GetStream();

            try {
                StreamReader reader = new StreamReader(stream);
                markup = reader.ReadToEnd();
            }
            finally {
                if (stream != null)
                {
                    source.CloseStream(stream);
                    stream = null;
                }
            }
            return(markup);
        }
示例#35
0
        private void ConfigureAudioStream(IMediaParserMediaStream audio)
        {
            IAudioConfigurationSource configurationSource            = (IAudioConfigurationSource)audio.ConfigurationSource;
            Dictionary <MediaStreamAttributeKeys, string> dictionary = new Dictionary <MediaStreamAttributeKeys, string>();
            string codecPrivateData = configurationSource.CodecPrivateData;

            Debug.WriteLine("TsMediaStreamSource.ConfigureAudioStream(): CodecPrivateData: " + codecPrivateData);
            if (!string.IsNullOrWhiteSpace(codecPrivateData))
            {
                dictionary[MediaStreamAttributeKeys.CodecPrivateData] = codecPrivateData;
            }
            MediaStreamDescription streamDescription = new MediaStreamDescription(MediaStreamType.Audio, (IDictionary <MediaStreamAttributeKeys, string>)dictionary);

            lock (this._streamConfigurationLock)
            {
                this._audioStreamSource      = audio.StreamSource;
                this._audioStreamDescription = streamDescription;
            }
        }
示例#36
0
        public PreprocessorTextReader(IStreamSource source, ICollection <string> predefinedVariables, IStreamResolver includeResolver)
        {
            Debug.Assert(source != null);

            _source          = source;
            _includeResolver = includeResolver;

            _definedVariables   = new Dictionary <string, string>();
            _activeInstructions = new Stack <Instruction>();

            if ((predefinedVariables != null) && (predefinedVariables.Count != 0))
            {
                foreach (string s in predefinedVariables)
                {
                    _definedVariables[s] = String.Empty;
                }
            }

            _currentLinePosition = -1;
        }
		public PersistedEventsStorage(PersistedOptions options)
		{
			cache = new JsonDataCache<PersistedEvent>(options);
			this.options = options;
			streamSource = options.StreamSource;
			file = streamSource.OpenReadWrite(dataPath);

			ReadAllFromDisk();

			binaryWriter = new BinaryWriter(file, Encoding.UTF8, leaveOpen: true);

			writerTask = Task.Factory.StartNew(() =>
				{
					try
					{
						WriteToDisk();
					}
					catch (Exception e)
					{
						corruptingException = e;
					}
				});
		}
示例#38
0
        public WinRtStreamState(string name, ContentType contentType, IStreamSource streamSource, IMediaStreamDescriptor descriptor)
        {
            if (null == name)
                throw new ArgumentNullException(nameof(name));
            if (null == contentType)
                throw new ArgumentNullException(nameof(contentType));
            if (null == streamSource)
                throw new ArgumentNullException(nameof(streamSource));
            if (null == descriptor)
                throw new ArgumentNullException(nameof(descriptor));

            _name = name;
            _contentType = contentType;
            _streamSource = streamSource;
            Descriptor = descriptor;

            var pool = _contentType.Kind == ContentKind.Video
                ? new WinRtBufferPool(1024, 4096, 16 * 1024, 64 * 1024)
                : new WinRtBufferPool(512, 1024, 2048, 8 * 1024);

            _pool = pool;

            TypedEventHandler<MediaStreamSample, object> freeBuffer = null;

            freeBuffer = (sender, args) =>
            {
                var buffer = sender.Buffer;

                if (null != buffer)
                    pool.Free(buffer);

                sender.Processed -= freeBuffer;
            };

            _freeBuffer = freeBuffer;
        }
示例#39
0
        private void Close()
        {
            lock (lockObject)
            {
                if (streamSource != null)
                {
                    streamSource.Dispose();
                    streamSource = null;
                }

                if (this.configurator != null)
                {
                    this.configurator.Dispose();
                    this.configurator = null;
                }

                if (this.mediaControl != null)
                {
                    this.mediaControl.Stop();
                    this.mediaControl = null;
                }

                if (this.filterGraph != null)
                {
                    ((IMediaEventSink)this.filterGraph).Notify(EventCode.UserAbort, IntPtr.Zero, IntPtr.Zero);

                    Marshal.ReleaseComObject(this.filterGraph);
                    this.filterGraph = null;
                }
            }

            GC.Collect();
        }
示例#40
0
 /// <summary>
 /// The constructor.
 /// </summary>
 /// <param name="streamSource">The stream source instance.</param>
 public TStreamInfo(IStreamSource streamSource)
 {
     Ensure.IsNotNull(Log, streamSource, "stream source is null");
     this.streamSource = streamSource;
 }
示例#41
0
        private void SetupGraph(Control hWin)
        {
            //streamSource = new UdpSource("127.0.0.1", 2001);
            streamSource = new UdpSource("224.0.0.1", 2002);
            //streamSource = new Core.Sources.FileSource("test.ts");

            streamSource.PacketLength = Constants.TSPacketSize;
            streamSource.SearchMethod = TSUtils.TSPacketSearch;

            streamSource.Configure();

            if (!streamSource.Require(10))
            {
                throw new Exception("Source is not ready. No data is received.");
            }

            Log.Info("Identify the A/V streams");
            var streamInfo = new TStreamInfo(streamSource);
            streamInfo.Configure();

            streamSource.Reset();

            filterGraph = new FilterGraph() as IFilterGraph2;
            Ensure.IsNotNull(Log, filterGraph, "graph is null");
            if (filterGraph == null) return;

            var pVideoRender = (IBaseFilter)new VideoRendererDefault();
            var hr = filterGraph.AddFilter(pVideoRender, "Video Renderer");
            DsError.ThrowExceptionForHR(hr);

            var pAudioRender = (IBaseFilter)new DSoundRender();
            hr = filterGraph.AddFilter(pAudioRender, "Audio Render");
            DsError.ThrowExceptionForHR(hr);

            Log.Info("Configure the directshow graph.");
            configurator = new GraphConfigurator
            {
                Source = streamSource,
                StreamInfo = streamInfo,
                Graph = filterGraph,
                VideoRender = pVideoRender,
                AudioRender = pAudioRender,
                VideoGrabber = null,
                AudioGrabber = null
            };

            configurator.Configure();

            var videoWindow = pVideoRender as IVideoWindow;
            ConfigureVideoWindow(videoWindow, hWin);

            this.mediaControl = this.filterGraph as IMediaControl;
        }
示例#42
0
        private void Dispose(bool disposing)
        {
            if (this.disposed) return;

            if (disposing)
            {
                this.source = null;
                this.isConfigured = false;
            }

            this.disposed = true;
        }
        public void ReportGetSampleCompleted(int streamType, IStreamSource streamSource, TsPesPacket packet)
        {
            if (null == packet)
            {
                Debug.WriteLine("SimulatedMediaElementManager.ReportGetSampleCompleted({0}) null packet", streamType);

                return;
            }

            Debug.WriteLine("SimulatedMediaElementManager.ReportGetSampleCompleted({0}) at {1}/{2}", streamType, packet.PresentationTimestamp, packet.DecodeTimestamp);

            var timestamp = packet.PresentationTimestamp;
            var oldestTimestamp = TimeSpan.MaxValue;
            var oldestIndex = -1;

            lock (_lock)
            {
                SampleState sampleState;

                if (!_streams.TryGetValue(streamType, out sampleState))
                {
                    sampleState = new SampleState
                    {
                        IsPending = false,
                        Timestamp = timestamp
                    };

                    _streams[streamType] = sampleState;
                }
                else
                {
                    sampleState.IsPending = false;
                    sampleState.Timestamp = timestamp;
                }

                foreach (var kv in _streams)
                {
                    var sampleTimestamp = kv.Value.Timestamp;

                    if (sampleTimestamp >= oldestTimestamp)
                        continue;

                    oldestTimestamp = sampleTimestamp;
                    oldestIndex = kv.Key;
                }

                if (oldestIndex >= 0)
                {
                    if (streamType != oldestIndex)
                        sampleState = _streams[oldestIndex];

                    if (sampleState.IsPending)
                        oldestIndex = -1;
                    else
                        sampleState.IsPending = true;
                }
            }

            if (oldestIndex >= 0)
            {
                var t = Task.Run(async () =>
                {
                    await Task.Delay((int)(10 * (1 + _random.GetRandomNumber()))).ConfigureAwait(false);

                    var mediaStreamSource = _mediaStreamConfigurator;

                    if (null != mediaStreamSource)
                        mediaStreamSource.GetSampleAsync(oldestIndex);
                });

                TaskCollector.Default.Add(t, "SimulatedMediaElementManager.ReportGetSampleCompleted");
            }
        }
示例#44
0
        IStreamSource IStreamResolver.ResolveInclude(IStreamSource baseStream, string includePath) {
            if (includePath == "%code%") {
                StringBuilder sb = new StringBuilder(4096);
                StringWriter sw = new StringWriter(sb);

                sw.WriteLine();
                GenerateScriptCore(sw);

                string compiledCode = sb.ToString();
                return new CodeStreamSource(compiledCode);
            }
            else {
                IStreamResolver resolver = baseStream as IStreamResolver;
                if (resolver != null) {
                    return resolver.ResolveInclude(baseStream, includePath);
                }

                string resolvedPath = Path.Combine(Path.GetDirectoryName(Path.GetFullPath(baseStream.FullName)), includePath);
                return new FileInputStreamSource(resolvedPath);
            }
        }
        private void ProcessIncludeInstruction(string instructionLine, bool skipPreprocessing) {
            Debug.Assert(_includeStream == null);
            Debug.Assert(_includeTextReader == null);

            bool included = false;
            int beginQuoteIndex = instructionLine.IndexOf('"');
            int endQuoteIndex = 0;

            if (beginQuoteIndex > 0) {
                endQuoteIndex = instructionLine.IndexOf('"', beginQuoteIndex + 1);
            }

            if (endQuoteIndex > 0) {
                Exception resolveException = null;
                string includePath = instructionLine.Substring(beginQuoteIndex + 1, endQuoteIndex - beginQuoteIndex - 1);
                try {
                    _include = _includeResolver.ResolveInclude(_source, includePath);

                    if (_include != null) {
                        _includeStream = _include.GetStream();
                        if (_includeStream != null) {
                            _includeTextReader = new StreamReader(_includeStream);
                            _includeLineCounter = 0;

                            if (skipPreprocessing) {
                                string includeText = _includeTextReader.ReadToEnd();
                                _skipPreprocessingWriter.Write(includeText);

                                _include.CloseStream(_includeStream);
                                _includeTextReader = null;
                                _includeStream = null;

                                included = true;
                            }
                        }
                    }
                }
                catch (Exception e) {
                    resolveException = e;
                }

                if ((included == false) && (_includeTextReader == null)) {
                    RaiseError("Unable to resolve or open included file '" + includePath + "'", resolveException);
                }
            }
            else {
                RaiseError("Invalid #include instruction.");
            }
        }
        private string GetNextLine() {
            string line = null;

            while (line == null) {
                if (_includeTextReader != null) {
                    line = _includeTextReader.ReadLine();
                    _includeLineCounter++;

                    if (line == null) {
                        _includeTextReader = null;
                        _includeLineCounter = 0;

                        _include.CloseStream(_includeStream);
                        _includeStream = null;
                        _include = null;
                    }
                }
                if (line == null) {
                    line = _sourceTextReader.ReadLine();
                    _lineCounter++;
                }

                if (line == null) {
                    break;
                }

                string trimmedLine = line.TrimStart(' ', '\t');

                bool isActive = true;
                if (_activeInstructions.Count != 0) {
                    Instruction currentInstruction = _activeInstructions.Peek();
                    isActive = currentInstruction.IsActive;
                }

                if (trimmedLine.StartsWith("##")) {
                    if (isActive == false) {
                        line = null;
                    }
                    if (line != null) {
                        line = ProcessSingleLineInstruction(trimmedLine);
                    }
                }
                else if (trimmedLine.StartsWith("#include[as-is] ")) {
                    if (isActive == false) {
                        line = null;
                    }

                    if (line != null) {
                        _currentLine = line;
                        if (_includeResolver != null) {
                            ProcessIncludeInstruction(trimmedLine, /* skipPreprocessing */ true);
                            line = null;
                        }
                        else {
                            RaiseError("Includes are not supported in this file.");
                        }
                    }
                }
                else if (trimmedLine.StartsWith("#include ")) {
                    if (isActive == false) {
                        line = null;
                    }

                    if (line != null) {
                        _currentLine = line;
                        if (_includeResolver != null) {
                            if (_includeStream == null) {
                                ProcessIncludeInstruction(trimmedLine, /* skipPreprocessing */ false);
                                line = null;
                            }
                            else {
                                RaiseError("Nested includes are not supported.");
                            }
                        }
                        else {
                            RaiseError("Includes are not supported in this file.");
                        }
                    }
                }
                else if (trimmedLine.StartsWith("#")) {
                    if ((isActive == false) &&
                        (trimmedLine.StartsWith("#elseif ") == false) &&
                        (trimmedLine.StartsWith("#elif ") == false) &&
                        (trimmedLine.StartsWith("#else") == false) &&
                        (trimmedLine.StartsWith("#endif") == false)) {
                        line = null;
                    }

                    if (line != null) {
                        ProcessInstruction(trimmedLine);
                        line = null;
                    }
                }
                else {
                    if (isActive == false) {
                        line = null;
                    }
                }
            }

            return ProcessInlineInstruction(line);
        }
示例#47
0
        bool SendStreamSample(IStreamSource source, MediaStreamDescription mediaStreamDescription, bool canCallReportBufferingProgress)
        {
            _taskScheduler.ThrowIfNotOnThread();

            var packet = source.GetNextSample();

            if (null == packet)
            {
                if (source.IsEof)
                    return SendLastStreamSample(mediaStreamDescription);

                if (canCallReportBufferingProgress)
                {
                    var progress = source.BufferingProgress;

                    if (progress.HasValue)
                    {
                        if (Math.Abs(_bufferingProgress - progress.Value) < 0.05)
                            return false;

                        Debug.WriteLine("Sample {0} buffering {1:F2}%", mediaStreamDescription.Type, progress * 100);

                        _bufferingProgress = progress.Value;

                        ValidateEvent(MediaStreamFsm.MediaEvent.CallingReportSampleCompleted);
                        ReportGetSampleProgress(progress.Value);
                    }
                    else
                    {
                        Debug.WriteLine("Sample {0} not buffering", mediaStreamDescription.Type);

                        // Try again, data might have arrived between the last call to GetNextSample() and
                        // when we checked the buffering progress.
                        packet = source.GetNextSample();
                    }
                }

                if (null == packet)
                    return false;
            }

            _bufferingProgress = -1;

            try
            {
                _pesStream.Packet = packet;

                var sample = new MediaStreamSample(mediaStreamDescription, _pesStream, 0, packet.Length,
                    packet.PresentationTimestamp.Ticks, NoMediaSampleAttributes);

                //Debug.WriteLine("Sample {0} at {1}", sample.MediaStreamDescription.Type, TimeSpan.FromTicks(sample.Timestamp));

                ValidateEvent(MediaStreamFsm.MediaEvent.CallingReportSampleCompleted);
                ReportGetSampleCompleted(sample);
            }
            finally
            {
                _pesStream.Packet = null;

                source.FreeSample(packet);
            }

            return true;
        }
 IStreamSource IStreamResolver.ResolveInclude(IStreamSource baseStream, string includePath) {
     string resolvedPath = Path.Combine(Path.GetDirectoryName(Path.GetFullPath(baseStream.FullName)), includePath);
     return new FileInputStreamSource(resolvedPath);
 }
 /// <summary>
 /// Loads this effect from a .cgfx stream
 /// </summary>
 /// <param name="source">Asset source</param>
 public void Load( IStreamSource source )
 {
     using ( Stream streamSource = source.Open( ) )
     {
         using ( StreamReader reader = new StreamReader( streamSource ) )
         {
             string str = reader.ReadToEnd( );
             if ( !CreateFromHandle( TaoCg.cgCreateEffect( m_Context, str, null ) ) )
             {
                 throw new ApplicationException( string.Format( "Unable to create CG effect from stream \"{0}\"\n{1}", source.Path, TaoCg.cgGetLastListing( m_Context ) ) );
             }
         }
     }
 }
示例#50
0
        private void Dispose(bool disposing)
        {
            if (this.disposed) return;

            if (disposing)
            {
                this.streamSource = null;
            }

            this.disposed = true;
        }
 /// <summary>
 /// Creates the effect, loading it from a .cgfx stream
 /// </summary>
 /// <param name="context">CG context</param>
 /// <param name="source">Asset source</param>
 public CgEffect( IntPtr context, IStreamSource source )
 {
     m_Context = context;
     Load( source );
 }
示例#52
0
        private void Dispose(bool disposing)
        {
            if (this.disposed) return;

            if (disposing)
            {
                this.source = null;
                this.streamInfo = null;
                this.graph = null;
                this.videoRender = null;
                this.audioRender = null;
                this.videoGrabber = null;
                this.audioGrabber = null;

                if (this.sampleHandler != null)
                {
                    this.sampleHandler.Dispose();
                    this.sampleHandler = null;
                }

                this.isConfigured = false;
            }

            this.disposed = true;
        }