Beispiel #1
0
        private void ExecuteImpl_NoOutput(Process process)
        {
            try
            {
                process.Start();
            }
            catch (Win32Exception win32e)
            {
                OnProcessStartWin32Exception?.Invoke(win32e);
                return;
            }
            catch (Exception)
            {
                return;
            }

            if (process.WaitForExit(ExecutableTimeout))
            {
                ProcessExit?.Invoke();
            }
            else
            {
                try
                {
                    process.Kill();
                    OnProcessTimeout?.Invoke();
                }
                catch (Win32Exception) { }
                catch (NotSupportedException) { }
                catch (InvalidOperationException) { }
            }
        }
Beispiel #2
0
        private void HandleProcessExit(int pid, int exit_code)
        {
            if (!Processes.Contains(pid))
            {
                return;
            }

            Processes.Remove(pid);
            ProcessExit?.Invoke(pid, exit_code);
        }
Beispiel #3
0
        internal static void OnProcessExit()
        {
            AssemblyLoadContext.OnProcessExit();
            if (EventSource.IsSupported)
            {
                EventListener.DisposeOnShutdown();
            }

            ProcessExit?.Invoke(AppDomain.CurrentDomain, EventArgs.Empty);
        }
Beispiel #4
0
        static void ReapChildren()
        {
            int pid = 0;

            while ((pid = Syscall.wait(out int status)) > -1)
            {
                ProcessExit?.Invoke(pid, status);
            }

            Syscall.alarm(60); // thanks sinit, this is neat
        }
        public static void Initialize()
        {
            if (_init)
            {
                return;
            }

            _init           = true;
            _lock           = new object();
            _timer          = new Timer(60000);
            _timer.Elapsed += delegate(object sender, ElapsedEventArgs args)
            {
                Save();
            };

            Tokens = File.Exists(TokendataFile) ? (TokenData)Serialization.Deserialize(File.ReadAllBytes(TokendataFile)) : new TokenData();
            ProcessExit.AddHandler(OnExit);
            _timer.Start();
        }
Beispiel #6
0
        internal static void OnProcessExit()
        {
            AssemblyLoadContext.OnProcessExit();

            ProcessExit?.Invoke(null /* AppDomain */, EventArgs.Empty);
        }
Beispiel #7
0
        internal static void OnProcessExit()
        {
            AssemblyLoadContext.OnProcessExit();

            ProcessExit?.Invoke(AppDomain.CurrentDomain, EventArgs.Empty);
        }
 private void OnProcessExit(object sender, EventArgs e) => ProcessExit?.Invoke(sender, e);
Beispiel #9
0
 private static void OnProcessExit(object sender, EventArgs e)
 {
     ProcessExit?.Invoke(sender, e);
 }
        private void HandleProcessExit(object sender, EventArgs e)
        {
            var process = (Process)sender;

            ProcessExit?.Invoke(process.Id, process.ExitCode);
        }
Beispiel #11
0
        /// <summary>
        /// async back when start encoding
        /// </summary>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <param name="resolution"></param>
        /// <returns></returns>
        public async Task RunAsync(string username, string password, Size resolution)
        {
            if (IsRunning)
            {
                return;
            }
            _isPreparing = true;
            try
            {
                _readyTcs = new TaskCompletionSource <object>();
                var baseDir  = Path.Combine(_management.BaseDir, Identity.Channel.ToString(), ((int)Identity.BitStream).ToString());
                var filePath = Path.Combine(baseDir, "realplay.m3u8");
                if (!Directory.Exists(baseDir))
                {
                    Directory.CreateDirectory(baseDir);
                }
                else if (File.Exists(filePath))
                {
                    File.Delete(filePath);
                }

                _builder = new RtspCommandBuilder()
                           .UseUri(Identity.Host, Identity.Port,
                                   HikvisionRouteValue.FromSettings(Identity.Channel, Identity.BitStream))
                           .WithAuthentication(username, password)
                           .WithHlsTime(1)
                           .WithHlsListSize(5)
                           .WithOutputResolution(resolution.Width, resolution.Height)
                           .ToM3U8File(filePath);

                BuildEncoderAndDecoder(resolution);

                if (_builder.EncodingSettings == null)
                {
                    throw new Exception("None of available encoders can be found.");
                }
                if (_builder.DecodingSettings == null)
                {
                    throw new Exception("None of available decoders can be found.");
                }

                var args = _builder.Build();
                WriteInfo("args: " + args);

                _proc = new Process
                {
                    EnableRaisingEvents = true,
                    StartInfo           = new ProcessStartInfo
                    {
                        FileName               = "ffmpeg",
                        Arguments              = "-loglevel level -hide_banner " + args,
                        RedirectStandardInput  = true,
                        RedirectStandardOutput = true,
                        RedirectStandardError  = true,
                        //WindowStyle = ProcessWindowStyle.Hidden,
                        CreateNoWindow  = false,
                        UseShellExecute = false
                    }
                };

                var o = new Regex(@"\[hls @ (.+)\] Opening '(.+)realplay\.m3u8\.tmp' for writing");

                string errMsg      = null;
                string innerErrMsg = null;

                _proc.OutputDataReceived += OnErrorDataReceived;
                _proc.ErrorDataReceived  += OnErrorDataReceived;

                _proc.Start();
                _proc.BeginOutputReadLine();
                _proc.BeginErrorReadLine();

                //await Task.Delay(100);
                new Task(() =>
                {
                    _proc.WaitForExit();

                    Thread.Sleep(100);
                    var exitCode = _proc.ExitCode;

                    if (exitCode != 0)
                    {
                        WriteError((innerErrMsg == null
                                ? errMsg
                                : (errMsg == null
                                    ? innerErrMsg
                                    : innerErrMsg + " -> " + errMsg)
                                    ) ?? $"Process exited unexpectedly. ({exitCode})");
                        //throw new Exception(errMsg ?? $"Process exited unexpectedly. ({exitCode})");
                    }

                    _builder = null;
                    _proc    = null;
                    ProcessExit?.Invoke(this);
                }).Start();

                await _readyTcs.Task;

                void OnErrorDataReceived(object obj, DataReceivedEventArgs e)
                {
                    //Console.WriteLine(e.Data);
                    if (e.Data == null)
                    {
                        return;
                    }
                    var match = o.Match(e.Data);

                    if (match.Success)
                    {
                        if (_readyTcs.Task?.IsCompleted != true)
                        {
                            ConsoleHelper.WriteInfo("Encoding Started", Module);
                            _readyTcs.SetResult(null);
                        }

                        return;
                    }

                    if (e.Data.StartsWith("[error] ") || e.Data.StartsWith("[fatal] ") || e.Data.StartsWith("[panic] "))
                    {
                        var i = e.Data.IndexOf("] ", StringComparison.Ordinal);
                        errMsg = e.Data.Substring(i + 2);
                        WriteError(errMsg);
                        if (_readyTcs.Task?.IsCompleted != true && !e.Data.StartsWith("[error] "))
                        {
                            _readyTcs.SetException(new Exception("Preload exception: " + errMsg));
                        }
                        return;
                    }

                    if (e.Data.Contains(" [error] "))
                    {
                        var i = e.Data.IndexOf(" [error] ", StringComparison.Ordinal);
                        innerErrMsg = e.Data.Substring(i + 9);
                        //if (tcs.Task?.IsCompleted != true)
                        //    tcs.SetException(new Exception("Preload exception: " + innerErrMsg));
                    }
                    else if (e.Data.Contains(" [fatal] "))
                    {
                        var i = e.Data.IndexOf(" [fatal] ", StringComparison.Ordinal);
                        innerErrMsg = e.Data.Substring(i + 9);
                        if (_readyTcs.Task?.IsCompleted != true)
                        {
                            _readyTcs.SetException(new Exception("Preload exception: " + innerErrMsg));
                        }
                    }
                    else if (e.Data.Contains(" [panic] "))
                    {
                        var i = e.Data.IndexOf(" [panic] ", StringComparison.Ordinal);
                        innerErrMsg = e.Data.Substring(i + 9);
                        if (_readyTcs.Task?.IsCompleted != true)
                        {
                            _readyTcs.SetException(new Exception("Preload exception: " + innerErrMsg));
                        }
                    }
                }
            }
            finally
            {
                _isPreparing = false;
            }
        }
Beispiel #12
0
        private void ExecuteImpl_ReadOutput(Process process)
        {
            StringBuilder output = new StringBuilder();
            StringBuilder error  = new StringBuilder();

            using (AutoResetEvent outputWaitHandle = new AutoResetEvent(false))
                using (AutoResetEvent errorWaitHandle = new AutoResetEvent(false))
                {
                    process.OutputDataReceived += (sender, e) =>
                    {
                        if (e.Data == null)
                        {
                            outputWaitHandle.Set();
                        }
                        else
                        {
                            output.AppendLine(e.Data);
                        }
                    };

                    process.ErrorDataReceived += (sender, e) =>
                    {
                        if (e.Data == null)
                        {
                            errorWaitHandle.Set();
                        }
                        else
                        {
                            error.AppendLine(e.Data);
                        }
                    };

                    try
                    {
                        process.Start();
                    }
                    catch (Win32Exception win32e)
                    {
                        OnProcessStartWin32Exception?.Invoke(win32e);
                        return;
                    }
                    catch (Exception)
                    {
                        return;
                    }

                    process.BeginOutputReadLine();
                    process.BeginErrorReadLine();

                    if (process.WaitForExit(ExecutableTimeout) &&
                        outputWaitHandle.WaitOne() &&
                        errorWaitHandle.WaitOne())
                    {
                        ProcessOutput?.Invoke(output, error);
                        ProcessExit?.Invoke();
                    }
                    else
                    {
                        try
                        {
                            process.Kill();
                            OnProcessTimeout?.Invoke();
                        }
                        catch (Win32Exception) { }
                        catch (NotSupportedException) { }
                        catch (InvalidOperationException) { }
                    }
                }
        }