jellyfin/MediaBrowser.MediaEncoding/Encoder/BaseEncoder.cs

376 lines
14 KiB
C#
Raw Normal View History

2015-01-01 23:12:58 -07:00
using MediaBrowser.Common.Configuration;
using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.MediaEncoding;
using MediaBrowser.Controller.Session;
using MediaBrowser.Model.Configuration;
2015-03-19 22:40:51 -07:00
using MediaBrowser.Model.Dto;
2015-01-01 23:12:58 -07:00
using MediaBrowser.Model.Entities;
using MediaBrowser.Model.IO;
using MediaBrowser.Model.Logging;
using MediaBrowser.Model.MediaInfo;
2015-01-01 23:12:58 -07:00
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
2016-10-31 21:07:12 -07:00
using MediaBrowser.Model.Diagnostics;
2016-03-07 11:50:58 -07:00
using MediaBrowser.Model.Dlna;
2015-01-01 23:12:58 -07:00
namespace MediaBrowser.MediaEncoding.Encoder
{
public abstract class BaseEncoder
{
protected readonly MediaEncoder MediaEncoder;
protected readonly ILogger Logger;
protected readonly IServerConfigurationManager ConfigurationManager;
protected readonly IFileSystem FileSystem;
protected readonly IIsoManager IsoManager;
protected readonly ILibraryManager LibraryManager;
protected readonly ISessionManager SessionManager;
protected readonly ISubtitleEncoder SubtitleEncoder;
2015-03-07 21:44:31 -07:00
protected readonly IMediaSourceManager MediaSourceManager;
2016-10-31 21:07:12 -07:00
protected IProcessFactory ProcessFactory;
2015-01-01 23:12:58 -07:00
protected readonly CultureInfo UsCulture = new CultureInfo("en-US");
protected EncodingHelper EncodingHelper;
2015-05-15 08:46:20 -07:00
protected BaseEncoder(MediaEncoder mediaEncoder,
2015-01-01 23:12:58 -07:00
ILogger logger,
IServerConfigurationManager configurationManager,
IFileSystem fileSystem,
IIsoManager isoManager,
ILibraryManager libraryManager,
2016-06-18 23:18:29 -07:00
ISessionManager sessionManager,
ISubtitleEncoder subtitleEncoder,
2016-10-31 21:07:12 -07:00
IMediaSourceManager mediaSourceManager, IProcessFactory processFactory)
2015-01-01 23:12:58 -07:00
{
MediaEncoder = mediaEncoder;
Logger = logger;
ConfigurationManager = configurationManager;
FileSystem = fileSystem;
IsoManager = isoManager;
LibraryManager = libraryManager;
SessionManager = sessionManager;
SubtitleEncoder = subtitleEncoder;
2015-03-07 21:44:31 -07:00
MediaSourceManager = mediaSourceManager;
2016-10-31 21:07:12 -07:00
ProcessFactory = processFactory;
EncodingHelper = new EncodingHelper(MediaEncoder, ConfigurationManager, FileSystem, SubtitleEncoder);
2015-01-01 23:12:58 -07:00
}
public async Task<EncodingJob> Start(EncodingJobOptions options,
IProgress<double> progress,
CancellationToken cancellationToken)
{
2017-03-18 23:10:11 -07:00
var encodingJob = await new EncodingJobFactory(Logger, LibraryManager, MediaSourceManager, ConfigurationManager, MediaEncoder)
.CreateJob(options, EncodingHelper, IsVideoEncoder, progress, cancellationToken).ConfigureAwait(false);
2015-01-01 23:12:58 -07:00
encodingJob.OutputFilePath = GetOutputFilePath(encodingJob);
2015-09-13 14:32:02 -07:00
FileSystem.CreateDirectory(Path.GetDirectoryName(encodingJob.OutputFilePath));
2015-01-01 23:12:58 -07:00
2015-04-09 10:30:18 -07:00
encodingJob.ReadInputAtNativeFramerate = options.ReadInputAtNativeFramerate;
2015-01-01 23:12:58 -07:00
await AcquireResources(encodingJob, cancellationToken).ConfigureAwait(false);
2016-06-18 23:18:29 -07:00
var commandLineArgs = await GetCommandLineArguments(encodingJob).ConfigureAwait(false);
2015-01-01 23:12:58 -07:00
2016-10-31 21:07:12 -07:00
var process = ProcessFactory.Create(new ProcessOptions
2015-01-01 23:12:58 -07:00
{
2016-10-31 21:07:12 -07:00
CreateNoWindow = true,
UseShellExecute = false,
2015-01-01 23:12:58 -07:00
2016-10-31 21:07:12 -07:00
// Must consume both stdout and stderr or deadlocks may occur
//RedirectStandardOutput = true,
RedirectStandardError = true,
RedirectStandardInput = true,
2015-01-01 23:12:58 -07:00
2016-10-31 21:07:12 -07:00
FileName = MediaEncoder.EncoderPath,
Arguments = commandLineArgs,
2015-01-01 23:12:58 -07:00
2016-10-31 21:07:12 -07:00
IsHidden = true,
ErrorDialog = false,
2015-01-01 23:12:58 -07:00
EnableRaisingEvents = true
2016-10-31 21:07:12 -07:00
});
2015-01-01 23:12:58 -07:00
var workingDirectory = GetWorkingDirectory(options);
if (!string.IsNullOrWhiteSpace(workingDirectory))
{
process.StartInfo.WorkingDirectory = workingDirectory;
}
OnTranscodeBeginning(encodingJob);
var commandLineLogMessage = process.StartInfo.FileName + " " + process.StartInfo.Arguments;
Logger.Info(commandLineLogMessage);
var logFilePath = Path.Combine(ConfigurationManager.CommonApplicationPaths.LogDirectoryPath, "transcode-" + Guid.NewGuid() + ".txt");
2015-09-13 14:32:02 -07:00
FileSystem.CreateDirectory(Path.GetDirectoryName(logFilePath));
2015-01-01 23:12:58 -07:00
// FFMpeg writes debug/error info to stderr. This is useful when debugging so let's put it in the log directory.
2016-10-25 12:02:04 -07:00
encodingJob.LogFileStream = FileSystem.GetFileStream(logFilePath, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read, true);
2015-01-01 23:12:58 -07:00
var commandLineLogMessageBytes = Encoding.UTF8.GetBytes(commandLineLogMessage + Environment.NewLine + Environment.NewLine);
await encodingJob.LogFileStream.WriteAsync(commandLineLogMessageBytes, 0, commandLineLogMessageBytes.Length, cancellationToken).ConfigureAwait(false);
process.Exited += (sender, args) => OnFfMpegProcessExited(process, encodingJob);
try
{
process.Start();
}
catch (Exception ex)
{
Logger.ErrorException("Error starting ffmpeg", ex);
OnTranscodeFailedToStart(encodingJob.OutputFilePath, encodingJob);
throw;
}
2015-01-04 23:00:13 -07:00
cancellationToken.Register(() => Cancel(process, encodingJob));
2016-06-18 23:18:29 -07:00
2015-01-01 23:12:58 -07:00
// MUST read both stdout and stderr asynchronously or a deadlock may occurr
2016-07-01 19:16:05 -07:00
//process.BeginOutputReadLine();
2015-01-01 23:12:58 -07:00
// Important - don't await the log task or we won't be able to kill ffmpeg when the user stops playback
new JobLogger(Logger).StartStreamingLog(encodingJob, process.StandardError.BaseStream, encodingJob.LogFileStream);
// Wait for the file to exist before proceeeding
2016-06-18 23:18:29 -07:00
while (!FileSystem.FileExists(encodingJob.OutputFilePath) && !encodingJob.HasExited)
2015-01-01 23:12:58 -07:00
{
await Task.Delay(100, cancellationToken).ConfigureAwait(false);
}
return encodingJob;
}
2016-10-31 21:07:12 -07:00
private void Cancel(IProcess process, EncodingJob job)
2015-01-04 23:00:13 -07:00
{
Logger.Info("Killing ffmpeg process for {0}", job.OutputFilePath);
//process.Kill();
process.StandardInput.WriteLine("q");
job.IsCancelled = true;
}
2015-01-01 23:12:58 -07:00
/// <summary>
/// Processes the exited.
/// </summary>
/// <param name="process">The process.</param>
/// <param name="job">The job.</param>
2016-10-31 21:07:12 -07:00
private void OnFfMpegProcessExited(IProcess process, EncodingJob job)
2015-01-01 23:12:58 -07:00
{
job.HasExited = true;
Logger.Debug("Disposing stream resources");
job.Dispose();
2015-01-04 23:00:13 -07:00
var isSuccesful = false;
2015-01-01 23:12:58 -07:00
try
{
2015-01-04 23:00:13 -07:00
var exitCode = process.ExitCode;
Logger.Info("FFMpeg exited with code {0}", exitCode);
2015-01-01 23:12:58 -07:00
2015-01-04 23:00:13 -07:00
isSuccesful = exitCode == 0;
}
catch
{
Logger.Error("FFMpeg exited with an error.");
}
if (isSuccesful && !job.IsCancelled)
{
job.TaskCompletionSource.TrySetResult(true);
}
else if (job.IsCancelled)
{
try
{
DeleteFiles(job);
}
catch
{
}
2015-01-01 23:12:58 -07:00
try
{
2015-01-04 23:00:13 -07:00
job.TaskCompletionSource.TrySetException(new OperationCanceledException());
2015-01-01 23:12:58 -07:00
}
catch
{
}
}
2015-01-04 23:00:13 -07:00
else
2015-01-01 23:12:58 -07:00
{
try
{
2015-01-04 23:00:13 -07:00
DeleteFiles(job);
}
catch
{
}
try
{
2016-10-30 00:11:37 -07:00
job.TaskCompletionSource.TrySetException(new Exception("Encoding failed"));
2015-01-01 23:12:58 -07:00
}
catch
{
}
}
// This causes on exited to be called twice:
//try
//{
// // Dispose the process
// process.Dispose();
//}
//catch (Exception ex)
//{
// Logger.ErrorException("Error disposing ffmpeg.", ex);
//}
}
2015-01-04 23:00:13 -07:00
protected virtual void DeleteFiles(EncodingJob job)
{
FileSystem.DeleteFile(job.OutputFilePath);
2015-01-04 23:00:13 -07:00
}
2015-01-01 23:12:58 -07:00
private void OnTranscodeBeginning(EncodingJob job)
{
job.ReportTranscodingProgress(null, null, null, null);
}
private void OnTranscodeFailedToStart(string path, EncodingJob job)
{
if (!string.IsNullOrWhiteSpace(job.Options.DeviceId))
{
SessionManager.ClearTranscodingInfo(job.Options.DeviceId);
}
}
2015-01-04 23:00:13 -07:00
protected abstract bool IsVideoEncoder { get; }
2015-01-01 23:12:58 -07:00
protected virtual string GetWorkingDirectory(EncodingJobOptions options)
{
return null;
}
protected EncodingOptions GetEncodingOptions()
{
return ConfigurationManager.GetConfiguration<EncodingOptions>("encoding");
}
2016-06-18 23:18:29 -07:00
protected abstract Task<string> GetCommandLineArguments(EncodingJob job);
2015-01-01 23:12:58 -07:00
private string GetOutputFilePath(EncodingJob state)
{
2016-06-18 23:18:29 -07:00
var folder = string.IsNullOrWhiteSpace(state.Options.OutputDirectory) ?
2015-01-16 21:29:53 -07:00
ConfigurationManager.ApplicationPaths.TranscodingTempPath :
state.Options.OutputDirectory;
2015-01-01 23:12:58 -07:00
var outputFileExtension = GetOutputFileExtension(state);
var filename = state.Id + (outputFileExtension ?? string.Empty).ToLower();
2015-01-16 21:29:53 -07:00
return Path.Combine(folder, filename);
2015-01-01 23:12:58 -07:00
}
protected virtual string GetOutputFileExtension(EncodingJob state)
{
if (!string.IsNullOrWhiteSpace(state.Options.OutputContainer))
{
return "." + state.Options.OutputContainer;
}
return null;
}
2015-09-19 19:06:56 -07:00
/// <summary>
/// Gets the name of the output video codec
/// </summary>
/// <param name="state">The state.</param>
/// <returns>System.String.</returns>
protected string GetVideoDecoder(EncodingJob state)
{
2016-04-29 21:00:45 -07:00
if (string.Equals(state.OutputVideoCodec, "copy", StringComparison.OrdinalIgnoreCase))
2015-09-19 19:06:56 -07:00
{
2016-06-18 23:18:29 -07:00
return null;
2016-04-29 21:00:45 -07:00
}
// Only use alternative encoders for video files.
// When using concat with folder rips, if the mfx session fails to initialize, ffmpeg will be stuck retrying and will not exit gracefully
// Since transcoding of folder rips is expiremental anyway, it's not worth adding additional variables such as this.
if (state.VideoType != VideoType.VideoFile)
{
return null;
}
2016-04-29 21:00:45 -07:00
if (state.VideoStream != null && !string.IsNullOrWhiteSpace(state.VideoStream.Codec))
{
if (string.Equals(GetEncodingOptions().HardwareAccelerationType, "qsv", StringComparison.OrdinalIgnoreCase))
2015-09-19 19:06:56 -07:00
{
switch (state.MediaSource.VideoStream.Codec.ToLower())
{
case "avc":
case "h264":
if (MediaEncoder.SupportsDecoder("h264_qsv"))
{
2016-04-29 21:00:45 -07:00
// Seeing stalls and failures with decoding. Not worth it compared to encoding.
2016-06-30 11:59:18 -07:00
return "-c:v h264_qsv ";
2015-09-19 19:06:56 -07:00
}
break;
case "mpeg2video":
if (MediaEncoder.SupportsDecoder("mpeg2_qsv"))
{
return "-c:v mpeg2_qsv ";
}
break;
case "vc1":
if (MediaEncoder.SupportsDecoder("vc1_qsv"))
{
return "-c:v vc1_qsv ";
}
break;
}
}
}
// leave blank so ffmpeg will decide
return null;
}
2015-01-01 23:12:58 -07:00
private async Task AcquireResources(EncodingJob state, CancellationToken cancellationToken)
{
if (state.VideoType == VideoType.Iso && state.IsoType.HasValue && IsoManager.CanMount(state.MediaPath))
{
state.IsoMount = await IsoManager.Mount(state.MediaPath, cancellationToken).ConfigureAwait(false);
}
2015-09-19 19:06:56 -07:00
if (state.MediaSource.RequiresOpening && string.IsNullOrWhiteSpace(state.LiveStreamId))
2015-01-01 23:12:58 -07:00
{
var liveStreamResponse = await MediaSourceManager.OpenLiveStream(new LiveStreamRequest
2015-01-01 23:12:58 -07:00
{
OpenToken = state.MediaSource.OpenToken
2015-01-01 23:12:58 -07:00
}, false, cancellationToken).ConfigureAwait(false);
2015-01-01 23:12:58 -07:00
EncodingHelper.AttachMediaSourceInfo(state, liveStreamResponse.MediaSource, null);
2015-01-01 23:12:58 -07:00
if (state.IsVideoRequest)
2015-01-01 23:12:58 -07:00
{
EncodingHelper.TryStreamCopy(state);
2015-01-01 23:12:58 -07:00
}
}
2015-01-01 23:12:58 -07:00
if (state.MediaSource.BufferMs.HasValue)
{
await Task.Delay(state.MediaSource.BufferMs.Value, cancellationToken).ConfigureAwait(false);
2015-01-01 23:12:58 -07:00
}
}
}
}