From ee2f911a2b85792c2bfc867d42b7d58b847de6ea Mon Sep 17 00:00:00 2001 From: Mark Monteiro Date: Fri, 27 Mar 2020 00:10:16 +0100 Subject: [PATCH 01/14] Remove unnecessary CommonProcess abstraction --- .../ApplicationHost.cs | 11 +- .../Diagnostics/CommonProcess.cs | 152 ------------------ .../Diagnostics/ProcessFactory.cs | 5 +- .../LiveTv/EmbyTV/EmbyTV.cs | 18 ++- .../LiveTv/EmbyTV/EncodedRecorder.cs | 23 ++- .../Extensions/ProcessExtensions.cs | 66 ++++++++ .../Encoder/MediaEncoder.cs | 31 ++-- .../Subtitles/SubtitleEncoder.cs | 13 +- MediaBrowser.Model/Diagnostics/IProcess.cs | 23 --- .../Diagnostics/IProcessFactory.cs | 19 +-- 10 files changed, 120 insertions(+), 241 deletions(-) delete mode 100644 Emby.Server.Implementations/Diagnostics/CommonProcess.cs create mode 100644 MediaBrowser.Common/Extensions/ProcessExtensions.cs delete mode 100644 MediaBrowser.Model/Diagnostics/IProcess.cs diff --git a/Emby.Server.Implementations/ApplicationHost.cs b/Emby.Server.Implementations/ApplicationHost.cs index d6a572818a..bc637b02f1 100644 --- a/Emby.Server.Implementations/ApplicationHost.cs +++ b/Emby.Server.Implementations/ApplicationHost.cs @@ -1727,15 +1727,15 @@ namespace Emby.Server.Implementations throw new NotSupportedException(); } - var process = ProcessFactory.Create(new ProcessOptions + var process = ProcessFactory.Create(new ProcessStartInfo { FileName = url, - EnableRaisingEvents = true, UseShellExecute = true, ErrorDialog = false }); - process.Exited += ProcessExited; + process.EnableRaisingEvents = true; + process.Exited += (sender, args) => ((Process)sender).Dispose(); ; try { @@ -1748,11 +1748,6 @@ namespace Emby.Server.Implementations } } - private static void ProcessExited(object sender, EventArgs e) - { - ((IProcess)sender).Dispose(); - } - public virtual void EnableLoopback(string appName) { } diff --git a/Emby.Server.Implementations/Diagnostics/CommonProcess.cs b/Emby.Server.Implementations/Diagnostics/CommonProcess.cs deleted file mode 100644 index bfa49ac5ff..0000000000 --- a/Emby.Server.Implementations/Diagnostics/CommonProcess.cs +++ /dev/null @@ -1,152 +0,0 @@ -#pragma warning disable CS1591 - -using System; -using System.Diagnostics; -using System.IO; -using System.Threading; -using System.Threading.Tasks; -using MediaBrowser.Model.Diagnostics; - -namespace Emby.Server.Implementations.Diagnostics -{ - public class CommonProcess : IProcess - { - private readonly Process _process; - - private bool _disposed = false; - private bool _hasExited; - - public CommonProcess(ProcessOptions options) - { - StartInfo = options; - - var startInfo = new ProcessStartInfo - { - Arguments = options.Arguments, - FileName = options.FileName, - WorkingDirectory = options.WorkingDirectory, - UseShellExecute = options.UseShellExecute, - CreateNoWindow = options.CreateNoWindow, - RedirectStandardError = options.RedirectStandardError, - RedirectStandardInput = options.RedirectStandardInput, - RedirectStandardOutput = options.RedirectStandardOutput, - ErrorDialog = options.ErrorDialog - }; - - - if (options.IsHidden) - { - startInfo.WindowStyle = ProcessWindowStyle.Hidden; - } - - _process = new Process - { - StartInfo = startInfo - }; - - if (options.EnableRaisingEvents) - { - _process.EnableRaisingEvents = true; - _process.Exited += OnProcessExited; - } - } - - public event EventHandler Exited; - - public ProcessOptions StartInfo { get; } - - public StreamWriter StandardInput => _process.StandardInput; - - public StreamReader StandardError => _process.StandardError; - - public StreamReader StandardOutput => _process.StandardOutput; - - public int ExitCode => _process.ExitCode; - - private bool HasExited - { - get - { - if (_hasExited) - { - return true; - } - - try - { - _hasExited = _process.HasExited; - } - catch (InvalidOperationException) - { - _hasExited = true; - } - - return _hasExited; - } - } - - public void Start() - { - _process.Start(); - } - - public void Kill() - { - _process.Kill(); - } - - public bool WaitForExit(int timeMs) - { - return _process.WaitForExit(timeMs); - } - - public Task WaitForExitAsync(int timeMs) - { - // Note: For this function to work correctly, the option EnableRisingEvents needs to be set to true. - - if (HasExited) - { - return Task.FromResult(true); - } - - timeMs = Math.Max(0, timeMs); - - var tcs = new TaskCompletionSource(); - - var cancellationToken = new CancellationTokenSource(timeMs).Token; - - _process.Exited += (sender, args) => tcs.TrySetResult(true); - - cancellationToken.Register(() => tcs.TrySetResult(HasExited)); - - return tcs.Task; - } - - public void Dispose() - { - Dispose(true); - GC.SuppressFinalize(this); - } - - protected virtual void Dispose(bool disposing) - { - if (_disposed) - { - return; - } - - if (disposing) - { - _process?.Dispose(); - } - - _disposed = true; - } - - private void OnProcessExited(object sender, EventArgs e) - { - _hasExited = true; - Exited?.Invoke(this, e); - } - } -} diff --git a/Emby.Server.Implementations/Diagnostics/ProcessFactory.cs b/Emby.Server.Implementations/Diagnostics/ProcessFactory.cs index 02ad3c1a89..00172e17a6 100644 --- a/Emby.Server.Implementations/Diagnostics/ProcessFactory.cs +++ b/Emby.Server.Implementations/Diagnostics/ProcessFactory.cs @@ -1,14 +1,15 @@ #pragma warning disable CS1591 +using System.Diagnostics; using MediaBrowser.Model.Diagnostics; namespace Emby.Server.Implementations.Diagnostics { public class ProcessFactory : IProcessFactory { - public IProcess Create(ProcessOptions options) + public Process Create(ProcessStartInfo startInfo) { - return new CommonProcess(options); + return new Process { StartInfo = startInfo }; } } } diff --git a/Emby.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs b/Emby.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs index 139aa19a4b..0f54022c8e 100644 --- a/Emby.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs +++ b/Emby.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs @@ -3,6 +3,7 @@ using System; using System.Collections.Concurrent; using System.Collections.Generic; +using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; @@ -1683,19 +1684,19 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV try { - var process = _processFactory.Create(new ProcessOptions + var process = _processFactory.Create(new ProcessStartInfo { Arguments = GetPostProcessArguments(path, options.RecordingPostProcessorArguments), CreateNoWindow = true, - EnableRaisingEvents = true, ErrorDialog = false, FileName = options.RecordingPostProcessor, - IsHidden = true, + WindowStyle = ProcessWindowStyle.Hidden, UseShellExecute = false }); _logger.LogInformation("Running recording post processor {0} {1}", process.StartInfo.FileName, process.StartInfo.Arguments); + process.EnableRaisingEvents = true; process.Exited += Process_Exited; process.Start(); } @@ -1712,11 +1713,14 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV private void Process_Exited(object sender, EventArgs e) { - using (var process = (IProcess)sender) + try { - _logger.LogInformation("Recording post-processing script completed with exit code {ExitCode}", process.ExitCode); - - process.Dispose(); + var exitCode = ((Process)sender).ExitCode; + _logger.LogInformation("Recording post-processing script completed with exit code {ExitCode}", exitCode); + } + finally + { + ((Process)sender).Dispose(); } } diff --git a/Emby.Server.Implementations/LiveTv/EmbyTV/EncodedRecorder.cs b/Emby.Server.Implementations/LiveTv/EmbyTV/EncodedRecorder.cs index 8590c56dfd..3591384de1 100644 --- a/Emby.Server.Implementations/LiveTv/EmbyTV/EncodedRecorder.cs +++ b/Emby.Server.Implementations/LiveTv/EmbyTV/EncodedRecorder.cs @@ -3,6 +3,7 @@ using System; using System.Collections.Generic; +using System.Diagnostics; using System.Globalization; using System.IO; using System.Text; @@ -30,7 +31,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV private bool _hasExited; private Stream _logFileStream; private string _targetPath; - private IProcess _process; + private Process _process; private readonly IProcessFactory _processFactory; private readonly IJsonSerializer _json; private readonly TaskCompletionSource _taskCompletionSource = new TaskCompletionSource(); @@ -80,7 +81,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV _targetPath = targetFile; Directory.CreateDirectory(Path.GetDirectoryName(targetFile)); - var process = _processFactory.Create(new ProcessOptions + _process = _processFactory.Create(new ProcessStartInfo { CreateNoWindow = true, UseShellExecute = false, @@ -91,14 +92,11 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV FileName = _mediaEncoder.EncoderPath, Arguments = GetCommandLineArgs(mediaSource, inputFile, targetFile, duration), - IsHidden = true, - ErrorDialog = false, - EnableRaisingEvents = true + WindowStyle = ProcessWindowStyle.Hidden, + ErrorDialog = false }); - _process = process; - - var commandLineLogMessage = process.StartInfo.FileName + " " + process.StartInfo.Arguments; + var commandLineLogMessage = _process.StartInfo.FileName + " " + _process.StartInfo.Arguments; _logger.LogInformation(commandLineLogMessage); var logFilePath = Path.Combine(_appPaths.LogDirectoryPath, "record-transcode-" + Guid.NewGuid() + ".txt"); @@ -110,16 +108,17 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV var commandLineLogMessageBytes = Encoding.UTF8.GetBytes(_json.SerializeToString(mediaSource) + Environment.NewLine + Environment.NewLine + commandLineLogMessage + Environment.NewLine + Environment.NewLine); _logFileStream.Write(commandLineLogMessageBytes, 0, commandLineLogMessageBytes.Length); - process.Exited += (sender, args) => OnFfMpegProcessExited(process, inputFile); + _process.EnableRaisingEvents = true; + _process.Exited += (sender, args) => OnFfMpegProcessExited(_process, inputFile); - process.Start(); + _process.Start(); cancellationToken.Register(Stop); onStarted(); // Important - don't await the log task or we won't be able to kill ffmpeg when the user stops playback - StartStreamingLog(process.StandardError.BaseStream, _logFileStream); + StartStreamingLog(_process.StandardError.BaseStream, _logFileStream); _logger.LogInformation("ffmpeg recording process started for {0}", _targetPath); @@ -293,7 +292,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV /// /// Processes the exited. /// - private void OnFfMpegProcessExited(IProcess process, string inputFile) + private void OnFfMpegProcessExited(Process process, string inputFile) { _hasExited = true; diff --git a/MediaBrowser.Common/Extensions/ProcessExtensions.cs b/MediaBrowser.Common/Extensions/ProcessExtensions.cs new file mode 100644 index 0000000000..9fa0efdff8 --- /dev/null +++ b/MediaBrowser.Common/Extensions/ProcessExtensions.cs @@ -0,0 +1,66 @@ +using System; +using System.Diagnostics; +using System.Threading; +using System.Threading.Tasks; + +namespace MediaBrowser.Common.Extensions +{ + /// + /// Extension methods for . + /// + public static class ProcessExtensions + { + /// + /// Gets a value indicating whether the associated process has been terminated using + /// . This is safe to call even if there is no operating system process + /// associated with the . + /// + /// The process to check the exit status for. + /// + /// True if the operating system process referenced by the component has + /// terminated, or if there is no associated operating system process; otherwise, false. + /// + public static bool HasExitedSafe(this Process process) + { + try + { + return process.HasExited; + } + catch (InvalidOperationException) + { + return true; + } + } + + /// + /// Asynchronously wait for the process to exit. + /// + /// The process to wait for. + /// A timeout, in milliseconds, after which to stop waiting for the task. + /// True if the task exited normally, false if the timeout elapsed before the process exited. + public static async Task WaitForExitAsync(this Process process, int timeMs) + { + if (!process.EnableRaisingEvents) + { + throw new InvalidOperationException("EnableRisingEvents must be enabled to async wait for a task to exit."); + } + + // Add an event handler for the process exit event + var tcs = new TaskCompletionSource(); + process.Exited += (sender, args) => tcs.TrySetResult(true); + + // Return immediately if the process has already exited + if (process.HasExitedSafe()) + { + return true; + } + + // Add an additional timeout then await + using (var cancelTokenSource = new CancellationTokenSource(Math.Max(0, timeMs))) + using (var cancelRegistration = cancelTokenSource.Token.Register(() => tcs.TrySetResult(process.HasExitedSafe()))) + { + return await tcs.Task.ConfigureAwait(false); + } + } + } +} diff --git a/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs b/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs index 4123f0203a..dbb7dea073 100644 --- a/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs +++ b/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs @@ -13,7 +13,6 @@ using MediaBrowser.Controller.Configuration; using MediaBrowser.Controller.MediaEncoding; using MediaBrowser.MediaEncoding.Probing; using MediaBrowser.Model.Configuration; -using MediaBrowser.Model.Diagnostics; using MediaBrowser.Model.Dlna; using MediaBrowser.Model.Entities; using MediaBrowser.Model.Globalization; @@ -22,6 +21,8 @@ using MediaBrowser.Model.MediaInfo; using MediaBrowser.Model.System; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Configuration; +using System.Diagnostics; +using MediaBrowser.Model.Diagnostics; namespace MediaBrowser.MediaEncoding.Encoder { @@ -362,7 +363,7 @@ namespace MediaBrowser.MediaEncoding.Encoder : "{0} -i {1} -threads 0 -v warning -print_format json -show_streams -show_format"; args = string.Format(args, probeSizeArgument, inputPath).Trim(); - var process = _processFactory.Create(new ProcessOptions + var process = _processFactory.Create(new ProcessStartInfo { CreateNoWindow = true, UseShellExecute = false, @@ -374,10 +375,10 @@ namespace MediaBrowser.MediaEncoding.Encoder Arguments = args, - IsHidden = true, + WindowStyle = ProcessWindowStyle.Hidden, ErrorDialog = false, - EnableRaisingEvents = true }); + process.EnableRaisingEvents = true; if (forceEnableLogging) { @@ -571,16 +572,16 @@ namespace MediaBrowser.MediaEncoding.Encoder } } - var process = _processFactory.Create(new ProcessOptions + var process = _processFactory.Create(new ProcessStartInfo { CreateNoWindow = true, UseShellExecute = false, FileName = _ffmpegPath, Arguments = args, - IsHidden = true, + WindowStyle = ProcessWindowStyle.Hidden, ErrorDialog = false, - EnableRaisingEvents = true }); + process.EnableRaisingEvents = true; _logger.LogDebug("{0} {1}", process.StartInfo.FileName, process.StartInfo.Arguments); @@ -700,16 +701,16 @@ namespace MediaBrowser.MediaEncoding.Encoder } } - var process = _processFactory.Create(new ProcessOptions + var process = _processFactory.Create(new ProcessStartInfo { CreateNoWindow = true, UseShellExecute = false, FileName = _ffmpegPath, Arguments = args, - IsHidden = true, - ErrorDialog = false, - EnableRaisingEvents = true + WindowStyle = ProcessWindowStyle.Hidden, + ErrorDialog = false }); + process.EnableRaisingEvents = true; _logger.LogInformation(process.StartInfo.FileName + " " + process.StartInfo.Arguments); @@ -949,14 +950,14 @@ namespace MediaBrowser.MediaEncoding.Encoder private bool _disposed = false; - public ProcessWrapper(IProcess process, MediaEncoder mediaEncoder) + public ProcessWrapper(Process process, MediaEncoder mediaEncoder) { Process = process; _mediaEncoder = mediaEncoder; Process.Exited += OnProcessExited; } - public IProcess Process { get; } + public Process Process { get; } public bool HasExited { get; private set; } @@ -964,7 +965,7 @@ namespace MediaBrowser.MediaEncoding.Encoder void OnProcessExited(object sender, EventArgs e) { - var process = (IProcess)sender; + var process = (Process)sender; HasExited = true; @@ -979,7 +980,7 @@ namespace MediaBrowser.MediaEncoding.Encoder DisposeProcess(process); } - private void DisposeProcess(IProcess process) + private void DisposeProcess(Process process) { lock (_mediaEncoder._runningProcessesLock) { diff --git a/MediaBrowser.MediaEncoding/Subtitles/SubtitleEncoder.cs b/MediaBrowser.MediaEncoding/Subtitles/SubtitleEncoder.cs index 6284e0fd9e..50ff834c62 100644 --- a/MediaBrowser.MediaEncoding/Subtitles/SubtitleEncoder.cs +++ b/MediaBrowser.MediaEncoding/Subtitles/SubtitleEncoder.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Concurrent; +using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; @@ -429,14 +430,13 @@ namespace MediaBrowser.MediaEncoding.Subtitles encodingParam = " -sub_charenc " + encodingParam; } - var process = _processFactory.Create(new ProcessOptions + var process = _processFactory.Create(new ProcessStartInfo { CreateNoWindow = true, UseShellExecute = false, FileName = _mediaEncoder.EncoderPath, Arguments = string.Format("{0} -i \"{1}\" -c:s srt \"{2}\"", encodingParam, inputPath, outputPath), - EnableRaisingEvents = true, - IsHidden = true, + WindowStyle = ProcessWindowStyle.Hidden, ErrorDialog = false }); @@ -453,6 +453,7 @@ namespace MediaBrowser.MediaEncoding.Subtitles throw; } + process.EnableRaisingEvents = true; var ranToCompletion = await process.WaitForExitAsync(300000).ConfigureAwait(false); if (!ranToCompletion) @@ -578,14 +579,13 @@ namespace MediaBrowser.MediaEncoding.Subtitles outputCodec, outputPath); - var process = _processFactory.Create(new ProcessOptions + var process = _processFactory.Create(new ProcessStartInfo { CreateNoWindow = true, UseShellExecute = false, - EnableRaisingEvents = true, FileName = _mediaEncoder.EncoderPath, Arguments = processArgs, - IsHidden = true, + WindowStyle = ProcessWindowStyle.Hidden, ErrorDialog = false }); @@ -602,6 +602,7 @@ namespace MediaBrowser.MediaEncoding.Subtitles throw; } + process.EnableRaisingEvents = true; var ranToCompletion = await process.WaitForExitAsync(300000).ConfigureAwait(false); if (!ranToCompletion) diff --git a/MediaBrowser.Model/Diagnostics/IProcess.cs b/MediaBrowser.Model/Diagnostics/IProcess.cs deleted file mode 100644 index 514d1e7379..0000000000 --- a/MediaBrowser.Model/Diagnostics/IProcess.cs +++ /dev/null @@ -1,23 +0,0 @@ -#pragma warning disable CS1591 - -using System; -using System.IO; -using System.Threading.Tasks; - -namespace MediaBrowser.Model.Diagnostics -{ - public interface IProcess : IDisposable - { - event EventHandler Exited; - - void Kill(); - bool WaitForExit(int timeMs); - Task WaitForExitAsync(int timeMs); - int ExitCode { get; } - void Start(); - StreamWriter StandardInput { get; } - StreamReader StandardError { get; } - StreamReader StandardOutput { get; } - ProcessOptions StartInfo { get; } - } -} diff --git a/MediaBrowser.Model/Diagnostics/IProcessFactory.cs b/MediaBrowser.Model/Diagnostics/IProcessFactory.cs index 57082acc57..d95227797c 100644 --- a/MediaBrowser.Model/Diagnostics/IProcessFactory.cs +++ b/MediaBrowser.Model/Diagnostics/IProcessFactory.cs @@ -1,24 +1,11 @@ #pragma warning disable CS1591 +using System.Diagnostics; + namespace MediaBrowser.Model.Diagnostics { public interface IProcessFactory { - IProcess Create(ProcessOptions options); - } - - public class ProcessOptions - { - public string FileName { get; set; } - public string Arguments { get; set; } - public string WorkingDirectory { get; set; } - public bool CreateNoWindow { get; set; } - public bool UseShellExecute { get; set; } - public bool EnableRaisingEvents { get; set; } - public bool ErrorDialog { get; set; } - public bool RedirectStandardError { get; set; } - public bool RedirectStandardInput { get; set; } - public bool RedirectStandardOutput { get; set; } - public bool IsHidden { get; set; } + Process Create(ProcessStartInfo options); } } From b947d98266371de7c9fd081e2038f53b3c67e859 Mon Sep 17 00:00:00 2001 From: Mark Monteiro Date: Fri, 27 Mar 2020 00:45:48 +0100 Subject: [PATCH 02/14] Delete unnecessary ProcessFactory abstraction --- .../ApplicationHost.cs | 20 +++------- .../Diagnostics/ProcessFactory.cs | 15 ------- .../LiveTv/EmbyTV/EmbyTV.cs | 14 +++---- .../LiveTv/EmbyTV/EncodedRecorder.cs | 40 +++++++++---------- .../Encoder/MediaEncoder.cs | 22 +++++----- .../Subtitles/SubtitleEncoder.cs | 18 ++++----- .../Diagnostics/IProcessFactory.cs | 11 ----- 7 files changed, 44 insertions(+), 96 deletions(-) delete mode 100644 Emby.Server.Implementations/Diagnostics/ProcessFactory.cs delete mode 100644 MediaBrowser.Model/Diagnostics/IProcessFactory.cs diff --git a/Emby.Server.Implementations/ApplicationHost.cs b/Emby.Server.Implementations/ApplicationHost.cs index bc637b02f1..f6c08bba8d 100644 --- a/Emby.Server.Implementations/ApplicationHost.cs +++ b/Emby.Server.Implementations/ApplicationHost.cs @@ -30,7 +30,6 @@ using Emby.Server.Implementations.Configuration; using Emby.Server.Implementations.Cryptography; using Emby.Server.Implementations.Data; using Emby.Server.Implementations.Devices; -using Emby.Server.Implementations.Diagnostics; using Emby.Server.Implementations.Dto; using Emby.Server.Implementations.HttpServer; using Emby.Server.Implementations.HttpServer.Security; @@ -85,7 +84,6 @@ using MediaBrowser.MediaEncoding.BdInfo; using MediaBrowser.Model.Activity; using MediaBrowser.Model.Configuration; using MediaBrowser.Model.Cryptography; -using MediaBrowser.Model.Diagnostics; using MediaBrowser.Model.Dlna; using MediaBrowser.Model.Events; using MediaBrowser.Model.Globalization; @@ -336,8 +334,6 @@ namespace Emby.Server.Implementations internal IImageEncoder ImageEncoder { get; private set; } - protected IProcessFactory ProcessFactory { get; private set; } - protected readonly IXmlSerializer XmlSerializer; protected ISocketFactory SocketFactory { get; private set; } @@ -685,9 +681,6 @@ namespace Emby.Server.Implementations serviceCollection.AddSingleton(XmlSerializer); - ProcessFactory = new ProcessFactory(); - serviceCollection.AddSingleton(ProcessFactory); - serviceCollection.AddSingleton(typeof(IStreamHelper), typeof(StreamHelper)); var cryptoProvider = new CryptographyProvider(); @@ -748,7 +741,6 @@ namespace Emby.Server.Implementations LoggerFactory.CreateLogger(), ServerConfigurationManager, FileSystemManager, - ProcessFactory, LocalizationManager, () => SubtitleEncoder, startupConfig, @@ -868,8 +860,7 @@ namespace Emby.Server.Implementations FileSystemManager, MediaEncoder, HttpClient, - MediaSourceManager, - ProcessFactory); + MediaSourceManager); serviceCollection.AddSingleton(SubtitleEncoder); serviceCollection.AddSingleton(typeof(IResourceFileManager), typeof(ResourceFileManager)); @@ -1727,15 +1718,14 @@ namespace Emby.Server.Implementations throw new NotSupportedException(); } - var process = ProcessFactory.Create(new ProcessStartInfo + var processStartInfo = new ProcessStartInfo { FileName = url, UseShellExecute = true, ErrorDialog = false - }); - - process.EnableRaisingEvents = true; - process.Exited += (sender, args) => ((Process)sender).Dispose(); ; + }; + var process = new Process { StartInfo = processStartInfo, EnableRaisingEvents = true }; + process.Exited += (sender, args) => ((Process)sender).Dispose(); try { diff --git a/Emby.Server.Implementations/Diagnostics/ProcessFactory.cs b/Emby.Server.Implementations/Diagnostics/ProcessFactory.cs deleted file mode 100644 index 00172e17a6..0000000000 --- a/Emby.Server.Implementations/Diagnostics/ProcessFactory.cs +++ /dev/null @@ -1,15 +0,0 @@ -#pragma warning disable CS1591 - -using System.Diagnostics; -using MediaBrowser.Model.Diagnostics; - -namespace Emby.Server.Implementations.Diagnostics -{ - public class ProcessFactory : IProcessFactory - { - public Process Create(ProcessStartInfo startInfo) - { - return new Process { StartInfo = startInfo }; - } - } -} diff --git a/Emby.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs b/Emby.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs index 0f54022c8e..e2ca0986bb 100644 --- a/Emby.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs +++ b/Emby.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs @@ -26,7 +26,6 @@ using MediaBrowser.Controller.LiveTv; using MediaBrowser.Controller.MediaEncoding; using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Configuration; -using MediaBrowser.Model.Diagnostics; using MediaBrowser.Model.Dto; using MediaBrowser.Model.Entities; using MediaBrowser.Model.Events; @@ -62,7 +61,6 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV private readonly ILibraryManager _libraryManager; private readonly IProviderManager _providerManager; private readonly IMediaEncoder _mediaEncoder; - private readonly IProcessFactory _processFactory; private readonly IMediaSourceManager _mediaSourceManager; private readonly IStreamHelper _streamHelper; @@ -89,8 +87,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV ILibraryManager libraryManager, ILibraryMonitor libraryMonitor, IProviderManager providerManager, - IMediaEncoder mediaEncoder, - IProcessFactory processFactory) + IMediaEncoder mediaEncoder) { Current = this; @@ -103,7 +100,6 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV _libraryMonitor = libraryMonitor; _providerManager = providerManager; _mediaEncoder = mediaEncoder; - _processFactory = processFactory; _liveTvManager = (LiveTvManager)liveTvManager; _jsonSerializer = jsonSerializer; _mediaSourceManager = mediaSourceManager; @@ -1663,7 +1659,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV { if (mediaSource.RequiresLooping || !(mediaSource.Container ?? string.Empty).EndsWith("ts", StringComparison.OrdinalIgnoreCase) || (mediaSource.Protocol != MediaProtocol.File && mediaSource.Protocol != MediaProtocol.Http)) { - return new EncodedRecorder(_logger, _mediaEncoder, _config.ApplicationPaths, _jsonSerializer, _processFactory, _config); + return new EncodedRecorder(_logger, _mediaEncoder, _config.ApplicationPaths, _jsonSerializer, _config); } return new DirectRecorder(_logger, _httpClient, _streamHelper); @@ -1684,7 +1680,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV try { - var process = _processFactory.Create(new ProcessStartInfo + var processStartInfo = new ProcessStartInfo { Arguments = GetPostProcessArguments(path, options.RecordingPostProcessorArguments), CreateNoWindow = true, @@ -1692,11 +1688,11 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV FileName = options.RecordingPostProcessor, WindowStyle = ProcessWindowStyle.Hidden, UseShellExecute = false - }); + }; + var process = new Process { StartInfo = processStartInfo, EnableRaisingEvents = true }; _logger.LogInformation("Running recording post processor {0} {1}", process.StartInfo.FileName, process.StartInfo.Arguments); - process.EnableRaisingEvents = true; process.Exited += Process_Exited; process.Start(); } diff --git a/Emby.Server.Implementations/LiveTv/EmbyTV/EncodedRecorder.cs b/Emby.Server.Implementations/LiveTv/EmbyTV/EncodedRecorder.cs index 3591384de1..55d1f810be 100644 --- a/Emby.Server.Implementations/LiveTv/EmbyTV/EncodedRecorder.cs +++ b/Emby.Server.Implementations/LiveTv/EmbyTV/EncodedRecorder.cs @@ -15,7 +15,6 @@ using MediaBrowser.Controller.Configuration; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.MediaEncoding; using MediaBrowser.Model.Configuration; -using MediaBrowser.Model.Diagnostics; using MediaBrowser.Model.Dto; using MediaBrowser.Model.IO; using MediaBrowser.Model.Serialization; @@ -32,7 +31,6 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV private Stream _logFileStream; private string _targetPath; private Process _process; - private readonly IProcessFactory _processFactory; private readonly IJsonSerializer _json; private readonly TaskCompletionSource _taskCompletionSource = new TaskCompletionSource(); private readonly IServerConfigurationManager _config; @@ -42,14 +40,12 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV IMediaEncoder mediaEncoder, IServerApplicationPaths appPaths, IJsonSerializer json, - IProcessFactory processFactory, IServerConfigurationManager config) { _logger = logger; _mediaEncoder = mediaEncoder; _appPaths = appPaths; _json = json; - _processFactory = processFactory; _config = config; } @@ -81,7 +77,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV _targetPath = targetFile; Directory.CreateDirectory(Path.GetDirectoryName(targetFile)); - _process = _processFactory.Create(new ProcessStartInfo + var processStartInfo = new ProcessStartInfo { CreateNoWindow = true, UseShellExecute = false, @@ -94,7 +90,8 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV WindowStyle = ProcessWindowStyle.Hidden, ErrorDialog = false - }); + }; + _process = new Process { StartInfo = processStartInfo, EnableRaisingEvents = true }; var commandLineLogMessage = _process.StartInfo.FileName + " " + _process.StartInfo.Arguments; _logger.LogInformation(commandLineLogMessage); @@ -108,7 +105,6 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV var commandLineLogMessageBytes = Encoding.UTF8.GetBytes(_json.SerializeToString(mediaSource) + Environment.NewLine + Environment.NewLine + commandLineLogMessage + Environment.NewLine + Environment.NewLine); _logFileStream.Write(commandLineLogMessageBytes, 0, commandLineLogMessageBytes.Length); - _process.EnableRaisingEvents = true; _process.Exited += (sender, args) => OnFfMpegProcessExited(_process, inputFile); _process.Start(); @@ -297,24 +293,24 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV _hasExited = true; _logFileStream?.Dispose(); - _logFileStream = null; + _logFileStream = null; - var exitCode = process.ExitCode; + var exitCode = process.ExitCode; - _logger.LogInformation("FFMpeg recording exited with code {ExitCode} for {Path}", exitCode, _targetPath); + _logger.LogInformation("FFMpeg recording exited with code {ExitCode} for {Path}", exitCode, _targetPath); - if (exitCode == 0) - { - _taskCompletionSource.TrySetResult(true); - } - else - { - _taskCompletionSource.TrySetException( - new Exception( - string.Format( - CultureInfo.InvariantCulture, - "Recording for {0} failed. Exit code {1}", - _targetPath, + if (exitCode == 0) + { + _taskCompletionSource.TrySetResult(true); + } + else + { + _taskCompletionSource.TrySetException( + new Exception( + string.Format( + CultureInfo.InvariantCulture, + "Recording for {0} failed. Exit code {1}", + _targetPath, exitCode))); } } diff --git a/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs b/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs index dbb7dea073..62a6c69ca5 100644 --- a/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs +++ b/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs @@ -22,7 +22,6 @@ using MediaBrowser.Model.System; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Configuration; using System.Diagnostics; -using MediaBrowser.Model.Diagnostics; namespace MediaBrowser.MediaEncoding.Encoder { @@ -39,7 +38,6 @@ namespace MediaBrowser.MediaEncoding.Encoder private readonly ILogger _logger; private readonly IServerConfigurationManager _configurationManager; private readonly IFileSystem _fileSystem; - private readonly IProcessFactory _processFactory; private readonly ILocalizationManager _localization; private readonly Func _subtitleEncoder; private readonly IConfiguration _configuration; @@ -59,7 +57,6 @@ namespace MediaBrowser.MediaEncoding.Encoder ILogger logger, IServerConfigurationManager configurationManager, IFileSystem fileSystem, - IProcessFactory processFactory, ILocalizationManager localization, Func subtitleEncoder, IConfiguration configuration, @@ -68,7 +65,6 @@ namespace MediaBrowser.MediaEncoding.Encoder _logger = logger; _configurationManager = configurationManager; _fileSystem = fileSystem; - _processFactory = processFactory; _localization = localization; _startupOptionFFmpegPath = startupOptionsFFmpegPath; _subtitleEncoder = subtitleEncoder; @@ -363,7 +359,7 @@ namespace MediaBrowser.MediaEncoding.Encoder : "{0} -i {1} -threads 0 -v warning -print_format json -show_streams -show_format"; args = string.Format(args, probeSizeArgument, inputPath).Trim(); - var process = _processFactory.Create(new ProcessStartInfo + var processStartInfo = new ProcessStartInfo { CreateNoWindow = true, UseShellExecute = false, @@ -377,8 +373,8 @@ namespace MediaBrowser.MediaEncoding.Encoder WindowStyle = ProcessWindowStyle.Hidden, ErrorDialog = false, - }); - process.EnableRaisingEvents = true; + }; + var process = new Process { StartInfo = processStartInfo, EnableRaisingEvents = true }; if (forceEnableLogging) { @@ -572,7 +568,7 @@ namespace MediaBrowser.MediaEncoding.Encoder } } - var process = _processFactory.Create(new ProcessStartInfo + var processStartInfo = new ProcessStartInfo { CreateNoWindow = true, UseShellExecute = false, @@ -580,8 +576,8 @@ namespace MediaBrowser.MediaEncoding.Encoder Arguments = args, WindowStyle = ProcessWindowStyle.Hidden, ErrorDialog = false, - }); - process.EnableRaisingEvents = true; + }; + var process = new Process { StartInfo = processStartInfo, EnableRaisingEvents = true }; _logger.LogDebug("{0} {1}", process.StartInfo.FileName, process.StartInfo.Arguments); @@ -701,7 +697,7 @@ namespace MediaBrowser.MediaEncoding.Encoder } } - var process = _processFactory.Create(new ProcessStartInfo + var processStartInfo = new ProcessStartInfo { CreateNoWindow = true, UseShellExecute = false, @@ -709,8 +705,8 @@ namespace MediaBrowser.MediaEncoding.Encoder Arguments = args, WindowStyle = ProcessWindowStyle.Hidden, ErrorDialog = false - }); - process.EnableRaisingEvents = true; + }; + var process = new Process { StartInfo = processStartInfo, EnableRaisingEvents = true }; _logger.LogInformation(process.StartInfo.FileName + " " + process.StartInfo.Arguments); diff --git a/MediaBrowser.MediaEncoding/Subtitles/SubtitleEncoder.cs b/MediaBrowser.MediaEncoding/Subtitles/SubtitleEncoder.cs index 50ff834c62..e2be2ea57c 100644 --- a/MediaBrowser.MediaEncoding/Subtitles/SubtitleEncoder.cs +++ b/MediaBrowser.MediaEncoding/Subtitles/SubtitleEncoder.cs @@ -13,7 +13,6 @@ using MediaBrowser.Common.Net; using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.MediaEncoding; -using MediaBrowser.Model.Diagnostics; using MediaBrowser.Model.Dto; using MediaBrowser.Model.Entities; using MediaBrowser.Model.IO; @@ -32,7 +31,6 @@ namespace MediaBrowser.MediaEncoding.Subtitles private readonly IMediaEncoder _mediaEncoder; private readonly IHttpClient _httpClient; private readonly IMediaSourceManager _mediaSourceManager; - private readonly IProcessFactory _processFactory; public SubtitleEncoder( ILibraryManager libraryManager, @@ -41,8 +39,7 @@ namespace MediaBrowser.MediaEncoding.Subtitles IFileSystem fileSystem, IMediaEncoder mediaEncoder, IHttpClient httpClient, - IMediaSourceManager mediaSourceManager, - IProcessFactory processFactory) + IMediaSourceManager mediaSourceManager) { _libraryManager = libraryManager; _logger = logger; @@ -51,7 +48,6 @@ namespace MediaBrowser.MediaEncoding.Subtitles _mediaEncoder = mediaEncoder; _httpClient = httpClient; _mediaSourceManager = mediaSourceManager; - _processFactory = processFactory; } private string SubtitleCachePath => Path.Combine(_appPaths.DataPath, "subtitles"); @@ -430,7 +426,7 @@ namespace MediaBrowser.MediaEncoding.Subtitles encodingParam = " -sub_charenc " + encodingParam; } - var process = _processFactory.Create(new ProcessStartInfo + var processStartInfo = new ProcessStartInfo { CreateNoWindow = true, UseShellExecute = false, @@ -438,7 +434,8 @@ namespace MediaBrowser.MediaEncoding.Subtitles Arguments = string.Format("{0} -i \"{1}\" -c:s srt \"{2}\"", encodingParam, inputPath, outputPath), WindowStyle = ProcessWindowStyle.Hidden, ErrorDialog = false - }); + }; + var process = new Process { StartInfo = processStartInfo, EnableRaisingEvents = true }; _logger.LogInformation("{0} {1}", process.StartInfo.FileName, process.StartInfo.Arguments); @@ -453,7 +450,6 @@ namespace MediaBrowser.MediaEncoding.Subtitles throw; } - process.EnableRaisingEvents = true; var ranToCompletion = await process.WaitForExitAsync(300000).ConfigureAwait(false); if (!ranToCompletion) @@ -579,7 +575,7 @@ namespace MediaBrowser.MediaEncoding.Subtitles outputCodec, outputPath); - var process = _processFactory.Create(new ProcessStartInfo + var processStartInfo = new ProcessStartInfo { CreateNoWindow = true, UseShellExecute = false, @@ -587,7 +583,8 @@ namespace MediaBrowser.MediaEncoding.Subtitles Arguments = processArgs, WindowStyle = ProcessWindowStyle.Hidden, ErrorDialog = false - }); + }; + var process = new Process { StartInfo = processStartInfo, EnableRaisingEvents = true }; _logger.LogInformation("{File} {Arguments}", process.StartInfo.FileName, process.StartInfo.Arguments); @@ -602,7 +599,6 @@ namespace MediaBrowser.MediaEncoding.Subtitles throw; } - process.EnableRaisingEvents = true; var ranToCompletion = await process.WaitForExitAsync(300000).ConfigureAwait(false); if (!ranToCompletion) diff --git a/MediaBrowser.Model/Diagnostics/IProcessFactory.cs b/MediaBrowser.Model/Diagnostics/IProcessFactory.cs deleted file mode 100644 index d95227797c..0000000000 --- a/MediaBrowser.Model/Diagnostics/IProcessFactory.cs +++ /dev/null @@ -1,11 +0,0 @@ -#pragma warning disable CS1591 - -using System.Diagnostics; - -namespace MediaBrowser.Model.Diagnostics -{ - public interface IProcessFactory - { - Process Create(ProcessStartInfo options); - } -} From 7447ea89609fe79be3c5d282a23fc6d7d2bddd66 Mon Sep 17 00:00:00 2001 From: Mark Monteiro Date: Fri, 27 Mar 2020 00:49:22 +0100 Subject: [PATCH 03/14] Make sure Process objects are all disposed correctly --- .../LiveTv/EmbyTV/EncodedRecorder.cs | 13 ++++++++++--- .../Subtitles/SubtitleEncoder.cs | 6 ++---- 2 files changed, 12 insertions(+), 7 deletions(-) diff --git a/Emby.Server.Implementations/LiveTv/EmbyTV/EncodedRecorder.cs b/Emby.Server.Implementations/LiveTv/EmbyTV/EncodedRecorder.cs index 55d1f810be..46fb47b7b9 100644 --- a/Emby.Server.Implementations/LiveTv/EmbyTV/EncodedRecorder.cs +++ b/Emby.Server.Implementations/LiveTv/EmbyTV/EncodedRecorder.cs @@ -290,9 +290,11 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV /// private void OnFfMpegProcessExited(Process process, string inputFile) { - _hasExited = true; + try + { + _hasExited = true; - _logFileStream?.Dispose(); + _logFileStream?.Dispose(); _logFileStream = null; var exitCode = process.ExitCode; @@ -311,7 +313,12 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV CultureInfo.InvariantCulture, "Recording for {0} failed. Exit code {1}", _targetPath, - exitCode))); + exitCode))); + } + } + finally + { + process.Dispose(); } } diff --git a/MediaBrowser.MediaEncoding/Subtitles/SubtitleEncoder.cs b/MediaBrowser.MediaEncoding/Subtitles/SubtitleEncoder.cs index e2be2ea57c..1736d79cf2 100644 --- a/MediaBrowser.MediaEncoding/Subtitles/SubtitleEncoder.cs +++ b/MediaBrowser.MediaEncoding/Subtitles/SubtitleEncoder.cs @@ -436,6 +436,7 @@ namespace MediaBrowser.MediaEncoding.Subtitles ErrorDialog = false }; var process = new Process { StartInfo = processStartInfo, EnableRaisingEvents = true }; + process.Exited += (sender, args) => ((Process)sender).Dispose(); _logger.LogInformation("{0} {1}", process.StartInfo.FileName, process.StartInfo.Arguments); @@ -468,8 +469,6 @@ namespace MediaBrowser.MediaEncoding.Subtitles var exitCode = ranToCompletion ? process.ExitCode : -1; - process.Dispose(); - var failed = false; if (exitCode == -1) @@ -585,6 +584,7 @@ namespace MediaBrowser.MediaEncoding.Subtitles ErrorDialog = false }; var process = new Process { StartInfo = processStartInfo, EnableRaisingEvents = true }; + process.Exited += (sender, args) => ((Process)sender).Dispose(); _logger.LogInformation("{File} {Arguments}", process.StartInfo.FileName, process.StartInfo.Arguments); @@ -617,8 +617,6 @@ namespace MediaBrowser.MediaEncoding.Subtitles var exitCode = ranToCompletion ? process.ExitCode : -1; - process.Dispose(); - var failed = false; if (exitCode == -1) From 97c36d11d4e52a8f33d48e382467b6c6068bb6ad Mon Sep 17 00:00:00 2001 From: Mark Monteiro Date: Fri, 27 Mar 2020 01:09:09 +0100 Subject: [PATCH 04/14] Use a TimeSpan instead of ms and support providing a custom CancellationToken --- .../Extensions/ProcessExtensions.cs | 23 +++++++++++++++---- .../Encoder/MediaEncoder.cs | 4 ++-- .../Subtitles/SubtitleEncoder.cs | 4 ++-- 3 files changed, 22 insertions(+), 9 deletions(-) diff --git a/MediaBrowser.Common/Extensions/ProcessExtensions.cs b/MediaBrowser.Common/Extensions/ProcessExtensions.cs index 9fa0efdff8..938ced1067 100644 --- a/MediaBrowser.Common/Extensions/ProcessExtensions.cs +++ b/MediaBrowser.Common/Extensions/ProcessExtensions.cs @@ -36,9 +36,23 @@ namespace MediaBrowser.Common.Extensions /// Asynchronously wait for the process to exit. /// /// The process to wait for. - /// A timeout, in milliseconds, after which to stop waiting for the task. + /// The duration to wait before cancelling waiting for the task. /// True if the task exited normally, false if the timeout elapsed before the process exited. - public static async Task WaitForExitAsync(this Process process, int timeMs) + public static async Task WaitForExitAsync(this Process process, TimeSpan timeout) + { + using (var cancelTokenSource = new CancellationTokenSource(timeout)) + { + return await WaitForExitAsync(process, cancelTokenSource.Token); + } + } + + /// + /// Asynchronously wait for the process to exit. + /// + /// The process to wait for. + /// A to observe while waiting for the process to exit. + /// True if the task exited normally, false if cancelled before the process exited. + public static async Task WaitForExitAsync(this Process process, CancellationToken cancelToken) { if (!process.EnableRaisingEvents) { @@ -55,9 +69,8 @@ namespace MediaBrowser.Common.Extensions return true; } - // Add an additional timeout then await - using (var cancelTokenSource = new CancellationTokenSource(Math.Max(0, timeMs))) - using (var cancelRegistration = cancelTokenSource.Token.Register(() => tcs.TrySetResult(process.HasExitedSafe()))) + // Register with the cancellation token then await + using (var cancelRegistration = cancelToken.Register(() => tcs.TrySetResult(process.HasExitedSafe()))) { return await tcs.Task.ConfigureAwait(false); } diff --git a/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs b/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs index 62a6c69ca5..855b1c7547 100644 --- a/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs +++ b/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs @@ -596,7 +596,7 @@ namespace MediaBrowser.MediaEncoding.Encoder timeoutMs = DefaultImageExtractionTimeout; } - ranToCompletion = await process.WaitForExitAsync(timeoutMs).ConfigureAwait(false); + ranToCompletion = await process.WaitForExitAsync(TimeSpan.FromMilliseconds(timeoutMs)).ConfigureAwait(false); if (!ranToCompletion) { @@ -729,7 +729,7 @@ namespace MediaBrowser.MediaEncoding.Encoder while (isResponsive) { - if (await process.WaitForExitAsync(30000).ConfigureAwait(false)) + if (await process.WaitForExitAsync(TimeSpan.FromSeconds(30)).ConfigureAwait(false)) { ranToCompletion = true; break; diff --git a/MediaBrowser.MediaEncoding/Subtitles/SubtitleEncoder.cs b/MediaBrowser.MediaEncoding/Subtitles/SubtitleEncoder.cs index 1736d79cf2..f1f0bfeb15 100644 --- a/MediaBrowser.MediaEncoding/Subtitles/SubtitleEncoder.cs +++ b/MediaBrowser.MediaEncoding/Subtitles/SubtitleEncoder.cs @@ -451,7 +451,7 @@ namespace MediaBrowser.MediaEncoding.Subtitles throw; } - var ranToCompletion = await process.WaitForExitAsync(300000).ConfigureAwait(false); + var ranToCompletion = await process.WaitForExitAsync(TimeSpan.FromMinutes(5)).ConfigureAwait(false); if (!ranToCompletion) { @@ -599,7 +599,7 @@ namespace MediaBrowser.MediaEncoding.Subtitles throw; } - var ranToCompletion = await process.WaitForExitAsync(300000).ConfigureAwait(false); + var ranToCompletion = await process.WaitForExitAsync(TimeSpan.FromMinutes(5)).ConfigureAwait(false); if (!ranToCompletion) { From 48bbcbb426b15724ccae05c71d418c8ce80cfb68 Mon Sep 17 00:00:00 2001 From: Mark Monteiro Date: Fri, 27 Mar 2020 01:09:25 +0100 Subject: [PATCH 05/14] Use WaitForExitAsync extension method in AttachmentExtractor --- .../Attachments/AttachmentExtractor.cs | 10 +++------- 1 file changed, 3 insertions(+), 7 deletions(-) diff --git a/MediaBrowser.MediaEncoding/Attachments/AttachmentExtractor.cs b/MediaBrowser.MediaEncoding/Attachments/AttachmentExtractor.cs index c530c9fd81..cb1d8d7bb8 100644 --- a/MediaBrowser.MediaEncoding/Attachments/AttachmentExtractor.cs +++ b/MediaBrowser.MediaEncoding/Attachments/AttachmentExtractor.cs @@ -166,19 +166,15 @@ namespace MediaBrowser.MediaEncoding.Attachments }; var process = new Process { - StartInfo = startInfo + StartInfo = startInfo, + EnableRaisingEvents = true }; _logger.LogInformation("{File} {Arguments}", process.StartInfo.FileName, process.StartInfo.Arguments); process.Start(); - var processTcs = new TaskCompletionSource(); - process.EnableRaisingEvents = true; - process.Exited += (sender, args) => processTcs.TrySetResult(true); - var unregister = cancellationToken.Register(() => processTcs.TrySetResult(process.HasExited)); - var ranToCompletion = await processTcs.Task.ConfigureAwait(false); - unregister.Dispose(); + var ranToCompletion = await process.WaitForExitAsync(cancellationToken); if (!ranToCompletion) { From 1c13be085fbc30ac6c5efa893f415fa0d06d557f Mon Sep 17 00:00:00 2001 From: Mark Monteiro Date: Fri, 27 Mar 2020 01:28:24 +0100 Subject: [PATCH 06/14] Make HasExitedSafe() private --- .../Extensions/ProcessExtensions.cs | 44 +++++++++---------- 1 file changed, 22 insertions(+), 22 deletions(-) diff --git a/MediaBrowser.Common/Extensions/ProcessExtensions.cs b/MediaBrowser.Common/Extensions/ProcessExtensions.cs index 938ced1067..525475ba5f 100644 --- a/MediaBrowser.Common/Extensions/ProcessExtensions.cs +++ b/MediaBrowser.Common/Extensions/ProcessExtensions.cs @@ -10,28 +10,6 @@ namespace MediaBrowser.Common.Extensions /// public static class ProcessExtensions { - /// - /// Gets a value indicating whether the associated process has been terminated using - /// . This is safe to call even if there is no operating system process - /// associated with the . - /// - /// The process to check the exit status for. - /// - /// True if the operating system process referenced by the component has - /// terminated, or if there is no associated operating system process; otherwise, false. - /// - public static bool HasExitedSafe(this Process process) - { - try - { - return process.HasExited; - } - catch (InvalidOperationException) - { - return true; - } - } - /// /// Asynchronously wait for the process to exit. /// @@ -75,5 +53,27 @@ namespace MediaBrowser.Common.Extensions return await tcs.Task.ConfigureAwait(false); } } + + /// + /// Gets a value indicating whether the associated process has been terminated using + /// . This is safe to call even if there is no operating system process + /// associated with the . + /// + /// The process to check the exit status for. + /// + /// True if the operating system process referenced by the component has + /// terminated, or if there is no associated operating system process; otherwise, false. + /// + private static bool HasExitedSafe(this Process process) + { + try + { + return process.HasExited; + } + catch (InvalidOperationException) + { + return true; + } + } } } From d705931e816db63b560efad51b8d0b79564aa260 Mon Sep 17 00:00:00 2001 From: Mark Monteiro Date: Fri, 27 Mar 2020 01:42:28 +0100 Subject: [PATCH 07/14] Dispose of process correctly in AttachmentExtractor --- .../Attachments/AttachmentExtractor.cs | 40 +++++++++---------- 1 file changed, 19 insertions(+), 21 deletions(-) diff --git a/MediaBrowser.MediaEncoding/Attachments/AttachmentExtractor.cs b/MediaBrowser.MediaEncoding/Attachments/AttachmentExtractor.cs index cb1d8d7bb8..d976347317 100644 --- a/MediaBrowser.MediaEncoding/Attachments/AttachmentExtractor.cs +++ b/MediaBrowser.MediaEncoding/Attachments/AttachmentExtractor.cs @@ -164,34 +164,32 @@ namespace MediaBrowser.MediaEncoding.Attachments WindowStyle = ProcessWindowStyle.Hidden, ErrorDialog = false }; - var process = new Process - { - StartInfo = startInfo, - EnableRaisingEvents = true - }; - _logger.LogInformation("{File} {Arguments}", process.StartInfo.FileName, process.StartInfo.Arguments); + int exitCode; - process.Start(); + using (var process = new Process { StartInfo = startInfo, EnableRaisingEvents = true }) + { + _logger.LogInformation("{File} {Arguments}", process.StartInfo.FileName, process.StartInfo.Arguments); - var ranToCompletion = await process.WaitForExitAsync(cancellationToken); + process.Start(); - if (!ranToCompletion) - { - try - { - _logger.LogWarning("Killing ffmpeg attachment extraction process"); - process.Kill(); - } - catch (Exception ex) + var ranToCompletion = await process.WaitForExitAsync(cancellationToken); + + if (!ranToCompletion) { - _logger.LogError(ex, "Error killing attachment extraction process"); + try + { + _logger.LogWarning("Killing ffmpeg attachment extraction process"); + process.Kill(); + } + catch (Exception ex) + { + _logger.LogError(ex, "Error killing attachment extraction process"); + } } - } - - var exitCode = ranToCompletion ? process.ExitCode : -1; - process.Dispose(); + exitCode = ranToCompletion ? process.ExitCode : -1; + } var failed = false; From 1f5caa46c53dde25ecf4482715333c049cb7e085 Mon Sep 17 00:00:00 2001 From: Mark Monteiro Date: Fri, 27 Mar 2020 01:53:08 +0100 Subject: [PATCH 08/14] Fix some more issues with disposing Process instances --- .../Encoder/MediaEncoder.cs | 8 +- .../Subtitles/SubtitleEncoder.cs | 94 ++++++++++--------- 2 files changed, 54 insertions(+), 48 deletions(-) diff --git a/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs b/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs index 855b1c7547..b3a45991e7 100644 --- a/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs +++ b/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs @@ -577,10 +577,10 @@ namespace MediaBrowser.MediaEncoding.Encoder WindowStyle = ProcessWindowStyle.Hidden, ErrorDialog = false, }; - var process = new Process { StartInfo = processStartInfo, EnableRaisingEvents = true }; - _logger.LogDebug("{0} {1}", process.StartInfo.FileName, process.StartInfo.Arguments); + _logger.LogDebug("{0} {1}", processStartInfo.FileName, processStartInfo.Arguments); + var process = new Process { StartInfo = processStartInfo, EnableRaisingEvents = true }; using (var processWrapper = new ProcessWrapper(process, this)) { bool ranToCompletion; @@ -706,14 +706,14 @@ namespace MediaBrowser.MediaEncoding.Encoder WindowStyle = ProcessWindowStyle.Hidden, ErrorDialog = false }; - var process = new Process { StartInfo = processStartInfo, EnableRaisingEvents = true }; - _logger.LogInformation(process.StartInfo.FileName + " " + process.StartInfo.Arguments); + _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 diff --git a/MediaBrowser.MediaEncoding/Subtitles/SubtitleEncoder.cs b/MediaBrowser.MediaEncoding/Subtitles/SubtitleEncoder.cs index f1f0bfeb15..a6982be5b6 100644 --- a/MediaBrowser.MediaEncoding/Subtitles/SubtitleEncoder.cs +++ b/MediaBrowser.MediaEncoding/Subtitles/SubtitleEncoder.cs @@ -435,39 +435,42 @@ namespace MediaBrowser.MediaEncoding.Subtitles WindowStyle = ProcessWindowStyle.Hidden, ErrorDialog = false }; - var process = new Process { StartInfo = processStartInfo, EnableRaisingEvents = true }; - process.Exited += (sender, args) => ((Process)sender).Dispose(); - _logger.LogInformation("{0} {1}", process.StartInfo.FileName, process.StartInfo.Arguments); + int exitCode; - try - { - process.Start(); - } - catch (Exception ex) + using (var process = new Process { StartInfo = processStartInfo, EnableRaisingEvents = true }) { - _logger.LogError(ex, "Error starting ffmpeg"); - - throw; - } + _logger.LogInformation("{0} {1}", process.StartInfo.FileName, process.StartInfo.Arguments); - var ranToCompletion = await process.WaitForExitAsync(TimeSpan.FromMinutes(5)).ConfigureAwait(false); - - if (!ranToCompletion) - { try { - _logger.LogInformation("Killing ffmpeg subtitle conversion process"); - - process.Kill(); + process.Start(); } catch (Exception ex) { - _logger.LogError(ex, "Error killing subtitle conversion process"); + _logger.LogError(ex, "Error starting ffmpeg"); + + throw; } - } - var exitCode = ranToCompletion ? process.ExitCode : -1; + var ranToCompletion = await process.WaitForExitAsync(TimeSpan.FromMinutes(5)).ConfigureAwait(false); + + if (!ranToCompletion) + { + try + { + _logger.LogInformation("Killing ffmpeg subtitle conversion process"); + + process.Kill(); + } + catch (Exception ex) + { + _logger.LogError(ex, "Error killing subtitle conversion process"); + } + } + + exitCode = ranToCompletion ? process.ExitCode : -1; + } var failed = false; @@ -583,39 +586,42 @@ namespace MediaBrowser.MediaEncoding.Subtitles WindowStyle = ProcessWindowStyle.Hidden, ErrorDialog = false }; - var process = new Process { StartInfo = processStartInfo, EnableRaisingEvents = true }; - process.Exited += (sender, args) => ((Process)sender).Dispose(); - _logger.LogInformation("{File} {Arguments}", process.StartInfo.FileName, process.StartInfo.Arguments); + int exitCode; - try - { - process.Start(); - } - catch (Exception ex) + using (var process = new Process { StartInfo = processStartInfo, EnableRaisingEvents = true }) { - _logger.LogError(ex, "Error starting ffmpeg"); - - throw; - } + _logger.LogInformation("{File} {Arguments}", process.StartInfo.FileName, process.StartInfo.Arguments); - var ranToCompletion = await process.WaitForExitAsync(TimeSpan.FromMinutes(5)).ConfigureAwait(false); - - if (!ranToCompletion) - { try { - _logger.LogWarning("Killing ffmpeg subtitle extraction process"); - - process.Kill(); + process.Start(); } catch (Exception ex) { - _logger.LogError(ex, "Error killing subtitle extraction process"); + _logger.LogError(ex, "Error starting ffmpeg"); + + throw; } - } - var exitCode = ranToCompletion ? process.ExitCode : -1; + var ranToCompletion = await process.WaitForExitAsync(TimeSpan.FromMinutes(5)).ConfigureAwait(false); + + if (!ranToCompletion) + { + try + { + _logger.LogWarning("Killing ffmpeg subtitle extraction process"); + + process.Kill(); + } + catch (Exception ex) + { + _logger.LogError(ex, "Error killing subtitle extraction process"); + } + } + + exitCode = ranToCompletion ? process.ExitCode : -1; + } var failed = false; From 0e195d2e49f4ee9979182603a356fdb7af8d98cf Mon Sep 17 00:00:00 2001 From: Mark Monteiro Date: Fri, 3 Apr 2020 20:20:55 -0400 Subject: [PATCH 09/14] Add missing call to ConfigureAwait() --- MediaBrowser.MediaEncoding/Attachments/AttachmentExtractor.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/MediaBrowser.MediaEncoding/Attachments/AttachmentExtractor.cs b/MediaBrowser.MediaEncoding/Attachments/AttachmentExtractor.cs index d976347317..48240d5b62 100644 --- a/MediaBrowser.MediaEncoding/Attachments/AttachmentExtractor.cs +++ b/MediaBrowser.MediaEncoding/Attachments/AttachmentExtractor.cs @@ -173,7 +173,7 @@ namespace MediaBrowser.MediaEncoding.Attachments process.Start(); - var ranToCompletion = await process.WaitForExitAsync(cancellationToken); + var ranToCompletion = await process.WaitForExitAsync(cancellationToken).ConfigureAwait(false); if (!ranToCompletion) { From 4efdc63337614762baff4a343c89464cf1b0963f Mon Sep 17 00:00:00 2001 From: Mark Monteiro Date: Fri, 3 Apr 2020 20:51:30 -0400 Subject: [PATCH 10/14] Add missing call to ConfigureAwait() --- MediaBrowser.Common/Extensions/ProcessExtensions.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/MediaBrowser.Common/Extensions/ProcessExtensions.cs b/MediaBrowser.Common/Extensions/ProcessExtensions.cs index 525475ba5f..6b205049da 100644 --- a/MediaBrowser.Common/Extensions/ProcessExtensions.cs +++ b/MediaBrowser.Common/Extensions/ProcessExtensions.cs @@ -20,7 +20,7 @@ namespace MediaBrowser.Common.Extensions { using (var cancelTokenSource = new CancellationTokenSource(timeout)) { - return await WaitForExitAsync(process, cancelTokenSource.Token); + return await WaitForExitAsync(process, cancelTokenSource.Token).ConfigureAwait(false); } } From 658e963e933319029d7cb730b2daab27e42feac5 Mon Sep 17 00:00:00 2001 From: Mark Monteiro Date: Sun, 5 Apr 2020 09:23:44 -0400 Subject: [PATCH 11/14] replace 'try-finally' with 'using' where appropriate --- Emby.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs | 9 ++------- .../LiveTv/EmbyTV/EncodedRecorder.cs | 7 +------ 2 files changed, 3 insertions(+), 13 deletions(-) diff --git a/Emby.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs b/Emby.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs index e2ca0986bb..4d777081b6 100644 --- a/Emby.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs +++ b/Emby.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs @@ -1709,14 +1709,9 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV private void Process_Exited(object sender, EventArgs e) { - try - { - var exitCode = ((Process)sender).ExitCode; - _logger.LogInformation("Recording post-processing script completed with exit code {ExitCode}", exitCode); - } - finally + using (var process = (Process)sender) { - ((Process)sender).Dispose(); + _logger.LogInformation("Recording post-processing script completed with exit code {ExitCode}", process.ExitCode); } } diff --git a/Emby.Server.Implementations/LiveTv/EmbyTV/EncodedRecorder.cs b/Emby.Server.Implementations/LiveTv/EmbyTV/EncodedRecorder.cs index 0f2203ca0f..4738272be6 100644 --- a/Emby.Server.Implementations/LiveTv/EmbyTV/EncodedRecorder.cs +++ b/Emby.Server.Implementations/LiveTv/EmbyTV/EncodedRecorder.cs @@ -289,8 +289,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV /// private void OnFfMpegProcessExited(Process process, string inputFile) { - try - { + using (process) { _hasExited = true; _logFileStream?.Dispose(); @@ -315,10 +314,6 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV exitCode))); } } - finally - { - process.Dispose(); - } } private async void StartStreamingLog(Stream source, Stream target) From 3d8501e462c1b4f9953444873e3ea64e085916a0 Mon Sep 17 00:00:00 2001 From: Mark Monteiro Date: Sun, 5 Apr 2020 09:25:23 -0400 Subject: [PATCH 12/14] Document exception --- MediaBrowser.Common/Extensions/ProcessExtensions.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/MediaBrowser.Common/Extensions/ProcessExtensions.cs b/MediaBrowser.Common/Extensions/ProcessExtensions.cs index 6b205049da..c747871222 100644 --- a/MediaBrowser.Common/Extensions/ProcessExtensions.cs +++ b/MediaBrowser.Common/Extensions/ProcessExtensions.cs @@ -16,6 +16,7 @@ namespace MediaBrowser.Common.Extensions /// The process to wait for. /// The duration to wait before cancelling waiting for the task. /// True if the task exited normally, false if the timeout elapsed before the process exited. + /// If is not set to true for the process. public static async Task WaitForExitAsync(this Process process, TimeSpan timeout) { using (var cancelTokenSource = new CancellationTokenSource(timeout)) From 7152b55747f508e69bb6417bd583ba15c0e591a4 Mon Sep 17 00:00:00 2001 From: Mark Monteiro Date: Sat, 11 Apr 2020 13:25:50 -0400 Subject: [PATCH 13/14] Use a separate line for each property initializer --- .../ApplicationHost.cs | 13 +++-- .../LiveTv/EmbyTV/EmbyTV.cs | 21 ++++---- .../LiveTv/EmbyTV/EncodedRecorder.cs | 8 ++- .../Attachments/AttachmentExtractor.cs | 23 ++++---- .../Encoder/MediaEncoder.cs | 54 +++++++++++-------- .../Subtitles/SubtitleEncoder.cs | 48 +++++++++-------- 6 files changed, 97 insertions(+), 70 deletions(-) diff --git a/Emby.Server.Implementations/ApplicationHost.cs b/Emby.Server.Implementations/ApplicationHost.cs index 2f7c0a3ebd..12423361ab 100644 --- a/Emby.Server.Implementations/ApplicationHost.cs +++ b/Emby.Server.Implementations/ApplicationHost.cs @@ -1700,13 +1700,16 @@ namespace Emby.Server.Implementations throw new NotSupportedException(); } - var processStartInfo = new ProcessStartInfo + var process = new Process { - FileName = url, - UseShellExecute = true, - ErrorDialog = false + StartInfo = new ProcessStartInfo + { + FileName = url, + UseShellExecute = true, + ErrorDialog = false + }, + EnableRaisingEvents = true }; - var process = new Process { StartInfo = processStartInfo, EnableRaisingEvents = true }; process.Exited += (sender, args) => ((Process)sender).Dispose(); try diff --git a/Emby.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs b/Emby.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs index 4d777081b6..900f12062f 100644 --- a/Emby.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs +++ b/Emby.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs @@ -1680,16 +1680,19 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV try { - var processStartInfo = new ProcessStartInfo - { - Arguments = GetPostProcessArguments(path, options.RecordingPostProcessorArguments), - CreateNoWindow = true, - ErrorDialog = false, - FileName = options.RecordingPostProcessor, - WindowStyle = ProcessWindowStyle.Hidden, - UseShellExecute = false + var process = new Process + { + StartInfo = new ProcessStartInfo + { + Arguments = GetPostProcessArguments(path, options.RecordingPostProcessorArguments), + CreateNoWindow = true, + ErrorDialog = false, + FileName = options.RecordingPostProcessor, + WindowStyle = ProcessWindowStyle.Hidden, + UseShellExecute = false + }, + EnableRaisingEvents = true }; - var process = new Process { StartInfo = processStartInfo, EnableRaisingEvents = true }; _logger.LogInformation("Running recording post processor {0} {1}", process.StartInfo.FileName, process.StartInfo.Arguments); diff --git a/Emby.Server.Implementations/LiveTv/EmbyTV/EncodedRecorder.cs b/Emby.Server.Implementations/LiveTv/EmbyTV/EncodedRecorder.cs index 4738272be6..29d17e2bb2 100644 --- a/Emby.Server.Implementations/LiveTv/EmbyTV/EncodedRecorder.cs +++ b/Emby.Server.Implementations/LiveTv/EmbyTV/EncodedRecorder.cs @@ -90,9 +90,8 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV WindowStyle = ProcessWindowStyle.Hidden, ErrorDialog = false }; - _process = new Process { StartInfo = processStartInfo, EnableRaisingEvents = true }; - var commandLineLogMessage = _process.StartInfo.FileName + " " + _process.StartInfo.Arguments; + var commandLineLogMessage = processStartInfo.FileName + " " + processStartInfo.Arguments; _logger.LogInformation(commandLineLogMessage); var logFilePath = Path.Combine(_appPaths.LogDirectoryPath, "record-transcode-" + Guid.NewGuid() + ".txt"); @@ -104,6 +103,11 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV var commandLineLogMessageBytes = Encoding.UTF8.GetBytes(_json.SerializeToString(mediaSource) + Environment.NewLine + Environment.NewLine + commandLineLogMessage + Environment.NewLine + Environment.NewLine); _logFileStream.Write(commandLineLogMessageBytes, 0, commandLineLogMessageBytes.Length); + _process = new Process + { + StartInfo = processStartInfo, + EnableRaisingEvents = true + }; _process.Exited += (sender, args) => OnFfMpegProcessExited(_process, inputFile); _process.Start(); diff --git a/MediaBrowser.MediaEncoding/Attachments/AttachmentExtractor.cs b/MediaBrowser.MediaEncoding/Attachments/AttachmentExtractor.cs index 8d27c33c01..84eb3b373e 100644 --- a/MediaBrowser.MediaEncoding/Attachments/AttachmentExtractor.cs +++ b/MediaBrowser.MediaEncoding/Attachments/AttachmentExtractor.cs @@ -155,19 +155,22 @@ namespace MediaBrowser.MediaEncoding.Attachments inputPath, attachmentStreamIndex, outputPath); - var startInfo = new ProcessStartInfo - { - Arguments = processArgs, - FileName = _mediaEncoder.EncoderPath, - UseShellExecute = false, - CreateNoWindow = true, - WindowStyle = ProcessWindowStyle.Hidden, - ErrorDialog = false - }; int exitCode; - using (var process = new Process { StartInfo = startInfo, EnableRaisingEvents = true }) + using (var process = new Process + { + StartInfo = new ProcessStartInfo + { + Arguments = processArgs, + FileName = _mediaEncoder.EncoderPath, + UseShellExecute = false, + CreateNoWindow = true, + WindowStyle = ProcessWindowStyle.Hidden, + ErrorDialog = false + }, + EnableRaisingEvents = true + }) { _logger.LogInformation("{File} {Arguments}", process.StartInfo.FileName, process.StartInfo.Arguments); diff --git a/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs b/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs index 4042e64f63..c2bfac9d63 100644 --- a/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs +++ b/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs @@ -359,30 +359,33 @@ namespace MediaBrowser.MediaEncoding.Encoder : "{0} -i {1} -threads 0 -v warning -print_format json -show_streams -show_format"; args = string.Format(args, probeSizeArgument, inputPath).Trim(); - var processStartInfo = new ProcessStartInfo + var process = new Process { - CreateNoWindow = true, - UseShellExecute = false, + StartInfo = new ProcessStartInfo + { + CreateNoWindow = true, + UseShellExecute = false, - // Must consume both or ffmpeg may hang due to deadlocks. See comments below. - RedirectStandardOutput = true, + // Must consume both or ffmpeg may hang due to deadlocks. See comments below. + RedirectStandardOutput = true, - FileName = _ffprobePath, - Arguments = args, + FileName = _ffprobePath, + Arguments = args, - WindowStyle = ProcessWindowStyle.Hidden, - ErrorDialog = false, + WindowStyle = ProcessWindowStyle.Hidden, + ErrorDialog = false, + }, + EnableRaisingEvents = true }; - var process = new Process { StartInfo = processStartInfo, EnableRaisingEvents = true }; if (forceEnableLogging) { - _logger.LogInformation("{0} {1}", process.StartInfo.FileName, process.StartInfo.Arguments); + _logger.LogInformation("{ProcessFileName} {ProcessArgs}", process.StartInfo.FileName, process.StartInfo.Arguments); } else { - _logger.LogDebug("{0} {1}", process.StartInfo.FileName, process.StartInfo.Arguments); + _logger.LogDebug("{ProcessFileName} {ProcessArgs}", process.StartInfo.FileName, process.StartInfo.Arguments); } using (var processWrapper = new ProcessWrapper(process, this)) @@ -568,19 +571,22 @@ namespace MediaBrowser.MediaEncoding.Encoder } } - var processStartInfo = new ProcessStartInfo + var process = new Process { - CreateNoWindow = true, - UseShellExecute = false, - FileName = _ffmpegPath, - Arguments = args, - WindowStyle = ProcessWindowStyle.Hidden, - ErrorDialog = false, + StartInfo = new ProcessStartInfo + { + CreateNoWindow = true, + UseShellExecute = false, + FileName = _ffmpegPath, + Arguments = args, + WindowStyle = ProcessWindowStyle.Hidden, + ErrorDialog = false, + }, + EnableRaisingEvents = true }; - _logger.LogDebug("{0} {1}", processStartInfo.FileName, processStartInfo.Arguments); + _logger.LogDebug("{ProcessFileName} {ProcessArguments}", process.StartInfo.FileName, process.StartInfo.Arguments); - var process = new Process { StartInfo = processStartInfo, EnableRaisingEvents = true }; using (var processWrapper = new ProcessWrapper(process, this)) { bool ranToCompletion; @@ -713,7 +719,11 @@ namespace MediaBrowser.MediaEncoding.Encoder bool ranToCompletion = false; - var process = new Process { StartInfo = processStartInfo, EnableRaisingEvents = true }; + var process = new Process + { + StartInfo = processStartInfo, + EnableRaisingEvents = true + }; using (var processWrapper = new ProcessWrapper(process, this)) { try diff --git a/MediaBrowser.MediaEncoding/Subtitles/SubtitleEncoder.cs b/MediaBrowser.MediaEncoding/Subtitles/SubtitleEncoder.cs index b1397d79db..a84dc30c88 100644 --- a/MediaBrowser.MediaEncoding/Subtitles/SubtitleEncoder.cs +++ b/MediaBrowser.MediaEncoding/Subtitles/SubtitleEncoder.cs @@ -426,19 +426,21 @@ namespace MediaBrowser.MediaEncoding.Subtitles encodingParam = " -sub_charenc " + encodingParam; } - var processStartInfo = new ProcessStartInfo - { - CreateNoWindow = true, - UseShellExecute = false, - FileName = _mediaEncoder.EncoderPath, - Arguments = string.Format("{0} -i \"{1}\" -c:s srt \"{2}\"", encodingParam, inputPath, outputPath), - WindowStyle = ProcessWindowStyle.Hidden, - ErrorDialog = false - }; - int exitCode; - using (var process = new Process { StartInfo = processStartInfo, EnableRaisingEvents = true }) + using (var process = new Process + { + StartInfo = new ProcessStartInfo + { + CreateNoWindow = true, + UseShellExecute = false, + FileName = _mediaEncoder.EncoderPath, + Arguments = string.Format("{0} -i \"{1}\" -c:s srt \"{2}\"", encodingParam, inputPath, outputPath), + WindowStyle = ProcessWindowStyle.Hidden, + ErrorDialog = false + }, + EnableRaisingEvents = true + }) { _logger.LogInformation("{0} {1}", process.StartInfo.FileName, process.StartInfo.Arguments); @@ -577,19 +579,21 @@ namespace MediaBrowser.MediaEncoding.Subtitles outputCodec, outputPath); - var processStartInfo = new ProcessStartInfo - { - CreateNoWindow = true, - UseShellExecute = false, - FileName = _mediaEncoder.EncoderPath, - Arguments = processArgs, - WindowStyle = ProcessWindowStyle.Hidden, - ErrorDialog = false - }; - int exitCode; - using (var process = new Process { StartInfo = processStartInfo, EnableRaisingEvents = true }) + using (var process = new Process + { + StartInfo = new ProcessStartInfo + { + CreateNoWindow = true, + UseShellExecute = false, + FileName = _mediaEncoder.EncoderPath, + Arguments = processArgs, + WindowStyle = ProcessWindowStyle.Hidden, + ErrorDialog = false + }, + EnableRaisingEvents = true + }) { _logger.LogInformation("{File} {Arguments}", process.StartInfo.FileName, process.StartInfo.Arguments); From 411328827808e115ce207f4c985c9dea1c7211e7 Mon Sep 17 00:00:00 2001 From: Mark Monteiro Date: Sat, 11 Apr 2020 13:46:31 -0400 Subject: [PATCH 14/14] Fix style issues --- .../LiveTv/EmbyTV/EncodedRecorder.cs | 3 +- .../Attachments/AttachmentExtractor.cs | 22 +++++----- .../Subtitles/SubtitleEncoder.cs | 44 +++++++++---------- 3 files changed, 35 insertions(+), 34 deletions(-) diff --git a/Emby.Server.Implementations/LiveTv/EmbyTV/EncodedRecorder.cs b/Emby.Server.Implementations/LiveTv/EmbyTV/EncodedRecorder.cs index 29d17e2bb2..bc86cc59a2 100644 --- a/Emby.Server.Implementations/LiveTv/EmbyTV/EncodedRecorder.cs +++ b/Emby.Server.Implementations/LiveTv/EmbyTV/EncodedRecorder.cs @@ -293,7 +293,8 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV /// private void OnFfMpegProcessExited(Process process, string inputFile) { - using (process) { + using (process) + { _hasExited = true; _logFileStream?.Dispose(); diff --git a/MediaBrowser.MediaEncoding/Attachments/AttachmentExtractor.cs b/MediaBrowser.MediaEncoding/Attachments/AttachmentExtractor.cs index 84eb3b373e..3f177a9fa8 100644 --- a/MediaBrowser.MediaEncoding/Attachments/AttachmentExtractor.cs +++ b/MediaBrowser.MediaEncoding/Attachments/AttachmentExtractor.cs @@ -159,18 +159,18 @@ namespace MediaBrowser.MediaEncoding.Attachments int exitCode; using (var process = new Process - { - StartInfo = new ProcessStartInfo { - Arguments = processArgs, - FileName = _mediaEncoder.EncoderPath, - UseShellExecute = false, - CreateNoWindow = true, - WindowStyle = ProcessWindowStyle.Hidden, - ErrorDialog = false - }, - EnableRaisingEvents = true - }) + StartInfo = new ProcessStartInfo + { + Arguments = processArgs, + FileName = _mediaEncoder.EncoderPath, + UseShellExecute = false, + CreateNoWindow = true, + WindowStyle = ProcessWindowStyle.Hidden, + ErrorDialog = false + }, + EnableRaisingEvents = true + }) { _logger.LogInformation("{File} {Arguments}", process.StartInfo.FileName, process.StartInfo.Arguments); diff --git a/MediaBrowser.MediaEncoding/Subtitles/SubtitleEncoder.cs b/MediaBrowser.MediaEncoding/Subtitles/SubtitleEncoder.cs index a84dc30c88..ba171295ea 100644 --- a/MediaBrowser.MediaEncoding/Subtitles/SubtitleEncoder.cs +++ b/MediaBrowser.MediaEncoding/Subtitles/SubtitleEncoder.cs @@ -429,18 +429,18 @@ namespace MediaBrowser.MediaEncoding.Subtitles int exitCode; using (var process = new Process - { - StartInfo = new ProcessStartInfo { - CreateNoWindow = true, - UseShellExecute = false, - FileName = _mediaEncoder.EncoderPath, - Arguments = string.Format("{0} -i \"{1}\" -c:s srt \"{2}\"", encodingParam, inputPath, outputPath), - WindowStyle = ProcessWindowStyle.Hidden, - ErrorDialog = false - }, - EnableRaisingEvents = true - }) + StartInfo = new ProcessStartInfo + { + CreateNoWindow = true, + UseShellExecute = false, + FileName = _mediaEncoder.EncoderPath, + Arguments = string.Format("{0} -i \"{1}\" -c:s srt \"{2}\"", encodingParam, inputPath, outputPath), + WindowStyle = ProcessWindowStyle.Hidden, + ErrorDialog = false + }, + EnableRaisingEvents = true + }) { _logger.LogInformation("{0} {1}", process.StartInfo.FileName, process.StartInfo.Arguments); @@ -582,18 +582,18 @@ namespace MediaBrowser.MediaEncoding.Subtitles int exitCode; using (var process = new Process - { - StartInfo = new ProcessStartInfo { - CreateNoWindow = true, - UseShellExecute = false, - FileName = _mediaEncoder.EncoderPath, - Arguments = processArgs, - WindowStyle = ProcessWindowStyle.Hidden, - ErrorDialog = false - }, - EnableRaisingEvents = true - }) + StartInfo = new ProcessStartInfo + { + CreateNoWindow = true, + UseShellExecute = false, + FileName = _mediaEncoder.EncoderPath, + Arguments = processArgs, + WindowStyle = ProcessWindowStyle.Hidden, + ErrorDialog = false + }, + EnableRaisingEvents = true + }) { _logger.LogInformation("{File} {Arguments}", process.StartInfo.FileName, process.StartInfo.Arguments);