コード例 #1
0
ファイル: ReplTests.cs プロジェクト: Gobiner/DotNetRepl
 public void ProtectedSpinloopReturns()
 {
     using (var repl = new ProcessWrapper())
     {
         repl.Execute(@"try { while(true); } finally { while(true); }");
         Assert.True(true);
     }
 }
コード例 #2
0
ファイル: ReplTests.cs プロジェクト: Gobiner/DotNetRepl
 public void CanExecuteCode()
 {
     using (var repl = new ProcessWrapper())
     {
         Assert.Equal("[(4, 20)]", repl.Execute(@"Tuple.Create(4,20);"));
         repl.Kill();
     }
 }
コード例 #3
0
ファイル: ProcessHandlerSpecs.cs プロジェクト: pshomov/frog
 public void should_make_the_process_nonexistent_after_killing_it()
 {
     var pw = new ProcessWrapper("ruby", @"-e ""system(\""ruby -e 'sleep 300'\"")""");
     pw.Execute();
     var processId = pw.Id;
     pw.Dispose();
     Assert.That(ProcessHasExited(processId));
 }
コード例 #4
0
ファイル: ReplTests.cs プロジェクト: Gobiner/DotNetRepl
 public void ProtectedSpinloopKillsProcess()
 {
     using (var repl = new ProcessWrapper())
     {
         repl.Execute(@"try { while(true); } finally { while(true); }");
         while (repl.IsProcessAlive)
             Thread.Sleep(500);
         Assert.True(true);
     }
 }
コード例 #5
0
ファイル: ProcessHandlerSpecs.cs プロジェクト: pshomov/frog
 public void should_capture_std_error_output()
 {
     var err = new StringBuilder();
     var pw = new ProcessWrapper("ruby", "-e '$stderr.puts(\"fle\")'");
     pw.OnErrorOutput += output => err.Append(output);
     pw.Execute();
     pw.WaitForProcess(5000);
     pw.Dispose();
     Assert.That(err.ToString(), Is.Not.Empty);
 }
コード例 #6
0
ファイル: ReplTests.cs プロジェクト: Gobiner/DotNetRepl
        public void CantAssertNewPermissions()
        {
            if (File.Exists("c:\\test.txt"))
                File.Delete("c:\\test.txt");

            using (var repl = new ProcessWrapper())
            {
                repl.Execute(@"new System.Security.PermissionSet(System.Security.Permissions.PermissionState.Unrestricted).Assert(); System.IO.File.WriteAllText(@""c:\test.txt"", ""test"");");
                repl.Kill();
                Assert.False(File.Exists("c:\\test.txt"));
            }
        }
コード例 #7
0
ファイル: ProcessHandlerSpecs.cs プロジェクト: pshomov/frog
        public void should_capture_std_output()
        {
            var std = new StringBuilder();
            var pw = new ProcessWrapper("ruby", "-e 'puts \"ff\"'");
            pw.OnStdOutput += output => std.Append(output);

            pw.Execute();
            pw.WaitForProcess(5000);
            pw.Dispose();

            Assert.That(std.ToString(), Is.Not.Empty);
        }
コード例 #8
0
ファイル: UnixSpecific.cs プロジェクト: pshomov/frog
 public static string UnixTotalProcessorTime(int processId)
 {
     var p = new ProcessWrapper("python",string.Format("{0} {1}", Path.Combine(Locations.SupportScriptsLocation, "cpu_times.py"), processId));
     var processStrings = new List<String>();
     var errorStrings = new List<String>();
     p.OnStdOutput += s => { if (!s.IsNullOrEmpty()) processStrings.Add(s); };
     p.OnErrorOutput += s => { if (!s.IsNullOrEmpty()) errorStrings.Add(s); };
     p.Execute();
     p.WaitForProcess(10000);
     p.Dispose();
     return ParseCPUTreeUsageInfo(processStrings, errorStrings);
 }
コード例 #9
0
ファイル: ProcessHandlerSpecs.cs プロジェクト: pshomov/frog
        public void should_indicate_no_cpu_usage_when_process_does_nothing()
        {
            var pw = new ProcessWrapper("ruby", "-e 'sleep 30'");
            pw.Execute();
            pw.WaitForProcess(1000);
            var tpt = pw.ProcessTreeCPUUsageId;
            pw.WaitForProcess(2000);
            var tpt1 = pw.ProcessTreeCPUUsageId;
            pw.Dispose();

            Assert.That(tpt, Is.EqualTo(tpt1));
        }
コード例 #10
0
ファイル: ProcessHandlerSpecs.cs プロジェクト: pshomov/frog
        public void should_indicate_cpu_usage_when_process_consumes_one()
        {
            var pw = new ProcessWrapper("ruby", "-e '100000000.times {|e| e}'");
            pw.Execute();
            pw.WaitForProcess(1);
            var tpt = pw.ProcessTreeCPUUsageId;
            pw.WaitForProcess(500);
            var tpt1 = pw.ProcessTreeCPUUsageId;
            pw.Dispose();

            Assert.That(tpt, Is.Not.EqualTo(tpt1));
        }
コード例 #11
0
ファイル: ReplTests.cs プロジェクト: Gobiner/DotNetRepl
        public void CantWriteFile()
        {
            if (File.Exists("c:\\test.txt"))
                File.Delete("c:\\test.txt");

            using (var repl = new ProcessWrapper())
            {
                repl.Execute(@"System.IO.File.WriteAllText(@""c:\test.txt"", ""test"");");
                repl.Kill();

                Assert.False(File.Exists("c:\\test.txt"));
            }
        }
コード例 #12
0
 public object GetValue(ProcessWrapper proc)
 {
     try
     {
         var o = ValueGetter(proc);
         Value = o;
         var d = string.Format(Format, o);
         return d;
     }
     catch
     {
         return "Err";
     }
 }
コード例 #13
0
ファイル: GitDriver.cs プロジェクト: pshomov/frog
 public CheckoutInfo GetSourceRevision(string revision, string workingArea)
 {
     var scriptPath = Path.Combine(Locations.GitProductionScriptsLocation, "git_fetch.rb");
     var process = new ProcessWrapper("ruby",
                                      scriptPath + " \"" + repoUrl + "\" " + revision + " " + " \"" + workingArea+"\"");
     var log = "";
     process.OnStdOutput += s => { if (!s.IsNullOrEmpty()) log = s; };
     string err_log = "";
     process.OnErrorOutput += s => err_log += s;
     process.Execute();
     process.WaitForProcess(GitTimeoutInMs);
     var exitcode = process.Dispose();
     if (exitcode != 0)
         throw new InvalidProgramException("script failed: "+err_log);
     return new CheckoutInfo {Comment = log, Revision = revision};
 }
コード例 #14
0
ファイル: Program.cs プロジェクト: ericlemes/vcsparser
        private static int RunPerforceToCosmosDbCodeChurnProcessor(P4ExtractToCosmosDbCommandLineArgs a)
        {
            var processWrapper       = new ProcessWrapper();
            var changesParser        = new ChangesParser();
            var describeParser       = new DescribeParser();
            var commandLineParser    = new CommandLineParser();
            var logger               = new ConsoleLoggerWithTimestamp();
            var stopWatch            = new StopWatchWrapper();
            var bugDatabaseFactory   = new BugDatabaseFactory();
            var bugDatabaseDllLoader = new BugDatabaseDllLoader(logger, bugDatabaseFactory);
            var webRequest           = new WebRequest(new HttpClientWrapperFactory(bugDatabaseFactory));
            var fileSystem           = new FileSystem();

            var cosmosConnection       = new CosmosConnection(new DatabaseFactory(a, JsonSerializerSettingsFactory.CreateDefaultSerializerSettingsForCosmosDB()), a.DatabaseId, Properties.Settings.Default.CosmosBulkBatchSize);
            var dataDocumentRepository = new DataDocumentRepository(cosmosConnection, a.CodeChurnCosmosContainer);
            var cosmosOutputProcessor  = new CosmosDbOutputProcessor(logger, dataDocumentRepository, new DataConverter(), a.CosmosProjectName, Properties.Settings.Default.CosmosBulkBatchSize);

            var bugDatabaseProcessor = new CosmosDbBugDatabaseProcessor(bugDatabaseDllLoader, fileSystem, webRequest, logger, dataDocumentRepository, a.CosmosProjectName);
            var processor            = new PerforceCodeChurnProcessor(processWrapper, changesParser, describeParser, commandLineParser, bugDatabaseProcessor, logger, stopWatch, cosmosOutputProcessor, a);

            processor.QueryBugDatabase();
            return(processor.Extract());
        }
コード例 #15
0
ファイル: Program.cs プロジェクト: ericlemes/vcsparser
        private static int RunGitToCosmosDbCodeChurnProcessor(GitExtractToCosmosDbCommandLineArgs a)
        {
            var processWrapper         = new ProcessWrapper();
            var commandLineParser      = new CommandLineParser();
            var gitLogParser           = new GitLogParser();
            var logger                 = new ConsoleLoggerWithTimestamp();
            var cosmosConnection       = new CosmosConnection(new DatabaseFactory(a, JsonSerializerSettingsFactory.CreateDefaultSerializerSettingsForCosmosDB()), a.DatabaseId, Properties.Settings.Default.CosmosBulkBatchSize);
            var dataDocumentRepository = new DataDocumentRepository(cosmosConnection, a.CodeChurnCosmosContainer);
            var cosmosOutputProcessor  = new CosmosDbOutputProcessor(logger, dataDocumentRepository, new DataConverter(), a.CosmosProjectName, Properties.Settings.Default.CosmosBulkBatchSize);
            var bugDatabaseFactory     = new BugDatabaseFactory();
            var bugDatabaseDllLoader   = new BugDatabaseDllLoader(logger, bugDatabaseFactory);
            var webRequest             = new WebRequest(new HttpClientWrapperFactory(bugDatabaseFactory));
            var fileSystem             = new FileSystem();
            var jsonParser             = new JsonListParser <WorkItem>(new FileStreamFactory());
            var bugDatabaseProcessor   = new BugDatabaseProcessor(bugDatabaseDllLoader, webRequest, fileSystem, jsonParser, logger, string.Empty);
            //, a.BugDatabaseOutputFile

            var processor = new GitCodeChurnProcessor(commandLineParser, processWrapper, gitLogParser, cosmosOutputProcessor, bugDatabaseProcessor, logger, a);

            processor.QueryBugDatabase();

            return(processor.Extract());
        }
コード例 #16
0
        private void StopProcess(ProcessWrapper process, int waitTimeMs)
        {
            try
            {
                if (process.Process.WaitForExit(waitTimeMs))
                {
                    return;
                }

                _logger.LogInformation("Killing ffmpeg process");

                process.Process.Kill();
            }
            catch (InvalidOperationException)
            {
                // The process has already exited or
                // there is no process associated with this Process object.
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error killing process");
            }
        }
コード例 #17
0
ファイル: MediaEncoder.cs プロジェクト: bert-alpen/Emby
        private void StopProcess(ProcessWrapper process, int waitTimeMs, bool enableForceKill)
        {
            try
            {
                _logger.Info("Killing ffmpeg process");

                try
                {
                    process.Process.StandardInput.WriteLine("q");
                }
                catch (Exception)
                {
                    _logger.Error("Error sending q command to process");
                }

                try
                {
                    if (process.Process.WaitForExit(waitTimeMs))
                    {
                        return;
                    }
                }
                catch (Exception ex)
                {
                    _logger.Error("Error in WaitForExit", ex);
                }

                if (enableForceKill)
                {
                    process.Process.Kill();
                }
            }
            catch (Exception ex)
            {
                _logger.ErrorException("Error killing process", ex);
            }
        }
コード例 #18
0
        public BuildResult RunTarget(MonoDevelop.Core.IProgressMonitor monitor, string target, ConfigurationSelector configuration)
        {
            if (target == ProjectService.BuildTarget)
            {
                target = "all";
            }
            else if (target == ProjectService.CleanTarget)
            {
                target = "clean";
            }

            DotNetProjectConfiguration conf = (DotNetProjectConfiguration)project.GetConfiguration(configuration);

            StringWriter  output = new StringWriter();
            LogTextWriter tw     = new LogTextWriter();

            tw.ChainWriter(output);
            tw.ChainWriter(monitor.Log);

            ProcessWrapper proc = Runtime.ProcessService.StartProcess("make", "PROFILE=" + conf.Id + " " + target, conf.OutputDirectory, monitor.Log, tw, null);

            proc.WaitForOutput();

            CompilerResults cr = new CompilerResults(null);

            string[] lines = output.ToString().Split('\n');
            foreach (string line in lines)
            {
                CompilerError err = CreateErrorFromString(line);
                if (err != null)
                {
                    cr.Errors.Add(err);
                }
            }

            return(new BuildResult(cr, output.ToString()));
        }
コード例 #19
0
ファイル: CliPatcherRun.cs プロジェクト: Deigue/Synthesis
        public async Task Run(RunSynthesisPatcher settings, CancellationToken?cancel = null)
        {
            if (cancel?.IsCancellationRequested ?? false)
            {
                return;
            }

            var internalSettings = RunSynthesisMutagenPatcher.Factory(settings);

            internalSettings.ExtraDataFolder = PathToExtraData;

            var args = Parser.Default.FormatCommandLine(internalSettings);

            try
            {
                using ProcessWrapper process = ProcessWrapper.Start(
                          new ProcessStartInfo(PathToExecutable, args)
                {
                    WorkingDirectory = Path.GetDirectoryName(PathToExecutable)
                },
                          cancel);
                using var outputSub = process.Output.Subscribe(_output);
                using var errSub    = process.Error.Subscribe(_error);
                var result = await process.Start();

                if (result != 0)
                {
                    throw new CliUnsuccessfulRunException(
                              result,
                              $"Process exited in failure: {process.StartInfo.FileName} {internalSettings}");
                }
            }
            catch (Win32Exception ex)
            {
                throw new FileNotFoundException($"Could not find target CLI file: {PathToExecutable}", ex);
            }
        }
コード例 #20
0
        public static async Task <IEnumerable <string> > FindGulpTasks(string workingDirectory)
        {
            var outputBuilder = new StringBuilder();

            using (var stringWriter = new StringWriter(outputBuilder)) {
                ProcessWrapper process = Runtime.ProcessService.StartProcess(
                    "gulp",
                    "--tasks-simple",
                    workingDirectory,
                    stringWriter,
                    null,
                    null);

                await process.Task;

                if (process.ExitCode != 0)
                {
                    return(Enumerable.Empty <string> ());
                }

                string[] tasks = outputBuilder.ToString().Split(new [] { '\n' }, StringSplitOptions.RemoveEmptyEntries);
                return(tasks);
            }
        }
コード例 #21
0
        public static SaveGame OpenSaveGameLSV(string fullFileName)
        {
            fullFileName = FileUtils.UseDefaultPathIfNotRooted(fullFileName);

            if (!Path.IsPathRooted(fullFileName) && !File.Exists(fullFileName))
            {
                Console.WriteLine($"[ERROR] Save game LSV could not be found, input parameter was: \"{fullFileName}\"");
                return(new SaveGame());
            }

            if (!FileUtils.IsLsv(fullFileName))
            {
                Console.WriteLine($"[ERROR] Inputted save game was not an LSV, it was: \"{fullFileName}\"");
                return(new SaveGame());
            }

            string filename     = Path.GetFileNameWithoutExtension(fullFileName);
            string outputFolder = Path.Combine(WorkspaceFolder, filename);

            Console.WriteLine($"[INFO] Extracting {fullFileName} to {outputFolder}...");

            string exportToolExtractSaveArgs        = $"-s \"{fullFileName}\" -d \"{outputFolder}\" -a extract-package";
            string exportToolDecompressContentsArgs = $"-s \"{outputFolder}\" -d \"{outputFolder}\" -a convert-resources -i lsf -o lsx";

            string exportToolExtractSaveCommand        = $".\\{ExportTool} {exportToolExtractSaveArgs}";
            string exportToolDecompressContentsCommand = $".\\{ExportTool} {exportToolDecompressContentsArgs}";

            ExecuteCommandsAsyncArgs commandArgs = new ExecuteCommandsAsyncArgs(new List <string> {
                exportToolExtractSaveCommand,
                exportToolDecompressContentsCommand
            }, null);

            Process cmd = ProcessWrapper.ExecuteCommands(commandArgs);

            return(new SaveGame(outputFolder, Path.GetFileNameWithoutExtension(outputFolder)));
        }
コード例 #22
0
        protected string GeneratePkgLinkerArgs(ProjectPackageCollection packages)
        {
            if (packages == null || packages.Count < 1)
            {
                return(string.Empty);
            }

            StringBuilder libs = new StringBuilder();

            foreach (Package p in packages)
            {
                libs.Append(p.File + " ");
            }

            string args = string.Format("--libs {0}", libs.ToString().Trim());

            StringWriter   output = new StringWriter();
            ProcessWrapper proc   = new ProcessWrapper();

            try {
                proc = Runtime.ProcessService.StartProcess("pkg-config", args, null, null);
                proc.WaitForExit();

                string line;
                while ((line = proc.StandardOutput.ReadLine()) != null)
                {
                    output.WriteLine(line);
                }
            } catch (Exception ex) {
                MessageService.ShowException(ex, "You need to have pkg-config installed");
            } finally {
                proc.Close();
            }

            return(output.ToString());
        }
コード例 #23
0
        public static async Task <GetResponse <string> > GetExecutablePath(string projectPath, CancellationToken cancel)
        {
            // Hacky way to locate executable, but running a build and extracting the path its logs spit out
            // Tried using Buildalyzer, but it has a lot of bad side effects like clearing build outputs when
            // locating information like this.
            using var proc = ProcessWrapper.Create(
                      new System.Diagnostics.ProcessStartInfo("dotnet", GetBuildString($"\"{projectPath}\"")),
                      cancel: cancel);
            List <string> outs = new List <string>();

            using var outp = proc.Output.Subscribe(o => outs.Add(o));
            List <string> errs = new List <string>();

            using var errp = proc.Error.Subscribe(o => errs.Add(o));
            var result = await proc.Run();

            if (errs.Count > 0)
            {
                throw new ArgumentException($"{string.Join("\n", errs)}");
            }
            int index = outs.IndexOf("Build succeeded.");

            if (index == -1 || index < 2)
            {
                return(GetResponse <string> .Fail("Could not locate target executable."));
            }
            var          line      = outs[index - 2];
            const string delimiter = " -> ";

            index = line.IndexOf(delimiter);
            if (index == -1)
            {
                return(GetResponse <string> .Fail("Could not locate target executable."));
            }
            return(GetResponse <string> .Succeed(line.Substring(index + delimiter.Length).Trim()));
        }
コード例 #24
0
		protected override void Execute (IProgressMonitor monitor, SolutionEntityItem entry, ExecutionContext context, ConfigurationSelector configuration)
		{
			Project project = entry as Project;
			if (project == null) {
				base.Execute (monitor, entry, context, configuration);
				return;
			}

			MakefileData data = project.ExtendedProperties ["MonoDevelop.Autotools.MakefileInfo"] as MakefileData;
			if (data == null || !data.SupportsIntegration || String.IsNullOrEmpty (data.ExecuteTargetName)) {
				base.Execute (monitor, entry, context, configuration);
				return;
			}

			IConsole console = context.ConsoleFactory.CreateConsole (true);
			monitor.BeginTask (GettextCatalog.GetString ("Executing {0}", project.Name), 1);
			try
			{
				ProcessWrapper process = Runtime.ProcessService.StartProcess ("make",
						data.ExecuteTargetName,
						project.BaseDirectory,
						console.Out,
						console.Error,
						null);
				process.WaitForOutput ();

				monitor.Log.WriteLine (GettextCatalog.GetString ("The application exited with code: {0}", process.ExitCode));
				monitor.Step (1);
			} catch (Exception e) {
				monitor.ReportError (GettextCatalog.GetString ("Project could not be executed: "), e);
				return;
			} finally {
				monitor.EndTask ();
				console.Dispose ();
			}
		}
コード例 #25
0
        void CheckExternalMonodoc()
        {
            firstCall = false;
            try {
                outWriter = new StringWriter();
                errWriter = new StringWriter();
                pw        = Runtime.ProcessService.StartProcess(
                    "monodoc", "--help", "", outWriter, errWriter,
                    delegate {
                    if (pw.ExitCode != 0)
                    {
                        MessageService.ShowError(
                            String.Format(
                                "MonoDoc exited with exit code {0}. Error : {1}",
                                pw.ExitCode, errWriter.ToString()));
                    }
                    pw = null;
                }, true);

                pw.WaitForOutput();
                if (outWriter.ToString().IndexOf("--about") > 0)
                {
                    useExternalMonodoc = true;
                }
                pw = null;
            } catch (Exception e) {
                MessageService.ShowError(String.Format(
                                             "Could not start monodoc : {0}", e.ToString()));
            }

            if (!useExternalMonodoc)
            {
                MessageService.ShowError(
                    GettextCatalog.GetString("You need a newer monodoc to use it externally from monodevelop. Using the integrated help viewer now."));
            }
        }
コード例 #26
0
        public override IProcessAsyncOperation StartConsoleProcess(string command, string arguments, string workingDirectory,
                                                                   IDictionary <string, string> environmentVariables,
                                                                   string title, bool pauseWhenFinished)
        {
            ProbeTerminal();

            string exec = runner(command, arguments, workingDirectory, title, pauseWhenFinished);
            var    psi  = new ProcessStartInfo(terminal_command, exec)
            {
                CreateNoWindow  = true,
                UseShellExecute = false,
            };

            foreach (var env in environmentVariables)
            {
                psi.EnvironmentVariables [env.Key] = env.Value;
            }

            ProcessWrapper proc = new ProcessWrapper();

            proc.StartInfo = psi;
            proc.Start();
            return(proc);
        }
コード例 #27
0
        int ExecuteCommand(string command, string args, string baseDirectory, ProgressMonitor monitor, out string errorOutput)
        {
            errorOutput = string.Empty;
            int exitCode = -1;

            using (var swError = new StringWriter()) {
                using (var chainedError = new LogTextWriter()) {
                    chainedError.ChainWriter(monitor.Log);
                    chainedError.ChainWriter(swError);

                    monitor.Log.WriteLine("{0} {1}", command, args);

                    using (ProcessWrapper p = Runtime.ProcessService.StartProcess(command, args, baseDirectory, monitor.Log, chainedError, null))
                        using (monitor.CancellationToken.Register(p.Cancel)) {
                            p.WaitForOutput();
                            chainedError.UnchainWriter(monitor.Log);
                            chainedError.UnchainWriter(swError);

                            errorOutput = swError.ToString();
                            exitCode    = p.ExitCode;

                            if (monitor.CancellationToken.IsCancellationRequested)
                            {
                                monitor.Log.WriteLine(GettextCatalog.GetString("Build cancelled"));
                                monitor.ReportError(GettextCatalog.GetString("Build cancelled"), null);
                                if (exitCode == 0)
                                {
                                    exitCode = -1;
                                }
                            }
                        }
                }
            }

            return(exitCode);
        }
コード例 #28
0
ファイル: GitDriver.cs プロジェクト: pshomov/frog
 public RevisionInfo GetLatestRevision()
 {
     string scriptPath = Path.Combine(Locations.GitProductionScriptsLocation, "git_remote_latest_rev.rb");
     var process = new ProcessWrapper("ruby",
                                      scriptPath + " \"" + repoUrl+"\"");
     string result = "";
     process.OnStdOutput +=
         s =>
             {
                 if (result.Length == 0 && !s.IsNullOrEmpty())
                 {
                     if (Regex.IsMatch(s, RevisionExtractingRegex))
                         result = Regex.Match(s, RevisionExtractingRegex).Groups[1].Value;
                 }
             };
     process.Execute();
     process.WaitForProcess(GitTimeoutInMs);
     var exitcode = process.Dispose();
     if (exitcode != 0)
         throw new InvalidProgramException(string.Format("script failed with exit code {1}: {0}", 1, exitcode));
     if (result.IsNullOrEmpty())
         throw new InvalidProgramException("Failed to retrieve repo revision");
     return new RevisionInfo {Revision = result};
 }
コード例 #29
0
        bool InternalInitialize()
        {
            string libDir = Path.Combine(prefix, "lib");

            if (!Directory.Exists(Path.Combine(libDir, "mono")))
            {
                return(false);
            }
            string binDir = Path.Combine(prefix, "bin");

            envVars ["PATH"]            = libDir + Path.PathSeparator + binDir + Path.PathSeparator + Environment.GetEnvironmentVariable("PATH");
            envVars ["LD_LIBRARY_PATH"] = libDir + Path.PathSeparator + Environment.GetEnvironmentVariable("LD_LIBRARY_PATH");

            // Avoid inheriting this var from the current process environment
            envVars ["MONO_PATH"] = string.Empty;

            StringWriter output = new StringWriter();

            try {
                string monoPath = Path.Combine(prefix, "bin");
                monoPath = Path.Combine(monoPath, force64or32bit.HasValue ? (force64or32bit.Value ? "mono64" : "mono32") : "mono");
                ProcessStartInfo pi = new ProcessStartInfo(monoPath, "--version");
                pi.UseShellExecute        = false;
                pi.RedirectStandardOutput = true;
                foreach (KeyValuePair <string, string> var in envVars)
                {
                    pi.EnvironmentVariables [var.Key] = var.Value;
                }
                ProcessWrapper p = Runtime.ProcessService.StartProcess(pi, output, null, null);
                p.WaitForOutput();
            } catch {
                return(false);
            }

            //set up paths using the prefix
            SetupPkgconfigPaths(null, null);

            string ver = output.ToString();
            int    i   = ver.IndexOf("version", StringComparison.Ordinal);

            if (i == -1)
            {
                return(false);
            }
            i += 8;
            int j = ver.IndexOf(' ', i);

            if (j == -1)
            {
                return(false);
            }

            monoVersion = ver.Substring(i, j - i);

            i = ver.IndexOf('(');
            if (i != -1)
            {
                i++;
                j = ver.IndexOf(' ', i);
                if (j == -1)
                {
                    j = ver.IndexOf(')', i);
                }
                if (j != -1)
                {
                    var rev = ver.Substring(i, j - i);
                    i = rev.IndexOf('/');
                    if (i != -1 && i + 1 < rev.Length)
                    {
                        rev = rev.Substring(i + 1);
                    }
                    if (rev != "tarball")
                    {
                        monoVersion += " (" + rev + ")";
                    }
                }
            }

            return(true);
        }
コード例 #30
0
ファイル: MediaEncoder.cs プロジェクト: bert-alpen/Emby
        public async Task ExtractVideoImagesOnInterval(string[] inputFiles,
                                                       MediaProtocol protocol,
                                                       Video3DFormat?threedFormat,
                                                       TimeSpan interval,
                                                       string targetDirectory,
                                                       string filenamePrefix,
                                                       int?maxWidth,
                                                       CancellationToken cancellationToken)
        {
            var resourcePool = _thumbnailResourcePool;

            var inputArgument = GetInputArgument(inputFiles, protocol);

            var vf = "fps=fps=1/" + interval.TotalSeconds.ToString(UsCulture);

            if (maxWidth.HasValue)
            {
                var maxWidthParam = maxWidth.Value.ToString(UsCulture);

                vf += string.Format(",scale=min(iw\\,{0}):trunc(ow/dar/2)*2", maxWidthParam);
            }

            Directory.CreateDirectory(targetDirectory);
            var outputPath = Path.Combine(targetDirectory, filenamePrefix + "%05d.jpg");

            var args = string.Format("-i {0} -threads 1 -v quiet -vf \"{2}\" -f image2 \"{1}\"", inputArgument, outputPath, vf);

            var probeSize = GetProbeSizeArgument(new[] { inputArgument }, protocol);

            if (!string.IsNullOrEmpty(probeSize))
            {
                args = probeSize + " " + args;
            }

            var process = new Process
            {
                StartInfo = new ProcessStartInfo
                {
                    CreateNoWindow        = true,
                    UseShellExecute       = false,
                    FileName              = FFMpegPath,
                    Arguments             = args,
                    WindowStyle           = ProcessWindowStyle.Hidden,
                    ErrorDialog           = false,
                    RedirectStandardInput = true
                }
            };

            _logger.Info(process.StartInfo.FileName + " " + process.StartInfo.Arguments);

            await resourcePool.WaitAsync(cancellationToken).ConfigureAwait(false);

            bool ranToCompletion = false;

            using (var processWrapper = new ProcessWrapper(process, this, _logger))
            {
                try
                {
                    StartProcess(processWrapper);

                    // Need to give ffmpeg enough time to make all the thumbnails, which could be a while,
                    // but we still need to detect if the process hangs.
                    // Making the assumption that as long as new jpegs are showing up, everything is good.

                    bool isResponsive = true;
                    int  lastCount    = 0;

                    while (isResponsive)
                    {
                        if (process.WaitForExit(30000))
                        {
                            ranToCompletion = true;
                            break;
                        }

                        cancellationToken.ThrowIfCancellationRequested();

                        var jpegCount = Directory.GetFiles(targetDirectory)
                                        .Count(i => string.Equals(Path.GetExtension(i), ".jpg", StringComparison.OrdinalIgnoreCase));

                        isResponsive = (jpegCount > lastCount);
                        lastCount    = jpegCount;
                    }

                    if (!ranToCompletion)
                    {
                        StopProcess(processWrapper, 1000, false);
                    }
                }
                finally
                {
                    resourcePool.Release();
                }

                var exitCode = ranToCompletion ? processWrapper.ExitCode ?? 0 : -1;

                if (exitCode == -1)
                {
                    var msg = string.Format("ffmpeg image extraction failed for {0}", inputArgument);

                    _logger.Error(msg);

                    throw new ApplicationException(msg);
                }
            }
        }
コード例 #31
0
ファイル: MediaEncoder.cs プロジェクト: bert-alpen/Emby
        /// <summary>
        /// Gets the media info internal.
        /// </summary>
        /// <param name="inputPath">The input path.</param>
        /// <param name="primaryPath">The primary path.</param>
        /// <param name="protocol">The protocol.</param>
        /// <param name="extractChapters">if set to <c>true</c> [extract chapters].</param>
        /// <param name="extractKeyFrameInterval">if set to <c>true</c> [extract key frame interval].</param>
        /// <param name="probeSizeArgument">The probe size argument.</param>
        /// <param name="isAudio">if set to <c>true</c> [is audio].</param>
        /// <param name="videoType">Type of the video.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns>Task{MediaInfoResult}.</returns>
        /// <exception cref="System.ApplicationException"></exception>
        private async Task <Model.MediaInfo.MediaInfo> GetMediaInfoInternal(string inputPath,
                                                                            string primaryPath,
                                                                            MediaProtocol protocol,
                                                                            bool extractChapters,
                                                                            bool extractKeyFrameInterval,
                                                                            string probeSizeArgument,
                                                                            bool isAudio,
                                                                            VideoType videoType,
                                                                            CancellationToken cancellationToken)
        {
            var args = extractChapters
                ? "{0} -i {1} -threads 0 -v info -print_format json -show_streams -show_chapters -show_format"
                : "{0} -i {1} -threads 0 -v info -print_format json -show_streams -show_format";

            var process = new Process
            {
                StartInfo = new ProcessStartInfo
                {
                    CreateNoWindow  = true,
                    UseShellExecute = false,

                    // Must consume both or ffmpeg may hang due to deadlocks. See comments below.
                    RedirectStandardOutput = true,
                    RedirectStandardError  = true,
                    RedirectStandardInput  = true,
                    FileName  = FFProbePath,
                    Arguments = string.Format(args,
                                              probeSizeArgument, inputPath).Trim(),

                    WindowStyle = ProcessWindowStyle.Hidden,
                    ErrorDialog = false
                },

                EnableRaisingEvents = true
            };

            _logger.Debug("{0} {1}", process.StartInfo.FileName, process.StartInfo.Arguments);

            await _ffProbeResourcePool.WaitAsync(cancellationToken).ConfigureAwait(false);

            using (var processWrapper = new ProcessWrapper(process, this, _logger))
            {
                try
                {
                    StartProcess(processWrapper);
                }
                catch (Exception ex)
                {
                    _ffProbeResourcePool.Release();

                    _logger.ErrorException("Error starting ffprobe", ex);

                    throw;
                }

                try
                {
                    process.BeginErrorReadLine();

                    var result = _jsonSerializer.DeserializeFromStream <InternalMediaInfoResult>(process.StandardOutput.BaseStream);

                    if (result != null)
                    {
                        if (result.streams != null)
                        {
                            // Normalize aspect ratio if invalid
                            foreach (var stream in result.streams)
                            {
                                if (string.Equals(stream.display_aspect_ratio, "0:1", StringComparison.OrdinalIgnoreCase))
                                {
                                    stream.display_aspect_ratio = string.Empty;
                                }
                                if (string.Equals(stream.sample_aspect_ratio, "0:1", StringComparison.OrdinalIgnoreCase))
                                {
                                    stream.sample_aspect_ratio = string.Empty;
                                }
                            }
                        }

                        var mediaInfo = new ProbeResultNormalizer(_logger, FileSystem).GetMediaInfo(result, videoType, isAudio, primaryPath, protocol);

                        if (extractKeyFrameInterval && mediaInfo.RunTimeTicks.HasValue)
                        {
                            if (ConfigurationManager.Configuration.EnableVideoFrameAnalysis && mediaInfo.Size.HasValue && mediaInfo.Size.Value <= ConfigurationManager.Configuration.VideoFrameAnalysisLimitBytes)
                            {
                                foreach (var stream in mediaInfo.MediaStreams)
                                {
                                    if (stream.Type == MediaStreamType.Video &&
                                        string.Equals(stream.Codec, "h264", StringComparison.OrdinalIgnoreCase) &&
                                        !stream.IsInterlaced &&
                                        !(stream.IsAnamorphic ?? false))
                                    {
                                        try
                                        {
                                            stream.KeyFrames = await GetKeyFrames(inputPath, stream.Index, cancellationToken).ConfigureAwait(false);
                                        }
                                        catch (OperationCanceledException)
                                        {
                                        }
                                        catch (Exception ex)
                                        {
                                            _logger.ErrorException("Error getting key frame interval", ex);
                                        }
                                    }
                                }
                            }
                        }

                        return(mediaInfo);
                    }
                }
                catch
                {
                    StopProcess(processWrapper, 100, true);

                    throw;
                }
                finally
                {
                    _ffProbeResourcePool.Release();
                }
            }

            throw new ApplicationException(string.Format("FFProbe failed for {0}", inputPath));
        }
コード例 #32
0
ファイル: MediaEncoder.cs プロジェクト: sxryt/jellyfin
        private async Task <string> ExtractImageInternal(string inputPath, string container, MediaStream videoStream, int?imageStreamIndex, Video3DFormat?threedFormat, TimeSpan?offset, bool useIFrame, CancellationToken cancellationToken)
        {
            if (string.IsNullOrEmpty(inputPath))
            {
                throw new ArgumentNullException("inputPath");
            }

            var tempExtractPath = Path.Combine(ConfigurationManager.ApplicationPaths.TempDirectory, Guid.NewGuid() + ".jpg");

            FileSystem.CreateDirectory(FileSystem.GetDirectoryName(tempExtractPath));

            // apply some filters to thumbnail extracted below (below) crop any black lines that we made and get the correct ar then scale to width 600.
            // This filter chain may have adverse effects on recorded tv thumbnails if ar changes during presentation ex. commercials @ diff ar
            var vf = "scale=600:trunc(600/dar/2)*2";

            if (threedFormat.HasValue)
            {
                switch (threedFormat.Value)
                {
                case Video3DFormat.HalfSideBySide:
                    vf = "crop=iw/2:ih:0:0,scale=(iw*2):ih,setdar=dar=a,crop=min(iw\\,ih*dar):min(ih\\,iw/dar):(iw-min(iw\\,iw*sar))/2:(ih - min (ih\\,ih/sar))/2,setsar=sar=1,scale=600:trunc(600/dar/2)*2";
                    // hsbs crop width in half,scale to correct size, set the display aspect,crop out any black bars we may have made the scale width to 600. Work out the correct height based on the display aspect it will maintain the aspect where -1 in this case (3d) may not.
                    break;

                case Video3DFormat.FullSideBySide:
                    vf = "crop=iw/2:ih:0:0,setdar=dar=a,crop=min(iw\\,ih*dar):min(ih\\,iw/dar):(iw-min(iw\\,iw*sar))/2:(ih - min (ih\\,ih/sar))/2,setsar=sar=1,scale=600:trunc(600/dar/2)*2";
                    //fsbs crop width in half,set the display aspect,crop out any black bars we may have made the scale width to 600.
                    break;

                case Video3DFormat.HalfTopAndBottom:
                    vf = "crop=iw:ih/2:0:0,scale=(iw*2):ih),setdar=dar=a,crop=min(iw\\,ih*dar):min(ih\\,iw/dar):(iw-min(iw\\,iw*sar))/2:(ih - min (ih\\,ih/sar))/2,setsar=sar=1,scale=600:trunc(600/dar/2)*2";
                    //htab crop heigh in half,scale to correct size, set the display aspect,crop out any black bars we may have made the scale width to 600
                    break;

                case Video3DFormat.FullTopAndBottom:
                    vf = "crop=iw:ih/2:0:0,setdar=dar=a,crop=min(iw\\,ih*dar):min(ih\\,iw/dar):(iw-min(iw\\,iw*sar))/2:(ih - min (ih\\,ih/sar))/2,setsar=sar=1,scale=600:trunc(600/dar/2)*2";
                    // ftab crop heigt in half, set the display aspect,crop out any black bars we may have made the scale width to 600
                    break;

                default:
                    break;
                }
            }

            var mapArg = imageStreamIndex.HasValue ? (" -map 0:v:" + imageStreamIndex.Value.ToString(CultureInfo.InvariantCulture)) : string.Empty;

            var enableThumbnail = !new List <string> {
                "wtv"
            }.Contains(container ?? string.Empty, StringComparer.OrdinalIgnoreCase);
            // Use ffmpeg to sample 100 (we can drop this if required using thumbnail=50 for 50 frames) frames and pick the best thumbnail. Have a fall back just in case.
            var thumbnail = enableThumbnail ? ",thumbnail=24" : string.Empty;

            var args = useIFrame ? string.Format("-i {0}{3} -threads 0 -v quiet -vframes 1 -vf \"{2}{4}\" -f image2 \"{1}\"", inputPath, tempExtractPath, vf, mapArg, thumbnail) :
                       string.Format("-i {0}{3} -threads 0 -v quiet -vframes 1 -vf \"{2}\" -f image2 \"{1}\"", inputPath, tempExtractPath, vf, mapArg);

            var probeSizeArgument       = EncodingHelper.GetProbeSizeArgument(1);
            var analyzeDurationArgument = EncodingHelper.GetAnalyzeDurationArgument(1);

            if (!string.IsNullOrWhiteSpace(probeSizeArgument))
            {
                args = probeSizeArgument + " " + args;
            }

            if (!string.IsNullOrWhiteSpace(analyzeDurationArgument))
            {
                args = analyzeDurationArgument + " " + args;
            }

            if (offset.HasValue)
            {
                args = string.Format("-ss {0} ", GetTimeParameter(offset.Value)) + args;
            }

            var encodinghelper = new EncodingHelper(this, FileSystem, SubtitleEncoder());

            if (videoStream != null)
            {
                /* fix
                 * var decoder = encodinghelper.GetHardwareAcceleratedVideoDecoder(VideoType.VideoFile, videoStream, GetEncodingOptions());
                 * if (!string.IsNullOrWhiteSpace(decoder))
                 * {
                 *  args = decoder + " " + args;
                 * }
                 */
            }

            if (!string.IsNullOrWhiteSpace(container))
            {
                var inputFormat = encodinghelper.GetInputFormat(container);
                if (!string.IsNullOrWhiteSpace(inputFormat))
                {
                    args = "-f " + inputFormat + " " + args;
                }
            }

            var process = _processFactory.Create(new ProcessOptions
            {
                CreateNoWindow  = true,
                UseShellExecute = false,
                FileName        = FFMpegPath,
                Arguments       = args,
                IsHidden        = true,
                ErrorDialog     = false
            });

            _logger.LogDebug("{0} {1}", process.StartInfo.FileName, process.StartInfo.Arguments);

            using (var processWrapper = new ProcessWrapper(process, this, _logger))
            {
                bool ranToCompletion;

                StartProcess(processWrapper);

                var timeoutMs = ConfigurationManager.Configuration.ImageExtractionTimeoutMs;
                if (timeoutMs <= 0)
                {
                    timeoutMs = DefaultImageExtractionTimeoutMs;
                }

                ranToCompletion = await process.WaitForExitAsync(timeoutMs).ConfigureAwait(false);

                if (!ranToCompletion)
                {
                    StopProcess(processWrapper, 1000);
                }

                var exitCode = ranToCompletion ? processWrapper.ExitCode ?? 0 : -1;
                var file     = FileSystem.GetFileInfo(tempExtractPath);

                if (exitCode == -1 || !file.Exists || file.Length == 0)
                {
                    var msg = string.Format("ffmpeg image extraction failed for {0}", inputPath);

                    _logger.LogError(msg);

                    throw new Exception(msg);
                }

                return(tempExtractPath);
            }
        }
コード例 #33
0
        private void CaptureMarketData()
        {
            try
            {
                CleanupDebugFiles();

                ProcessWrapper procWrap = comboBoxPPWindows.SelectedItem as ProcessWrapper;
                if (procWrap == null || procWrap.Process == null || procWrap.Process.HasExited)
                {
                    MessageBox.Show(this, "Can't find Puzzle Pirates window.", Application.ProductName);
                    return;
                }

                PPOcr  myOcr = new PPOcr(procWrap.Process);
                string island;

                DateTime dtStart = DateTime.Now;

                if (bidData != null)
                {
                    bidData.Clear();
                }
                allCommods = myOcr.ExtractAllCommodities(out island);

                this.BringToFront();
                this.Activate();

                if (myOcr.Error.Length > 0)
                {
                    MessageBox.Show(this, myOcr.Error, Application.ProductName);
                }

                if (island == null || island.Length <= 0)
                {
                    labelTitle.Text = "Island: Unknown";
                }
                else
                {
                    labelTitle.Text = "Island: " + island;
                }

                labelTitle.Text = labelTitle.Text + " on " + myOcr.Ocean;

                if (allCommods == null)
                {
                    dataGridView1.DataSource = null;
                    labelText.Text           = "Rows: 0";
                }
                else
                {
                    DateTime         dtStop = DateTime.Now;
                    List <Commodity> list   = new List <Commodity>(allCommods.Values);
                    dataGridView1.DataSource = list;

                    labelText.Text = "Rows: " + allCommods.Count.ToString() + "  Rows/Sec: " + (Convert.ToDouble(allCommods.Count) / dtStop.Subtract(dtStart).TotalSeconds).ToString("N0");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.Message.ToString() + "\n" + "\n" + ex.StackTrace.ToString(), Application.ProductName);
            }
        }
コード例 #34
0
        private async Task <string> ExtractImageInternal(string inputPath, string container, MediaStream videoStream, int?imageStreamIndex, Video3DFormat?threedFormat, TimeSpan?offset, bool useIFrame, bool allowTonemap, CancellationToken cancellationToken)
        {
            if (string.IsNullOrEmpty(inputPath))
            {
                throw new ArgumentNullException(nameof(inputPath));
            }

            var tempExtractPath = Path.Combine(_configurationManager.ApplicationPaths.TempDirectory, Guid.NewGuid() + ".jpg");

            Directory.CreateDirectory(Path.GetDirectoryName(tempExtractPath));

            // apply some filters to thumbnail extracted below (below) crop any black lines that we made and get the correct ar.
            // This filter chain may have adverse effects on recorded tv thumbnails if ar changes during presentation ex. commercials @ diff ar
            var vf = threedFormat switch
            {
                // hsbs crop width in half,scale to correct size, set the display aspect,crop out any black bars we may have made. Work out the correct height based on the display aspect it will maintain the aspect where -1 in this case (3d) may not.
                Video3DFormat.HalfSideBySide => "-vf crop=iw/2:ih:0:0,scale=(iw*2):ih,setdar=dar=a,crop=min(iw\\,ih*dar):min(ih\\,iw/dar):(iw-min(iw\\,iw*sar))/2:(ih - min (ih\\,ih/sar))/2,setsar=sar=1",
                // fsbs crop width in half,set the display aspect,crop out any black bars we may have made
                Video3DFormat.FullSideBySide => "-vf crop=iw/2:ih:0:0,setdar=dar=a,crop=min(iw\\,ih*dar):min(ih\\,iw/dar):(iw-min(iw\\,iw*sar))/2:(ih - min (ih\\,ih/sar))/2,setsar=sar=1",
                // htab crop heigh in half,scale to correct size, set the display aspect,crop out any black bars we may have made
                Video3DFormat.HalfTopAndBottom => "-vf crop=iw:ih/2:0:0,scale=(iw*2):ih),setdar=dar=a,crop=min(iw\\,ih*dar):min(ih\\,iw/dar):(iw-min(iw\\,iw*sar))/2:(ih - min (ih\\,ih/sar))/2,setsar=sar=1",
                // ftab crop heigt in half, set the display aspect,crop out any black bars we may have made
                Video3DFormat.FullTopAndBottom => "-vf crop=iw:ih/2:0:0,setdar=dar=a,crop=min(iw\\,ih*dar):min(ih\\,iw/dar):(iw-min(iw\\,iw*sar))/2:(ih - min (ih\\,ih/sar))/2,setsar=sar=1",
                _ => string.Empty
            };

            var mapArg = imageStreamIndex.HasValue ? (" -map 0:v:" + imageStreamIndex.Value.ToString(CultureInfo.InvariantCulture)) : string.Empty;

            var enableHdrExtraction = allowTonemap && string.Equals(videoStream?.VideoRange, "HDR", StringComparison.OrdinalIgnoreCase);

            if (enableHdrExtraction)
            {
                string tonemapFilters = "zscale=t=linear:npl=100,format=gbrpf32le,zscale=p=bt709,tonemap=tonemap=hable:desat=0:peak=100,zscale=t=bt709:m=bt709,format=yuv420p";
                if (vf.Length == 0)
                {
                    vf = "-vf " + tonemapFilters;
                }
                else
                {
                    vf += "," + tonemapFilters;
                }
            }

            // Use ffmpeg to sample 100 (we can drop this if required using thumbnail=50 for 50 frames) frames and pick the best thumbnail. Have a fall back just in case.
            // mpegts need larger batch size otherwise the corrupted thumbnail will be created. Larger batch size will lower the processing speed.
            var enableThumbnail = useIFrame && !string.Equals("wtv", container, StringComparison.OrdinalIgnoreCase);

            if (enableThumbnail)
            {
                var useLargerBatchSize = string.Equals("mpegts", container, StringComparison.OrdinalIgnoreCase);
                var batchSize          = useLargerBatchSize ? "50" : "24";
                if (string.IsNullOrEmpty(vf))
                {
                    vf = "-vf thumbnail=" + batchSize;
                }
                else
                {
                    vf += ",thumbnail=" + batchSize;
                }
            }

            var args = string.Format(CultureInfo.InvariantCulture, "-i {0}{3} -threads {4} -v quiet -vframes 1 {2} -f image2 \"{1}\"", inputPath, tempExtractPath, vf, mapArg, threads);

            if (offset.HasValue)
            {
                args = string.Format(CultureInfo.InvariantCulture, "-ss {0} ", GetTimeParameter(offset.Value)) + args;
            }

            if (!string.IsNullOrWhiteSpace(container))
            {
                var inputFormat = EncodingHelper.GetInputFormat(container);
                if (!string.IsNullOrWhiteSpace(inputFormat))
                {
                    args = "-f " + inputFormat + " " + args;
                }
            }

            var process = new Process
            {
                StartInfo = new ProcessStartInfo
                {
                    CreateNoWindow  = true,
                    UseShellExecute = false,
                    FileName        = _ffmpegPath,
                    Arguments       = args,
                    WindowStyle     = ProcessWindowStyle.Hidden,
                    ErrorDialog     = false,
                },
                EnableRaisingEvents = true
            };

            _logger.LogDebug("{ProcessFileName} {ProcessArguments}", process.StartInfo.FileName, process.StartInfo.Arguments);

            using (var processWrapper = new ProcessWrapper(process, this))
            {
                bool ranToCompletion;

                await _thumbnailResourcePool.WaitAsync(cancellationToken).ConfigureAwait(false);

                try
                {
                    StartProcess(processWrapper);

                    var timeoutMs = _configurationManager.Configuration.ImageExtractionTimeoutMs;
                    if (timeoutMs <= 0)
                    {
                        timeoutMs = enableHdrExtraction ? DefaultHdrImageExtractionTimeout : DefaultSdrImageExtractionTimeout;
                    }

                    ranToCompletion = await process.WaitForExitAsync(TimeSpan.FromMilliseconds(timeoutMs)).ConfigureAwait(false);

                    if (!ranToCompletion)
                    {
                        StopProcess(processWrapper, 1000);
                    }
                }
                finally
                {
                    _thumbnailResourcePool.Release();
                }

                var exitCode = ranToCompletion ? processWrapper.ExitCode ?? 0 : -1;
                var file     = _fileSystem.GetFileInfo(tempExtractPath);

                if (exitCode == -1 || !file.Exists || file.Length == 0)
                {
                    var msg = string.Format(CultureInfo.InvariantCulture, "ffmpeg image extraction failed for {0}", inputPath);

                    _logger.LogError(msg);

                    throw new FfmpegException(msg);
                }

                return(tempExtractPath);
            }
        }
コード例 #35
0
ファイル: Process.CLR.cs プロジェクト: dw4dev/Phalanger
		public static PhpResource OpenPipe(string command, string mode)
		{
			if (String.IsNullOrEmpty(mode))
			{
				PhpException.Throw(PhpError.Warning, CoreResources.GetString("invalid_file_mode", mode));
				return null;
			}

			bool read = mode[0] == 'r';
			bool write = mode[0] == 'w' || mode[0] == 'a' || mode[0] == 'x';

			if (!read && !write)
			{
				PhpException.Throw(PhpError.Warning, CoreResources.GetString("invalid_file_mode", mode));
				return null;
			}

			Process process = CreateProcessExecutingCommand(ref command, false);
			if (process == null) return null;

			process.StartInfo.RedirectStandardOutput = read;
			process.StartInfo.RedirectStandardInput = write;

			if (!StartProcess(process, true))
				return null;

			Stream stream = (read) ? process.StandardOutput.BaseStream : process.StandardInput.BaseStream;
			StreamAccessOptions access = (read) ? StreamAccessOptions.Read : StreamAccessOptions.Write;
			ProcessWrapper wrapper = new ProcessWrapper(process);
			PhpStream php_stream = new NativeStream(stream, wrapper, access, String.Empty, StreamContext.Default);

			return php_stream;
		}
コード例 #36
0
ファイル: ProcessHandlerSpecs.cs プロジェクト: pshomov/frog
 public void should_throw_an_exception_when_trying_to_get_process_snapshot_for_process_that_has_died()
 {
     var pw = new ProcessWrapper("ruby", @"-e exit 0");
     pw.Execute();
     pw.WaitForProcess(1000);
     var processId = pw.Id;
     //            pw.Dispose();
     Assert.That(ProcessHasExited(processId));
     try
     {
         var tpt = pw.ProcessTreeCPUUsageId;
         Assert.Fail("the process should have been gone, operation should have failed");
     }
     catch(InvalidOperationException)
     {
         // that's what we are aiming for ;)
     }
     pw.Dispose();
 }
コード例 #37
0
ファイル: DumpRequest.cs プロジェクト: fremag/MemoScope.Net
 public DumpRequest(ProcessWrapper processWrapper)
 {
     ProcessWrapper = processWrapper;
 }
コード例 #38
0
ファイル: MediaEncoder.cs プロジェクト: jrags56/MediaBrowser
        private async Task<List<int>> GetKeyFrames(string inputPath, int videoStreamIndex, CancellationToken cancellationToken)
        {
            const string args = "-i {0} -select_streams v:{1} -show_frames -show_entries frame=pkt_dts,key_frame -print_format compact";

            var process = new Process
            {
                StartInfo = new ProcessStartInfo
                {
                    CreateNoWindow = true,
                    UseShellExecute = false,

                    // Must consume both or ffmpeg may hang due to deadlocks. See comments below.   
                    RedirectStandardOutput = true,
                    RedirectStandardError = true,
                    RedirectStandardInput = true,
                    FileName = FFProbePath,
                    Arguments = string.Format(args, inputPath, videoStreamIndex.ToString(CultureInfo.InvariantCulture)).Trim(),

                    WindowStyle = ProcessWindowStyle.Hidden,
                    ErrorDialog = false
                },

                EnableRaisingEvents = true
            };

            _logger.Debug("{0} {1}", process.StartInfo.FileName, process.StartInfo.Arguments);

            using (var processWrapper = new ProcessWrapper(process, this, _logger))
            {
                StartProcess(processWrapper);

                var lines = new List<int>();

                try
                {
                    process.BeginErrorReadLine();

                    await StartReadingOutput(process.StandardOutput.BaseStream, lines, 120000, cancellationToken).ConfigureAwait(false);
                }
                catch (OperationCanceledException)
                {
                    if (cancellationToken.IsCancellationRequested)
                    {
                        throw;
                    }
                }
                finally
                {
                    StopProcess(processWrapper, 100, true);
                }

                return lines;
            }
        }
コード例 #39
0
		public void LoadAssemblyFromMetadataInterfaces(ModuleWrapper debuggedModule)
		{
			string assemblyPath = (IsInMemory ? Name : FullPath);
			NuGenUIHandler.Instance.ResetProgressBar();

			if (IsInMemory)
			{
				NuGenUIHandler.Instance.SetProgressBarMaximum(15);
				DebuggedProcess = debuggedModule.GetProcess();
			}
			else
			{
				NuGenUIHandler.Instance.SetProgressBarMaximum(16);
				NuGenUIHandler.Instance.SetProgressText(assemblyPath, "Reading header...", true);
				ReadHeader();
				NuGenUIHandler.Instance.StepProgressBar(1);
			}

			NuGenUIHandler.Instance.SetProgressText(assemblyPath, "Opening assembly references...", true);
			OpenAssemblyRefs();
			NuGenUIHandler.Instance.StepProgressBar(1);

			NuGenUIHandler.Instance.SetProgressText(assemblyPath, "Loading user strings...", true);
			GetUserStrings();
			NuGenUIHandler.Instance.StepProgressBar(1);

			NuGenUIHandler.Instance.SetProgressText(assemblyPath, "Loading manifest resources...", true);
			GetManifestResources();
			NuGenUIHandler.Instance.StepProgressBar(1);

			NuGenUIHandler.Instance.SetProgressText(assemblyPath, "Loading files...", true);
			GetFiles();
			NuGenUIHandler.Instance.StepProgressBar(1);

			NuGenUIHandler.Instance.SetProgressText(assemblyPath, "Loading module references...", true);
			GetModuleReferences();
			NuGenUIHandler.Instance.StepProgressBar(1);
			NuGenUIHandler.Instance.SetProgressText(assemblyPath, "Loading type references...", true);
			GetTypeReferences();
			NuGenUIHandler.Instance.StepProgressBar(1);
			NuGenUIHandler.Instance.SetProgressText(assemblyPath, "Loading global type's references...", true);
			NuGenHelperFunctions.GetMemberReferences(this, 0);
			NuGenUIHandler.Instance.StepProgressBar(1);
			NuGenUIHandler.Instance.SetProgressText(assemblyPath, "Loading type specifications...", true);
			GetTypeSpecs();
			NuGenUIHandler.Instance.StepProgressBar(1);
			NuGenUIHandler.Instance.SetProgressText(assemblyPath, "Loading standalone signatures...", true);
			GetSignatures();
			NuGenUIHandler.Instance.StepProgressBar(1);

			NuGenUIHandler.Instance.SetProgressText(assemblyPath, "Loading module scope...", true);
			ModuleScope = new NuGenModuleScope(Import, this);
			ModuleScope.EnumerateTypeDefinitions(Import, debuggedModule);
			NuGenUIHandler.Instance.StepProgressBar(1);
			NuGenUIHandler.Instance.SetProgressText(assemblyPath, "Loading global type...", true);
			GlobalType = new NuGenTypeDefinition(Import, ModuleScope, 0);
			NuGenUIHandler.Instance.StepProgressBar(1);
			AllTokens[0] = GlobalType;

			NuGenUIHandler.Instance.SetProgressText(assemblyPath, "Associating properties with methods...", true);
			AssociatePropertiesWithMethods();
			NuGenUIHandler.Instance.StepProgressBar(1);
			NuGenUIHandler.Instance.SetProgressText(assemblyPath, "Reading assembly properties...", true);

			DisplayInTree = false;
			try
			{
				ReadProperties();
				DisplayInTree = true;
			}
			catch (COMException comException)
			{
				unchecked
				{
					if (comException.ErrorCode != (int)0x80131130)
					{
						throw;
					}
				}
			}

			NuGenUIHandler.Instance.StepProgressBar(1);
			NuGenUIHandler.Instance.SetProgressText(assemblyPath, "Loading resolving resolution scopes...", true);
			ResolveResolutionScopes();
			NuGenUIHandler.Instance.StepProgressBar(1);
			NuGenUIHandler.Instance.SetProgressText(assemblyPath, "Searching for entry method...", true);
			SearchEntryPoint();
			NuGenUIHandler.Instance.StepProgressBar(1);
		}
コード例 #40
0
        private string[] Headers(Project project, string filename, bool with_system)
        {
            List <string> headers  = new List <string> ();
            CProject      cproject = project as CProject;

            if (cproject == null)
            {
                return(headers.ToArray());
            }

            StringBuilder output = new StringBuilder();
            StringBuilder option = new StringBuilder("-M");

            if (!with_system)
            {
                option.Append("M");
            }

            option.Append(" -MG ");
            foreach (Package package in cproject.Packages)
            {
                package.ParsePackage();
                option.AppendFormat("{0} ", string.Join(" ", package.CFlags.ToArray()));
            }

            ProcessWrapper p = null;

            try {
                p = Runtime.ProcessService.StartProcess("gcc", option.ToString() + filename.Replace(@"\ ", " ").Replace(" ", @"\ "), null, null);
                p.WaitForOutput();

                // Doing the below completely breaks header parsing
                // // Skip first two lines (.o & .c* files) - WARNING, sometimes this is compacted to 1 line... we need a better way of handling this.
                // if(p.StandardOutput.ReadLine () == null) return new string[0]; // object file
                // if(p.StandardOutput.ReadLine () == null) return new string[0]; // compile file

                string line;
                while ((line = p.StandardOutput.ReadLine()) != null)
                {
                    output.Append(line);
                }
            } catch (Exception ex) {
                LoggingService.LogError(ex.ToString());
                return(new string [0]);
            }
            finally {
                if (p != null)
                {
                    p.Dispose();
                }
            }

            MatchCollection files = Regex.Matches(output.ToString().Replace(@" \", String.Empty), @" (?<file>([^ \\]|(\\ ))+)", RegexOptions.IgnoreCase);

            foreach (Match match in files)
            {
                string depfile = findFileInIncludes(project, match.Groups["file"].Value.Trim());

                headers.Add(depfile.Replace(@"\ ", " ").Replace(" ", @"\ "));
            }

            return(headers.ToArray());
        }
コード例 #41
0
ファイル: MediaEncoder.cs プロジェクト: 7illusions/Emby
        private async Task<string> ExtractImageInternal(string inputPath, int? imageStreamIndex, MediaProtocol protocol, Video3DFormat? threedFormat, TimeSpan? offset, bool useIFrame, SemaphoreSlim resourcePool, CancellationToken cancellationToken)
        {
            if (string.IsNullOrEmpty(inputPath))
            {
                throw new ArgumentNullException("inputPath");
            }

            var tempExtractPath = Path.Combine(ConfigurationManager.ApplicationPaths.TempDirectory, Guid.NewGuid() + ".jpg");
            Directory.CreateDirectory(Path.GetDirectoryName(tempExtractPath));

            // apply some filters to thumbnail extracted below (below) crop any black lines that we made and get the correct ar then scale to width 600. 
            // This filter chain may have adverse effects on recorded tv thumbnails if ar changes during presentation ex. commercials @ diff ar
            var vf = "scale=600:trunc(600/dar/2)*2";

            if (threedFormat.HasValue)
            {
                switch (threedFormat.Value)
                {
                    case Video3DFormat.HalfSideBySide:
                        vf = "crop=iw/2:ih:0:0,scale=(iw*2):ih,setdar=dar=a,crop=min(iw\\,ih*dar):min(ih\\,iw/dar):(iw-min(iw\\,iw*sar))/2:(ih - min (ih\\,ih/sar))/2,setsar=sar=1,scale=600:trunc(600/dar/2)*2";
                        // hsbs crop width in half,scale to correct size, set the display aspect,crop out any black bars we may have made the scale width to 600. Work out the correct height based on the display aspect it will maintain the aspect where -1 in this case (3d) may not.
                        break;
                    case Video3DFormat.FullSideBySide:
                        vf = "crop=iw/2:ih:0:0,setdar=dar=a,crop=min(iw\\,ih*dar):min(ih\\,iw/dar):(iw-min(iw\\,iw*sar))/2:(ih - min (ih\\,ih/sar))/2,setsar=sar=1,scale=600:trunc(600/dar/2)*2";
                        //fsbs crop width in half,set the display aspect,crop out any black bars we may have made the scale width to 600.
                        break;
                    case Video3DFormat.HalfTopAndBottom:
                        vf = "crop=iw:ih/2:0:0,scale=(iw*2):ih),setdar=dar=a,crop=min(iw\\,ih*dar):min(ih\\,iw/dar):(iw-min(iw\\,iw*sar))/2:(ih - min (ih\\,ih/sar))/2,setsar=sar=1,scale=600:trunc(600/dar/2)*2";
                        //htab crop heigh in half,scale to correct size, set the display aspect,crop out any black bars we may have made the scale width to 600
                        break;
                    case Video3DFormat.FullTopAndBottom:
                        vf = "crop=iw:ih/2:0:0,setdar=dar=a,crop=min(iw\\,ih*dar):min(ih\\,iw/dar):(iw-min(iw\\,iw*sar))/2:(ih - min (ih\\,ih/sar))/2,setsar=sar=1,scale=600:trunc(600/dar/2)*2";
                        // ftab crop heigt in half, set the display aspect,crop out any black bars we may have made the scale width to 600
                        break;
                    default:
                        break;
                }
            }

            var mapArg = imageStreamIndex.HasValue ? (" -map 0:v:" + imageStreamIndex.Value.ToString(CultureInfo.InvariantCulture)) : string.Empty;

            // Use ffmpeg to sample 100 (we can drop this if required using thumbnail=50 for 50 frames) frames and pick the best thumbnail. Have a fall back just in case.
            var args = useIFrame ? string.Format("-i {0}{3} -threads 0 -v quiet -vframes 1 -vf \"{2},thumbnail=30\" -f image2 \"{1}\"", inputPath, tempExtractPath, vf, mapArg) :
                string.Format("-i {0}{3} -threads 0 -v quiet -vframes 1 -vf \"{2}\" -f image2 \"{1}\"", inputPath, tempExtractPath, vf, mapArg);

            var probeSize = GetProbeSizeArgument(new[] { inputPath }, protocol);

            if (!string.IsNullOrEmpty(probeSize))
            {
                args = probeSize + " " + args;
            }

            if (offset.HasValue)
            {
                args = string.Format("-ss {0} ", GetTimeParameter(offset.Value)) + args;
            }

            var process = new Process
            {
                StartInfo = new ProcessStartInfo
                {
                    CreateNoWindow = true,
                    UseShellExecute = false,
                    FileName = FFMpegPath,
                    Arguments = args,
                    WindowStyle = ProcessWindowStyle.Hidden,
                    ErrorDialog = false
                }
            };

            _logger.Debug("{0} {1}", process.StartInfo.FileName, process.StartInfo.Arguments);

            using (var processWrapper = new ProcessWrapper(process, this, _logger, false))
            {
                await resourcePool.WaitAsync(cancellationToken).ConfigureAwait(false);

                bool ranToCompletion;

                try
                {
                    StartProcess(processWrapper);

                    ranToCompletion = process.WaitForExit(10000);

                    if (!ranToCompletion)
                    {
                        StopProcess(processWrapper, 1000, false);
                    }

                }
                finally
                {
                    resourcePool.Release();
                }

                var exitCode = ranToCompletion ? processWrapper.ExitCode ?? 0 : -1;
                var file = new FileInfo(tempExtractPath);

                if (exitCode == -1 || !file.Exists || file.Length == 0)
                {
                    var msg = string.Format("ffmpeg image extraction failed for {0}", inputPath);

                    _logger.Error(msg);

                    throw new ApplicationException(msg);
                }

                return tempExtractPath;
            }
        }
コード例 #42
0
        bool CheckBug77135()
        {
            try {
                // Check for bug 77135. Some versions of gnome-vfs2 and libgda
                // make MD crash in the file open dialog or in FileIconLoader.
                // Only in Suse.

                string path = "/etc/SuSE-release";
                if (!File.Exists(path))
                {
                    return(true);
                }

                // Only run the check for SUSE 10
                StreamReader sr  = File.OpenText(path);
                string       txt = sr.ReadToEnd();
                sr.Close();

                if (txt.IndexOf("SUSE LINUX 10") == -1)
                {
                    return(true);
                }

                string current_libgda;
                string current_gnomevfs;
                string required_libgda   = "1.3.91.5.4";
                string required_gnomevfs = "2.12.0.9.2";

                StringWriter   sw = new StringWriter();
                ProcessWrapper pw = Runtime.ProcessService.StartProcess("rpm", "--qf %{version}.%{release} -q libgda", null, sw, null, null);
                pw.WaitForOutput();
                current_libgda = sw.ToString().Trim(' ', '\n');

                sw = new StringWriter();
                pw = Runtime.ProcessService.StartProcess("rpm", "--qf %{version}.%{release} -q gnome-vfs2", null, sw, null, null);
                pw.WaitForOutput();
                current_gnomevfs = sw.ToString().Trim(' ', '\n');

                bool fail1 = Addin.CompareVersions(current_libgda, required_libgda) == 1;
                bool fail2 = Addin.CompareVersions(current_gnomevfs, required_gnomevfs) == 1;

                if (fail1 || fail2)
                {
                    string msg = GettextCatalog.GetString("Some packages installed in your system are not compatible with MonoDevelop:\n");
                    if (fail1)
                    {
                        msg += "\nlibgda " + current_libgda + " (" + GettextCatalog.GetString("version required: {0}", required_libgda) + ")";
                    }
                    if (fail2)
                    {
                        msg += "\ngnome-vfs2 " + current_gnomevfs + " (" + GettextCatalog.GetString("version required: {0}", required_gnomevfs) + ")";
                    }
                    msg += "\n\n";
                    msg += GettextCatalog.GetString("You need to upgrade the previous packages to start using MonoDevelop.");

                    SplashScreenForm.SplashScreen.Hide();
                    Gtk.MessageDialog dlg = new Gtk.MessageDialog(null, Gtk.DialogFlags.Modal, Gtk.MessageType.Error, Gtk.ButtonsType.Ok, msg);
                    dlg.Run();
                    dlg.Destroy();

                    return(false);
                }
                else
                {
                    return(true);
                }
            }
            catch (Exception ex)
            {
                // Just ignore for now.
                Console.WriteLine(ex);
                return(true);
            }
        }
コード例 #43
0
        public async Task ExtractVideoImagesOnInterval(
            string inputFile,
            string container,
            MediaStream videoStream,
            MediaSourceInfo mediaSource,
            Video3DFormat?threedFormat,
            TimeSpan interval,
            string targetDirectory,
            string filenamePrefix,
            int?maxWidth,
            CancellationToken cancellationToken)
        {
            var inputArgument = GetInputArgument(inputFile, mediaSource);

            var vf = "fps=fps=1/" + interval.TotalSeconds.ToString(_usCulture);

            if (maxWidth.HasValue)
            {
                var maxWidthParam = maxWidth.Value.ToString(_usCulture);

                vf += string.Format(CultureInfo.InvariantCulture, ",scale=min(iw\\,{0}):trunc(ow/dar/2)*2", maxWidthParam);
            }

            Directory.CreateDirectory(targetDirectory);
            var outputPath = Path.Combine(targetDirectory, filenamePrefix + "%05d.jpg");

            var args = string.Format(CultureInfo.InvariantCulture, "-i {0} -threads {3} -v quiet {2} -f image2 \"{1}\"", inputArgument, outputPath, vf, threads);

            if (!string.IsNullOrWhiteSpace(container))
            {
                var inputFormat = EncodingHelper.GetInputFormat(container);
                if (!string.IsNullOrWhiteSpace(inputFormat))
                {
                    args = "-f " + inputFormat + " " + args;
                }
            }

            var processStartInfo = new ProcessStartInfo
            {
                CreateNoWindow  = true,
                UseShellExecute = false,
                FileName        = _ffmpegPath,
                Arguments       = args,
                WindowStyle     = ProcessWindowStyle.Hidden,
                ErrorDialog     = false
            };

            _logger.LogInformation(processStartInfo.FileName + " " + processStartInfo.Arguments);

            await _thumbnailResourcePool.WaitAsync(cancellationToken).ConfigureAwait(false);

            bool ranToCompletion = false;

            var process = new Process
            {
                StartInfo           = processStartInfo,
                EnableRaisingEvents = true
            };

            using (var processWrapper = new ProcessWrapper(process, this))
            {
                try
                {
                    StartProcess(processWrapper);

                    // Need to give ffmpeg enough time to make all the thumbnails, which could be a while,
                    // but we still need to detect if the process hangs.
                    // Making the assumption that as long as new jpegs are showing up, everything is good.

                    bool isResponsive = true;
                    int  lastCount    = 0;

                    while (isResponsive)
                    {
                        if (await process.WaitForExitAsync(TimeSpan.FromSeconds(30)).ConfigureAwait(false))
                        {
                            ranToCompletion = true;
                            break;
                        }

                        cancellationToken.ThrowIfCancellationRequested();

                        var jpegCount = _fileSystem.GetFilePaths(targetDirectory)
                                        .Count(i => string.Equals(Path.GetExtension(i), ".jpg", StringComparison.OrdinalIgnoreCase));

                        isResponsive = jpegCount > lastCount;
                        lastCount    = jpegCount;
                    }

                    if (!ranToCompletion)
                    {
                        StopProcess(processWrapper, 1000);
                    }
                }
                finally
                {
                    _thumbnailResourcePool.Release();
                }

                var exitCode = ranToCompletion ? processWrapper.ExitCode ?? 0 : -1;

                if (exitCode == -1)
                {
                    var msg = string.Format(CultureInfo.InvariantCulture, "ffmpeg image extraction failed for {0}", inputArgument);

                    _logger.LogError(msg);

                    throw new FfmpegException(msg);
                }
            }
        }
コード例 #44
0
ファイル: ProcessHandlerSpecs.cs プロジェクト: pshomov/frog
 public void should_run_when_no_std_error_output_is_captured()
 {
     var pw = new ProcessWrapper("ruby", "-e '$stderr.puts(\"fle\")'");
     pw.Execute();
     pw.WaitForProcess(5000);
 }
コード例 #45
0
ファイル: MediaEncoder.cs プロジェクト: kuebelkasten/Emby
        /// <summary>
        /// Gets the media info internal.
        /// </summary>
        /// <param name="inputPath">The input path.</param>
        /// <param name="primaryPath">The primary path.</param>
        /// <param name="protocol">The protocol.</param>
        /// <param name="extractChapters">if set to <c>true</c> [extract chapters].</param>
        /// <param name="probeSizeArgument">The probe size argument.</param>
        /// <param name="isAudio">if set to <c>true</c> [is audio].</param>
        /// <param name="videoType">Type of the video.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns>Task{MediaInfoResult}.</returns>
        /// <exception cref="System.ApplicationException">ffprobe failed - streams and format are both null.</exception>
        private async Task<Model.MediaInfo.MediaInfo> GetMediaInfoInternal(string inputPath,
            string primaryPath,
            MediaProtocol protocol,
            bool extractChapters,
            string probeSizeArgument,
            bool isAudio,
            VideoType videoType,
            CancellationToken cancellationToken)
        {
            var args = extractChapters
                ? "{0} -i {1} -threads 0 -v info -print_format json -show_streams -show_chapters -show_format"
                : "{0} -i {1} -threads 0 -v info -print_format json -show_streams -show_format";

            var process = new Process
            {
                StartInfo = new ProcessStartInfo
                {
                    CreateNoWindow = true,
                    UseShellExecute = false,

                    // Must consume both or ffmpeg may hang due to deadlocks. See comments below.   
                    RedirectStandardOutput = true,
                    RedirectStandardError = true,
                    RedirectStandardInput = true,
                    FileName = FFProbePath,
                    Arguments = string.Format(args,
                    probeSizeArgument, inputPath).Trim(),

                    WindowStyle = ProcessWindowStyle.Hidden,
                    ErrorDialog = false
                },

                EnableRaisingEvents = true
            };

            _logger.Debug("{0} {1}", process.StartInfo.FileName, process.StartInfo.Arguments);

            using (var processWrapper = new ProcessWrapper(process, this, _logger))
            {
                await _ffProbeResourcePool.WaitAsync(cancellationToken).ConfigureAwait(false);

                try
                {
                    StartProcess(processWrapper);
                }
                catch (Exception ex)
                {
                    _ffProbeResourcePool.Release();

                    _logger.ErrorException("Error starting ffprobe", ex);

                    throw;
                }

                try
                {
                    process.BeginErrorReadLine();

                    var result = _jsonSerializer.DeserializeFromStream<InternalMediaInfoResult>(process.StandardOutput.BaseStream);

                    if (result.streams == null && result.format == null)
                    {
                        throw new ApplicationException("ffprobe failed - streams and format are both null.");
                    }

                    if (result.streams != null)
                    {
                        // Normalize aspect ratio if invalid
                        foreach (var stream in result.streams)
                        {
                            if (string.Equals(stream.display_aspect_ratio, "0:1", StringComparison.OrdinalIgnoreCase))
                            {
                                stream.display_aspect_ratio = string.Empty;
                            }
                            if (string.Equals(stream.sample_aspect_ratio, "0:1", StringComparison.OrdinalIgnoreCase))
                            {
                                stream.sample_aspect_ratio = string.Empty;
                            }
                        }
                    }

                    var mediaInfo = new ProbeResultNormalizer(_logger, FileSystem).GetMediaInfo(result, videoType, isAudio, primaryPath, protocol);

                    var videoStream = mediaInfo.MediaStreams.FirstOrDefault(i => i.Type == MediaStreamType.Video);

                    if (videoStream != null)
                    {
                        var isInterlaced = await DetectInterlaced(mediaInfo, videoStream, inputPath, probeSizeArgument).ConfigureAwait(false);

                        if (isInterlaced)
                        {
                            videoStream.IsInterlaced = true;
                        }
                    }

                    return mediaInfo;
                }
                catch
                {
                    StopProcess(processWrapper, 100, true);

                    throw;
                }
                finally
                {
                    _ffProbeResourcePool.Release();
                }
            }
        }
コード例 #46
0
		public NuGenInMemoryMethodStream(ProcessWrapper debuggedProcess, ulong startingAddress)
		{
			DebuggedProcess = debuggedProcess;
			StartingAddress = startingAddress;
			CurrentAddress = StartingAddress;
		}
コード例 #47
0
ファイル: MediaEncoder.cs プロジェクト: kuebelkasten/Emby
        private async Task<bool> DetectInterlaced(MediaSourceInfo video, MediaStream videoStream, string inputPath, string probeSizeArgument)
        {
            if (video.Protocol != MediaProtocol.File)
            {
                return false;
            }

            // If the video codec is not some form of mpeg, then take a shortcut and limit this to containers that are likely to have interlaced content
            if ((videoStream.Codec ?? string.Empty).IndexOf("mpeg", StringComparison.OrdinalIgnoreCase) == -1)
            {
                var formats = (video.Container ?? string.Empty).Split(',').ToList();

                if (!formats.Contains("vob", StringComparer.OrdinalIgnoreCase) &&
                    !formats.Contains("m2ts", StringComparer.OrdinalIgnoreCase) &&
                    !formats.Contains("ts", StringComparer.OrdinalIgnoreCase) &&
                    !formats.Contains("mpegts", StringComparer.OrdinalIgnoreCase) &&
                    !formats.Contains("wtv", StringComparer.OrdinalIgnoreCase))
                {
                    return false;
                }
            }

            var args = "{0} -i {1} -map 0:v:{2} -an -filter:v idet -frames:v 500 -an -f null /dev/null";

            var process = new Process
            {
                StartInfo = new ProcessStartInfo
                {
                    CreateNoWindow = true,
                    UseShellExecute = false,

                    // Must consume both or ffmpeg may hang due to deadlocks. See comments below.   
                    RedirectStandardOutput = true,
                    RedirectStandardError = true,
                    RedirectStandardInput = true,
                    FileName = FFMpegPath,
                    Arguments = string.Format(args, probeSizeArgument, inputPath, videoStream.Index.ToString(CultureInfo.InvariantCulture)).Trim(),

                    WindowStyle = ProcessWindowStyle.Hidden,
                    ErrorDialog = false
                },

                EnableRaisingEvents = true
            };

            _logger.Debug("{0} {1}", process.StartInfo.FileName, process.StartInfo.Arguments);
            var idetFoundInterlaced = false;

            using (var processWrapper = new ProcessWrapper(process, this, _logger))
            {
                try
                {
                    StartProcess(processWrapper);
                }
                catch (Exception ex)
                {
                    _logger.ErrorException("Error starting ffprobe", ex);

                    throw;
                }

                try
                {
                    process.BeginOutputReadLine();

                    using (var reader = new StreamReader(process.StandardError.BaseStream))
                    {
                        while (!reader.EndOfStream)
                        {
                            var line = await reader.ReadLineAsync().ConfigureAwait(false);

                            if (line.StartsWith("[Parsed_idet", StringComparison.OrdinalIgnoreCase))
                            {
                                var idetResult = AnalyzeIdetResult(line);

                                if (idetResult.HasValue)
                                {
                                    if (!idetResult.Value)
                                    {
                                        return false;
                                    }

                                    idetFoundInterlaced = true;
                                }
                            }
                        }
                    }

                }
                catch
                {
                    StopProcess(processWrapper, 100, true);

                    throw;
                }
            }

            return idetFoundInterlaced;
        }
コード例 #48
0
ファイル: MediaEncoder.cs プロジェクト: kuebelkasten/Emby
        private async Task<Stream> ExtractImageInternal(string inputPath, int? imageStreamIndex, MediaProtocol protocol, Video3DFormat? threedFormat, TimeSpan? offset, bool useIFrame, SemaphoreSlim resourcePool, CancellationToken cancellationToken)
        {
            if (string.IsNullOrEmpty(inputPath))
            {
                throw new ArgumentNullException("inputPath");
            }

            // apply some filters to thumbnail extracted below (below) crop any black lines that we made and get the correct ar then scale to width 600. 
            // This filter chain may have adverse effects on recorded tv thumbnails if ar changes during presentation ex. commercials @ diff ar
            var vf = "scale=600:trunc(600/dar/2)*2";

            if (threedFormat.HasValue)
            {
                switch (threedFormat.Value)
                {
                    case Video3DFormat.HalfSideBySide:
                        vf = "crop=iw/2:ih:0:0,scale=(iw*2):ih,setdar=dar=a,crop=min(iw\\,ih*dar):min(ih\\,iw/dar):(iw-min(iw\\,iw*sar))/2:(ih - min (ih\\,ih/sar))/2,setsar=sar=1,scale=600:trunc(600/dar/2)*2";
                        // hsbs crop width in half,scale to correct size, set the display aspect,crop out any black bars we may have made the scale width to 600. Work out the correct height based on the display aspect it will maintain the aspect where -1 in this case (3d) may not.
                        break;
                    case Video3DFormat.FullSideBySide:
                        vf = "crop=iw/2:ih:0:0,setdar=dar=a,crop=min(iw\\,ih*dar):min(ih\\,iw/dar):(iw-min(iw\\,iw*sar))/2:(ih - min (ih\\,ih/sar))/2,setsar=sar=1,scale=600:trunc(600/dar/2)*2";
                        //fsbs crop width in half,set the display aspect,crop out any black bars we may have made the scale width to 600.
                        break;
                    case Video3DFormat.HalfTopAndBottom:
                        vf = "crop=iw:ih/2:0:0,scale=(iw*2):ih),setdar=dar=a,crop=min(iw\\,ih*dar):min(ih\\,iw/dar):(iw-min(iw\\,iw*sar))/2:(ih - min (ih\\,ih/sar))/2,setsar=sar=1,scale=600:trunc(600/dar/2)*2";
                        //htab crop heigh in half,scale to correct size, set the display aspect,crop out any black bars we may have made the scale width to 600
                        break;
                    case Video3DFormat.FullTopAndBottom:
                        vf = "crop=iw:ih/2:0:0,setdar=dar=a,crop=min(iw\\,ih*dar):min(ih\\,iw/dar):(iw-min(iw\\,iw*sar))/2:(ih - min (ih\\,ih/sar))/2,setsar=sar=1,scale=600:trunc(600/dar/2)*2";
                        // ftab crop heigt in half, set the display aspect,crop out any black bars we may have made the scale width to 600
                        break;
                }
            }

            var mapArg = imageStreamIndex.HasValue ? (" -map 0:v:" + imageStreamIndex.Value.ToString(CultureInfo.InvariantCulture)) : string.Empty;

            // Use ffmpeg to sample 100 (we can drop this if required using thumbnail=50 for 50 frames) frames and pick the best thumbnail. Have a fall back just in case.
            var args = useIFrame ? string.Format("-i {0}{3} -threads 1 -v quiet -vframes 1 -vf \"{2},thumbnail=30\" -f image2 \"{1}\"", inputPath, "-", vf, mapArg) :
                string.Format("-i {0}{3} -threads 1 -v quiet -vframes 1 -vf \"{2}\" -f image2 \"{1}\"", inputPath, "-", vf, mapArg);

            var probeSize = GetProbeSizeArgument(new[] { inputPath }, protocol);

            if (!string.IsNullOrEmpty(probeSize))
            {
                args = probeSize + " " + args;
            }

            if (offset.HasValue)
            {
                args = string.Format("-ss {0} ", GetTimeParameter(offset.Value)) + args;
            }

            var process = new Process
            {
                StartInfo = new ProcessStartInfo
                {
                    CreateNoWindow = true,
                    UseShellExecute = false,
                    FileName = FFMpegPath,
                    Arguments = args,
                    WindowStyle = ProcessWindowStyle.Hidden,
                    ErrorDialog = false,
                    RedirectStandardOutput = true,
                    RedirectStandardError = true,
                    RedirectStandardInput = true
                }
            };

            _logger.Debug("{0} {1}", process.StartInfo.FileName, process.StartInfo.Arguments);

            using (var processWrapper = new ProcessWrapper(process, this, _logger))
            {
                await resourcePool.WaitAsync(cancellationToken).ConfigureAwait(false);

                bool ranToCompletion;

                var memoryStream = new MemoryStream();

                try
                {
                    StartProcess(processWrapper);

#pragma warning disable 4014
                    // Important - don't await the log task or we won't be able to kill ffmpeg when the user stops playback
                    process.StandardOutput.BaseStream.CopyToAsync(memoryStream);
#pragma warning restore 4014

                    // MUST read both stdout and stderr asynchronously or a deadlock may occurr
                    process.BeginErrorReadLine();

                    ranToCompletion = process.WaitForExit(10000);

                    if (!ranToCompletion)
                    {
                        StopProcess(processWrapper, 1000, false);
                    }

                }
                finally
                {
                    resourcePool.Release();
                }

                var exitCode = ranToCompletion ? processWrapper.ExitCode ?? 0 : -1;

                if (exitCode == -1 || memoryStream.Length == 0)
                {
                    memoryStream.Dispose();

                    var msg = string.Format("ffmpeg image extraction failed for {0}", inputPath);

                    _logger.Error(msg);

                    throw new ApplicationException(msg);
                }

                memoryStream.Position = 0;
                return memoryStream;
            }
        }
コード例 #49
0
ファイル: MediaEncoder.cs プロジェクト: sxryt/jellyfin
        /// <summary>
        /// Gets the media info internal.
        /// </summary>
        /// <returns>Task{MediaInfoResult}.</returns>
        private async Task <MediaInfo> GetMediaInfoInternal(string inputPath,
                                                            string primaryPath,
                                                            MediaProtocol protocol,
                                                            bool extractChapters,
                                                            string probeSizeArgument,
                                                            bool isAudio,
                                                            VideoType?videoType,
                                                            bool forceEnableLogging,
                                                            CancellationToken cancellationToken)
        {
            var args = extractChapters
                ? "{0} -i {1} -threads 0 -v info -print_format json -show_streams -show_chapters -show_format"
                : "{0} -i {1} -threads 0 -v info -print_format json -show_streams -show_format";

            var process = _processFactory.Create(new ProcessOptions
            {
                CreateNoWindow  = true,
                UseShellExecute = false,

                // Must consume both or ffmpeg may hang due to deadlocks. See comments below.
                RedirectStandardOutput = true,
                FileName  = FFProbePath,
                Arguments = string.Format(args, probeSizeArgument, inputPath).Trim(),

                IsHidden            = true,
                ErrorDialog         = false,
                EnableRaisingEvents = true
            });

            if (forceEnableLogging)
            {
                _logger.LogInformation("{0} {1}", process.StartInfo.FileName, process.StartInfo.Arguments);
            }
            else
            {
                _logger.LogDebug("{0} {1}", process.StartInfo.FileName, process.StartInfo.Arguments);
            }

            using (var processWrapper = new ProcessWrapper(process, this, _logger))
            {
                StartProcess(processWrapper);

                try
                {
                    //process.BeginErrorReadLine();

                    var result = await _jsonSerializer.DeserializeFromStreamAsync <InternalMediaInfoResult>(process.StandardOutput.BaseStream).ConfigureAwait(false);

                    if (result == null || (result.streams == null && result.format == null))
                    {
                        throw new Exception("ffprobe failed - streams and format are both null.");
                    }

                    if (result.streams != null)
                    {
                        // Normalize aspect ratio if invalid
                        foreach (var stream in result.streams)
                        {
                            if (string.Equals(stream.display_aspect_ratio, "0:1", StringComparison.OrdinalIgnoreCase))
                            {
                                stream.display_aspect_ratio = string.Empty;
                            }
                            if (string.Equals(stream.sample_aspect_ratio, "0:1", StringComparison.OrdinalIgnoreCase))
                            {
                                stream.sample_aspect_ratio = string.Empty;
                            }
                        }
                    }

                    return(new ProbeResultNormalizer(_logger, FileSystem).GetMediaInfo(result, videoType, isAudio, primaryPath, protocol));
                }
                catch
                {
                    StopProcess(processWrapper, 100);

                    throw;
                }
            }
        }
コード例 #50
0
ファイル: MediaEncoder.cs プロジェクト: kuebelkasten/Emby
        public async Task ExtractVideoImagesOnInterval(string[] inputFiles,
            MediaProtocol protocol,
            Video3DFormat? threedFormat,
            TimeSpan interval,
            string targetDirectory,
            string filenamePrefix,
            int? maxWidth,
            CancellationToken cancellationToken)
        {
            var resourcePool = _thumbnailResourcePool;

            var inputArgument = GetInputArgument(inputFiles, protocol);

            var vf = "fps=fps=1/" + interval.TotalSeconds.ToString(UsCulture);

            if (maxWidth.HasValue)
            {
                var maxWidthParam = maxWidth.Value.ToString(UsCulture);

                vf += string.Format(",scale=min(iw\\,{0}):trunc(ow/dar/2)*2", maxWidthParam);
            }

            FileSystem.CreateDirectory(targetDirectory);
            var outputPath = Path.Combine(targetDirectory, filenamePrefix + "%05d.jpg");

            var args = string.Format("-i {0} -threads 1 -v quiet -vf \"{2}\" -f image2 \"{1}\"", inputArgument, outputPath, vf);

            var probeSize = GetProbeSizeArgument(new[] { inputArgument }, protocol);

            if (!string.IsNullOrEmpty(probeSize))
            {
                args = probeSize + " " + args;
            }

            var process = new Process
            {
                StartInfo = new ProcessStartInfo
                {
                    CreateNoWindow = true,
                    UseShellExecute = false,
                    FileName = FFMpegPath,
                    Arguments = args,
                    WindowStyle = ProcessWindowStyle.Hidden,
                    ErrorDialog = false,
                    RedirectStandardInput = true
                }
            };

            _logger.Info(process.StartInfo.FileName + " " + process.StartInfo.Arguments);

            await resourcePool.WaitAsync(cancellationToken).ConfigureAwait(false);

            bool ranToCompletion = false;

            using (var processWrapper = new ProcessWrapper(process, this, _logger))
            {
                try
                {
                    StartProcess(processWrapper);

                    // Need to give ffmpeg enough time to make all the thumbnails, which could be a while,
                    // but we still need to detect if the process hangs.
                    // Making the assumption that as long as new jpegs are showing up, everything is good.

                    bool isResponsive = true;
                    int lastCount = 0;

                    while (isResponsive)
                    {
                        if (process.WaitForExit(30000))
                        {
                            ranToCompletion = true;
                            break;
                        }

                        cancellationToken.ThrowIfCancellationRequested();

                        var jpegCount = Directory.GetFiles(targetDirectory)
                            .Count(i => string.Equals(Path.GetExtension(i), ".jpg", StringComparison.OrdinalIgnoreCase));

                        isResponsive = (jpegCount > lastCount);
                        lastCount = jpegCount;
                    }

                    if (!ranToCompletion)
                    {
                        StopProcess(processWrapper, 1000, false);
                    }
                }
                finally
                {
                    resourcePool.Release();
                }

                var exitCode = ranToCompletion ? processWrapper.ExitCode ?? 0 : -1;

                if (exitCode == -1)
                {
                    var msg = string.Format("ffmpeg image extraction failed for {0}", inputArgument);

                    _logger.Error(msg);

                    throw new ApplicationException(msg);
                }
            }
        }
コード例 #51
0
ファイル: MediaEncoder.cs プロジェクト: sxryt/jellyfin
        public async Task ExtractVideoImagesOnInterval(string[] inputFiles,
                                                       string container,
                                                       MediaStream videoStream,
                                                       MediaProtocol protocol,
                                                       Video3DFormat?threedFormat,
                                                       TimeSpan interval,
                                                       string targetDirectory,
                                                       string filenamePrefix,
                                                       int?maxWidth,
                                                       CancellationToken cancellationToken)
        {
            var resourcePool = _thumbnailResourcePool;

            var inputArgument = GetInputArgument(inputFiles, protocol);

            var vf = "fps=fps=1/" + interval.TotalSeconds.ToString(UsCulture);

            if (maxWidth.HasValue)
            {
                var maxWidthParam = maxWidth.Value.ToString(UsCulture);

                vf += string.Format(",scale=min(iw\\,{0}):trunc(ow/dar/2)*2", maxWidthParam);
            }

            FileSystem.CreateDirectory(targetDirectory);
            var outputPath = Path.Combine(targetDirectory, filenamePrefix + "%05d.jpg");

            var args = string.Format("-i {0} -threads 0 -v quiet -vf \"{2}\" -f image2 \"{1}\"", inputArgument, outputPath, vf);

            var probeSizeArgument       = EncodingHelper.GetProbeSizeArgument(1);
            var analyzeDurationArgument = EncodingHelper.GetAnalyzeDurationArgument(1);

            if (!string.IsNullOrWhiteSpace(probeSizeArgument))
            {
                args = probeSizeArgument + " " + args;
            }

            if (!string.IsNullOrWhiteSpace(analyzeDurationArgument))
            {
                args = analyzeDurationArgument + " " + args;
            }

            var encodinghelper = new EncodingHelper(this, FileSystem, SubtitleEncoder());

            if (videoStream != null)
            {
                /* fix
                 * var decoder = encodinghelper.GetHardwareAcceleratedVideoDecoder(VideoType.VideoFile, videoStream, GetEncodingOptions());
                 * if (!string.IsNullOrWhiteSpace(decoder))
                 * {
                 *  args = decoder + " " + args;
                 * }
                 */
            }

            if (!string.IsNullOrWhiteSpace(container))
            {
                var inputFormat = encodinghelper.GetInputFormat(container);
                if (!string.IsNullOrWhiteSpace(inputFormat))
                {
                    args = "-f " + inputFormat + " " + args;
                }
            }

            var process = _processFactory.Create(new ProcessOptions
            {
                CreateNoWindow  = true,
                UseShellExecute = false,
                FileName        = FFMpegPath,
                Arguments       = args,
                IsHidden        = true,
                ErrorDialog     = false
            });

            _logger.LogInformation(process.StartInfo.FileName + " " + process.StartInfo.Arguments);

            await resourcePool.WaitAsync(cancellationToken).ConfigureAwait(false);

            bool ranToCompletion = false;

            using (var processWrapper = new ProcessWrapper(process, this, _logger))
            {
                try
                {
                    StartProcess(processWrapper);

                    // Need to give ffmpeg enough time to make all the thumbnails, which could be a while,
                    // but we still need to detect if the process hangs.
                    // Making the assumption that as long as new jpegs are showing up, everything is good.

                    bool isResponsive = true;
                    int  lastCount    = 0;

                    while (isResponsive)
                    {
                        if (await process.WaitForExitAsync(30000).ConfigureAwait(false))
                        {
                            ranToCompletion = true;
                            break;
                        }

                        cancellationToken.ThrowIfCancellationRequested();

                        var jpegCount = FileSystem.GetFilePaths(targetDirectory)
                                        .Count(i => string.Equals(Path.GetExtension(i), ".jpg", StringComparison.OrdinalIgnoreCase));

                        isResponsive = (jpegCount > lastCount);
                        lastCount    = jpegCount;
                    }

                    if (!ranToCompletion)
                    {
                        StopProcess(processWrapper, 1000);
                    }
                }
                finally
                {
                    resourcePool.Release();
                }

                var exitCode = ranToCompletion ? processWrapper.ExitCode ?? 0 : -1;

                if (exitCode == -1)
                {
                    var msg = string.Format("ffmpeg image extraction failed for {0}", inputArgument);

                    _logger.LogError(msg);

                    throw new Exception(msg);
                }
            }
        }
コード例 #52
0
ファイル: MediaEncoder.cs プロジェクト: kuebelkasten/Emby
        private void StartProcess(ProcessWrapper process)
        {
            process.Process.Start();

            lock (_runningProcesses)
            {
                _runningProcesses.Add(process);
            }
        }
コード例 #53
0
ファイル: MediaEncoder.cs プロジェクト: bert-alpen/Emby
        private async Task <Stream> ExtractImageInternal(string inputPath, MediaProtocol protocol, Video3DFormat?threedFormat, TimeSpan?offset, bool useIFrame, SemaphoreSlim resourcePool, CancellationToken cancellationToken)
        {
            if (string.IsNullOrEmpty(inputPath))
            {
                throw new ArgumentNullException("inputPath");
            }

            // apply some filters to thumbnail extracted below (below) crop any black lines that we made and get the correct ar then scale to width 600.
            // This filter chain may have adverse effects on recorded tv thumbnails if ar changes during presentation ex. commercials @ diff ar
            var vf = "scale=600:trunc(600/dar/2)*2";

            if (threedFormat.HasValue)
            {
                switch (threedFormat.Value)
                {
                case Video3DFormat.HalfSideBySide:
                    vf = "crop=iw/2:ih:0:0,scale=(iw*2):ih,setdar=dar=a,crop=min(iw\\,ih*dar):min(ih\\,iw/dar):(iw-min(iw\\,iw*sar))/2:(ih - min (ih\\,ih/sar))/2,setsar=sar=1,scale=600:trunc(600/dar/2)*2";
                    // hsbs crop width in half,scale to correct size, set the display aspect,crop out any black bars we may have made the scale width to 600. Work out the correct height based on the display aspect it will maintain the aspect where -1 in this case (3d) may not.
                    break;

                case Video3DFormat.FullSideBySide:
                    vf = "crop=iw/2:ih:0:0,setdar=dar=a,crop=min(iw\\,ih*dar):min(ih\\,iw/dar):(iw-min(iw\\,iw*sar))/2:(ih - min (ih\\,ih/sar))/2,setsar=sar=1,scale=600:trunc(600/dar/2)*2";
                    //fsbs crop width in half,set the display aspect,crop out any black bars we may have made the scale width to 600.
                    break;

                case Video3DFormat.HalfTopAndBottom:
                    vf = "crop=iw:ih/2:0:0,scale=(iw*2):ih),setdar=dar=a,crop=min(iw\\,ih*dar):min(ih\\,iw/dar):(iw-min(iw\\,iw*sar))/2:(ih - min (ih\\,ih/sar))/2,setsar=sar=1,scale=600:trunc(600/dar/2)*2";
                    //htab crop heigh in half,scale to correct size, set the display aspect,crop out any black bars we may have made the scale width to 600
                    break;

                case Video3DFormat.FullTopAndBottom:
                    vf = "crop=iw:ih/2:0:0,setdar=dar=a,crop=min(iw\\,ih*dar):min(ih\\,iw/dar):(iw-min(iw\\,iw*sar))/2:(ih - min (ih\\,ih/sar))/2,setsar=sar=1,scale=600:trunc(600/dar/2)*2";
                    // ftab crop heigt in half, set the display aspect,crop out any black bars we may have made the scale width to 600
                    break;
                }
            }

            // TODO: Output in webp for smaller sizes
            // -f image2 -f webp

            // Use ffmpeg to sample 100 (we can drop this if required using thumbnail=50 for 50 frames) frames and pick the best thumbnail. Have a fall back just in case.
            var args = useIFrame ? string.Format("-i {0} -threads 1 -v quiet -vframes 1 -vf \"{2},thumbnail=30\" -f image2 \"{1}\"", inputPath, "-", vf) :
                       string.Format("-i {0} -threads 1 -v quiet -vframes 1 -vf \"{2}\" -f image2 \"{1}\"", inputPath, "-", vf);

            var probeSize = GetProbeSizeArgument(new[] { inputPath }, protocol);

            if (!string.IsNullOrEmpty(probeSize))
            {
                args = probeSize + " " + args;
            }

            if (offset.HasValue)
            {
                args = string.Format("-ss {0} ", GetTimeParameter(offset.Value)) + args;
            }

            var process = new Process
            {
                StartInfo = new ProcessStartInfo
                {
                    CreateNoWindow         = true,
                    UseShellExecute        = false,
                    FileName               = FFMpegPath,
                    Arguments              = args,
                    WindowStyle            = ProcessWindowStyle.Hidden,
                    ErrorDialog            = false,
                    RedirectStandardOutput = true,
                    RedirectStandardError  = true,
                    RedirectStandardInput  = true
                }
            };

            _logger.Debug("{0} {1}", process.StartInfo.FileName, process.StartInfo.Arguments);

            await resourcePool.WaitAsync(cancellationToken).ConfigureAwait(false);

            using (var processWrapper = new ProcessWrapper(process, this, _logger))
            {
                bool ranToCompletion;

                var memoryStream = new MemoryStream();

                try
                {
                    StartProcess(processWrapper);

#pragma warning disable 4014
                    // Important - don't await the log task or we won't be able to kill ffmpeg when the user stops playback
                    process.StandardOutput.BaseStream.CopyToAsync(memoryStream);
#pragma warning restore 4014

                    // MUST read both stdout and stderr asynchronously or a deadlock may occurr
                    process.BeginErrorReadLine();

                    ranToCompletion = process.WaitForExit(10000);

                    if (!ranToCompletion)
                    {
                        StopProcess(processWrapper, 1000, false);
                    }
                }
                finally
                {
                    resourcePool.Release();
                }

                var exitCode = ranToCompletion ? processWrapper.ExitCode ?? 0 : -1;

                if (exitCode == -1 || memoryStream.Length == 0)
                {
                    memoryStream.Dispose();

                    var msg = string.Format("ffmpeg image extraction failed for {0}", inputPath);

                    _logger.Error(msg);

                    throw new ApplicationException(msg);
                }

                memoryStream.Position = 0;
                return(memoryStream);
            }
        }
コード例 #54
0
ファイル: MediaEncoder.cs プロジェクト: kuebelkasten/Emby
        private void StopProcess(ProcessWrapper process, int waitTimeMs, bool enableForceKill)
        {
            try
            {
                _logger.Info("Killing ffmpeg process");

                try
                {
                    process.Process.StandardInput.WriteLine("q");
                }
                catch (Exception)
                {
                    _logger.Error("Error sending q command to process");
                }

                try
                {
                    if (process.Process.WaitForExit(waitTimeMs))
                    {
                        return;
                    }
                }
                catch (Exception ex)
                {
                    _logger.Error("Error in WaitForExit", ex);
                }

                if (enableForceKill)
                {
                    process.Process.Kill();
                }
            }
            catch (Exception ex)
            {
                _logger.ErrorException("Error killing process", ex);
            }
        }
コード例 #55
0
ファイル: ProcessHandlerSpecs.cs プロジェクト: pshomov/frog
 public void should_throw_exception_when_executable_not_found()
 {
     var pw = new ProcessWrapper("rubyyyyyy", "-e '$stderr.puts(\"fle\")'");
     try
     {
         pw.Execute();
         Assert.Fail("Should have thrown an exception");
     }
     catch (ApplicationNotFoundException)
     {
     }
 }
コード例 #56
0
        public void WhenInvokingWithWorkingDirShouldReturn0()
        {
            var processWrapper = new ProcessWrapper();

            Assert.Equal(0, processWrapper.Invoke("cmd", "/c dir", "C:\\").Item1);
        }
コード例 #57
0
        //FIXME: Check whether autogen.sh is required or not
        protected override BuildResult Build(IProgressMonitor monitor, SolutionEntityItem entry, ConfigurationSelector configuration)
        {
            Project project = entry as Project;

            if (project == null)
            {
                return(base.Build(monitor, entry, configuration));
            }

            MakefileData data = project.ExtendedProperties ["MonoDevelop.Autotools.MakefileInfo"] as MakefileData;

            if (data == null || !data.SupportsIntegration || String.IsNullOrEmpty(data.BuildTargetName))
            {
                return(base.Build(monitor, entry, configuration));
            }

            //FIXME: Gen autofoo ? autoreconf?

            string output   = String.Empty;
            int    exitCode = 0;

            monitor.BeginTask(GettextCatalog.GetString("Building {0}", project.Name), 1);
            try
            {
                string baseDir = project.BaseDirectory;
                string args    = string.Format("-j {0} {1}", data.ParallelProcesses, data.BuildTargetName);

                StringWriter  swOutput      = new StringWriter();
                LogTextWriter chainedOutput = new LogTextWriter();
                chainedOutput.ChainWriter(monitor.Log);
                chainedOutput.ChainWriter(swOutput);

                ProcessWrapper process = Runtime.ProcessService.StartProcess("make",
                                                                             args,
                                                                             baseDir,
                                                                             chainedOutput,
                                                                             chainedOutput,
                                                                             null);
                process.WaitForOutput();

                exitCode = process.ExitCode;
                output   = swOutput.ToString();
                chainedOutput.Close();
                swOutput.Close();
                monitor.Step(1);
            }
            catch (Exception e)
            {
                monitor.ReportError(GettextCatalog.GetString("Project could not be built: "), e);
                return(null);
            }
            finally
            {
                monitor.EndTask();
            }

            TempFileCollection tf = new TempFileCollection();
            Regex regexError      = data.GetErrorRegex(false);
            Regex regexWarning    = data.GetWarningRegex(false);

            BuildResult cr = ParseOutput(tf, output, project.BaseDirectory, regexError, regexWarning);

            if (exitCode != 0 && cr.FailedBuildCount == 0)
            {
                cr.AddError(GettextCatalog.GetString("Build failed. See Build Output panel."));
            }

            return(cr);
        }
コード例 #58
0
        /// <summary>
        /// Gets the media info internal.
        /// </summary>
        /// <returns>Task{MediaInfoResult}.</returns>
        private async Task <MediaInfo> GetMediaInfoInternal(
            string inputPath,
            string primaryPath,
            MediaProtocol protocol,
            bool extractChapters,
            string probeSizeArgument,
            bool isAudio,
            VideoType?videoType,
            bool forceEnableLogging,
            CancellationToken cancellationToken)
        {
            var args = extractChapters
                ? "{0} -i {1} -threads {2} -v warning -print_format json -show_streams -show_chapters -show_format"
                : "{0} -i {1} -threads {2} -v warning -print_format json -show_streams -show_format";

            args = string.Format(CultureInfo.InvariantCulture, args, probeSizeArgument, inputPath, threads).Trim();

            var process = new Process
            {
                StartInfo = new ProcessStartInfo
                {
                    CreateNoWindow  = true,
                    UseShellExecute = false,

                    // Must consume both or ffmpeg may hang due to deadlocks. See comments below.
                    RedirectStandardOutput = true,

                    FileName  = _ffprobePath,
                    Arguments = args,

                    WindowStyle = ProcessWindowStyle.Hidden,
                    ErrorDialog = false,
                },
                EnableRaisingEvents = true
            };

            if (forceEnableLogging)
            {
                _logger.LogInformation("{ProcessFileName} {ProcessArgs}", process.StartInfo.FileName, process.StartInfo.Arguments);
            }
            else
            {
                _logger.LogDebug("{ProcessFileName} {ProcessArgs}", process.StartInfo.FileName, process.StartInfo.Arguments);
            }

            using (var processWrapper = new ProcessWrapper(process, this))
            {
                _logger.LogDebug("Starting ffprobe with args {Args}", args);
                StartProcess(processWrapper);

                InternalMediaInfoResult result;
                try
                {
                    result = await JsonSerializer.DeserializeAsync <InternalMediaInfoResult>(
                        process.StandardOutput.BaseStream,
                        _jsonSerializerOptions,
                        cancellationToken : cancellationToken).ConfigureAwait(false);
                }
                catch
                {
                    StopProcess(processWrapper, 100);

                    throw;
                }

                if (result == null || (result.Streams == null && result.Format == null))
                {
                    throw new FfmpegException("ffprobe failed - streams and format are both null.");
                }

                if (result.Streams != null)
                {
                    // Normalize aspect ratio if invalid
                    foreach (var stream in result.Streams)
                    {
                        if (string.Equals(stream.DisplayAspectRatio, "0:1", StringComparison.OrdinalIgnoreCase))
                        {
                            stream.DisplayAspectRatio = string.Empty;
                        }

                        if (string.Equals(stream.SampleAspectRatio, "0:1", StringComparison.OrdinalIgnoreCase))
                        {
                            stream.SampleAspectRatio = string.Empty;
                        }
                    }
                }

                return(new ProbeResultNormalizer(_logger, _localization).GetMediaInfo(result, videoType, isAudio, primaryPath, protocol));
            }
        }
コード例 #59
0
        CompilerError GetResourceId(FilePath outputFile, ExecutionEnvironment env, ProjectFile finfo, ref string fname, string resgen, out string resourceId, IProgressMonitor monitor)
        {
            resourceId = finfo.ResourceId;
            if (resourceId == null)
            {
                LoggingService.LogDebug(GettextCatalog.GetString("Error: Unable to build ResourceId for {0}.", fname));
                monitor.Log.WriteLine(GettextCatalog.GetString("Error: Unable to build ResourceId for {0}.", fname));

                return(new CompilerError(fname, 0, 0, String.Empty,
                                         GettextCatalog.GetString("Unable to build ResourceId for {0}.", fname)));
            }

            if (String.Compare(Path.GetExtension(fname), ".resx", true) != 0)
            {
                return(null);
            }

            if (!IsResgenRequired(fname, outputFile))
            {
                fname = File.Exists(outputFile) ? (string)outputFile : Path.ChangeExtension(fname, ".resources");
                return(null);
            }

            if (resgen == null)
            {
                string msg = GettextCatalog.GetString("Unable to find 'resgen' tool.");
                monitor.ReportError(msg, null);
                return(new CompilerError(fname, 0, 0, String.Empty, msg));
            }

            using (StringWriter sw = new StringWriter()) {
                LoggingService.LogDebug("Compiling resources\n{0}$ {1} /compile {2}", Path.GetDirectoryName(fname), resgen, fname);
                monitor.Log.WriteLine(GettextCatalog.GetString(
                                          "Compiling resource {0} with {1}", fname, resgen));
                ProcessWrapper pw = null;
                try {
                    ProcessStartInfo info = Runtime.ProcessService.CreateProcessStartInfo(
                        resgen, String.Format("/compile \"{0}\"", fname),
                        Path.GetDirectoryName(fname), false);

                    env.MergeTo(info);
                    if (PlatformID.Unix == Environment.OSVersion.Platform)
                    {
                        info.EnvironmentVariables ["MONO_IOMAP"] = "drive";
                    }

                    pw = Runtime.ProcessService.StartProcess(info, sw, sw, null);
                } catch (System.ComponentModel.Win32Exception ex) {
                    LoggingService.LogDebug(GettextCatalog.GetString(
                                                "Error while trying to invoke '{0}' to compile resource '{1}' :\n {2}", resgen, fname, ex.ToString()));
                    monitor.Log.WriteLine(GettextCatalog.GetString(
                                              "Error while trying to invoke '{0}' to compile resource '{1}' :\n {2}", resgen, fname, ex.Message));

                    return(new CompilerError(fname, 0, 0, String.Empty, ex.Message));
                }

                //FIXME: Handle exceptions
                pw.WaitForOutput();

                if (pw.ExitCode == 0)
                {
                    fname = Path.ChangeExtension(fname, ".resources");
                }
                else
                {
                    string output = sw.ToString();
                    LoggingService.LogDebug(GettextCatalog.GetString(
                                                "Unable to compile ({0}) {1} to .resources. \nReason: \n{2}\n",
                                                resgen, fname, output));
                    monitor.Log.WriteLine(GettextCatalog.GetString(
                                              "Unable to compile ({0}) {1} to .resources. \nReason: \n{2}\n",
                                              resgen, fname, output));

                    //Try to get the line/pos
                    int   line  = 0;
                    int   pos   = 0;
                    Match match = RegexErrorLinePos.Match(output);
                    if (match.Success && match.Groups.Count == 3)
                    {
                        try {
                            line = int.Parse(match.Groups [1].Value);
                        } catch (FormatException) {
                        }

                        try {
                            pos = int.Parse(match.Groups [2].Value);
                        } catch (FormatException) {
                        }
                    }

                    return(new CompilerError(fname, line, pos, String.Empty, output));
                }
            }

            return(null);
        }
コード例 #60
0
ファイル: MediaEncoder.cs プロジェクト: raven-au/Emby
        /// <summary>
        /// Gets the media info internal.
        /// </summary>
        /// <param name="inputPath">The input path.</param>
        /// <param name="primaryPath">The primary path.</param>
        /// <param name="protocol">The protocol.</param>
        /// <param name="extractChapters">if set to <c>true</c> [extract chapters].</param>
        /// <param name="extractKeyFrameInterval">if set to <c>true</c> [extract key frame interval].</param>
        /// <param name="probeSizeArgument">The probe size argument.</param>
        /// <param name="isAudio">if set to <c>true</c> [is audio].</param>
        /// <param name="videoType">Type of the video.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns>Task{MediaInfoResult}.</returns>
        /// <exception cref="System.ApplicationException"></exception>
        private async Task<Model.MediaInfo.MediaInfo> GetMediaInfoInternal(string inputPath,
            string primaryPath,
            MediaProtocol protocol,
            bool extractChapters,
            bool extractKeyFrameInterval,
            string probeSizeArgument,
            bool isAudio,
            VideoType videoType,
            CancellationToken cancellationToken)
        {
            var args = extractChapters
                ? "{0} -i {1} -threads 0 -v info -print_format json -show_streams -show_chapters -show_format"
                : "{0} -i {1} -threads 0 -v info -print_format json -show_streams -show_format";

            var process = new Process
            {
                StartInfo = new ProcessStartInfo
                {
                    CreateNoWindow = true,
                    UseShellExecute = false,

                    // Must consume both or ffmpeg may hang due to deadlocks. See comments below.   
                    RedirectStandardOutput = true,
                    RedirectStandardError = true,
                    RedirectStandardInput = true,
                    FileName = FFProbePath,
                    Arguments = string.Format(args,
                    probeSizeArgument, inputPath).Trim(),

                    WindowStyle = ProcessWindowStyle.Hidden,
                    ErrorDialog = false
                },

                EnableRaisingEvents = true
            };

            _logger.Debug("{0} {1}", process.StartInfo.FileName, process.StartInfo.Arguments);

            await _ffProbeResourcePool.WaitAsync(cancellationToken).ConfigureAwait(false);

            using (var processWrapper = new ProcessWrapper(process, this, _logger))
            {
                try
                {
                    StartProcess(processWrapper);
                }
                catch (Exception ex)
                {
                    _ffProbeResourcePool.Release();

                    _logger.ErrorException("Error starting ffprobe", ex);

                    throw;
                }

                try
                {
                    process.BeginErrorReadLine();

                    var result = _jsonSerializer.DeserializeFromStream<InternalMediaInfoResult>(process.StandardOutput.BaseStream);

                    if (result != null)
                    {
                        if (result.streams != null)
                        {
                            // Normalize aspect ratio if invalid
                            foreach (var stream in result.streams)
                            {
                                if (string.Equals(stream.display_aspect_ratio, "0:1", StringComparison.OrdinalIgnoreCase))
                                {
                                    stream.display_aspect_ratio = string.Empty;
                                }
                                if (string.Equals(stream.sample_aspect_ratio, "0:1", StringComparison.OrdinalIgnoreCase))
                                {
                                    stream.sample_aspect_ratio = string.Empty;
                                }
                            }
                        }

                        var mediaInfo = new ProbeResultNormalizer(_logger, FileSystem).GetMediaInfo(result, videoType, isAudio, primaryPath, protocol);

                        if (extractKeyFrameInterval && mediaInfo.RunTimeTicks.HasValue)
                        {
                            if (ConfigurationManager.Configuration.EnableVideoFrameAnalysis && mediaInfo.Size.HasValue && mediaInfo.Size.Value <= ConfigurationManager.Configuration.VideoFrameAnalysisLimitBytes)
                            {
                                foreach (var stream in mediaInfo.MediaStreams)
                                {
                                    if (stream.Type == MediaStreamType.Video &&
                                        string.Equals(stream.Codec, "h264", StringComparison.OrdinalIgnoreCase) &&
                                        !stream.IsInterlaced &&
                                        !(stream.IsAnamorphic ?? false))
                                    {
                                        try
                                        {
                                            stream.KeyFrames = await GetKeyFrames(inputPath, stream.Index, cancellationToken).ConfigureAwait(false);
                                        }
                                        catch (OperationCanceledException)
                                        {

                                        }
                                        catch (Exception ex)
                                        {
                                            _logger.ErrorException("Error getting key frame interval", ex);
                                        }
                                    }
                                }
                            }
                        }

                        return mediaInfo;
                    }
                }
                catch
                {
                    StopProcess(processWrapper, 100, true);

                    throw;
                }
                finally
                {
                    _ffProbeResourcePool.Release();
                }
            }

            throw new ApplicationException(string.Format("FFProbe failed for {0}", inputPath));
        }