jellyfin-server/MediaBrowser.MediaEncoding/Encoder/BaseEncoder.cs

376 lines
14 KiB
C#
Raw Normal View History

2015-01-02 06:12:58 +00: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-20 05:40:51 +00:00
using MediaBrowser.Model.Dto;
2015-01-02 06:12:58 +00:00
using MediaBrowser.Model.Entities;
using MediaBrowser.Model.IO;
using MediaBrowser.Model.Logging;
using MediaBrowser.Model.MediaInfo;
2015-01-02 06:12:58 +00:00
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
2016-11-01 04:07:12 +00:00
using MediaBrowser.Model.Diagnostics;
2016-03-07 18:50:58 +00:00
using MediaBrowser.Model.Dlna;
2015-01-02 06:12:58 +00: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-08 04:44:31 +00:00
protected readonly IMediaSourceManager MediaSourceManager;
2016-11-01 04:07:12 +00:00
protected IProcessFactory ProcessFactory;
2015-01-02 06:12:58 +00:00
protected readonly CultureInfo UsCulture = new CultureInfo("en-US");
protected EncodingHelper EncodingHelper;
2015-05-15 15:46:20 +00:00
protected BaseEncoder(MediaEncoder mediaEncoder,
2015-01-02 06:12:58 +00:00
ILogger logger,
IServerConfigurationManager configurationManager,
IFileSystem fileSystem,
IIsoManager isoManager,
ILibraryManager libraryManager,
2016-06-19 06:18:29 +00:00
ISessionManager sessionManager,
ISubtitleEncoder subtitleEncoder,
2016-11-01 04:07:12 +00:00
IMediaSourceManager mediaSourceManager, IProcessFactory processFactory)
2015-01-02 06:12:58 +00:00
{
MediaEncoder = mediaEncoder;
Logger = logger;
ConfigurationManager = configurationManager;
FileSystem = fileSystem;
IsoManager = isoManager;
LibraryManager = libraryManager;
SessionManager = sessionManager;
SubtitleEncoder = subtitleEncoder;
2015-03-08 04:44:31 +00:00
MediaSourceManager = mediaSourceManager;
2016-11-01 04:07:12 +00:00
ProcessFactory = processFactory;
EncodingHelper = new EncodingHelper(MediaEncoder, ConfigurationManager, FileSystem, SubtitleEncoder);
2015-01-02 06:12:58 +00:00
}
public async Task<EncodingJob> Start(EncodingJobOptions options,
IProgress<double> progress,
CancellationToken cancellationToken)
{
2017-03-19 06:10:11 +00:00
var encodingJob = await new EncodingJobFactory(Logger, LibraryManager, MediaSourceManager, ConfigurationManager, MediaEncoder)
.CreateJob(options, EncodingHelper, IsVideoEncoder, progress, cancellationToken).ConfigureAwait(false);
2015-01-02 06:12:58 +00:00
encodingJob.OutputFilePath = GetOutputFilePath(encodingJob);
2017-05-04 18:14:45 +00:00
FileSystem.CreateDirectory(FileSystem.GetDirectoryName(encodingJob.OutputFilePath));
2015-01-02 06:12:58 +00:00
2015-04-09 17:30:18 +00:00
encodingJob.ReadInputAtNativeFramerate = options.ReadInputAtNativeFramerate;
2015-01-02 06:12:58 +00:00
await AcquireResources(encodingJob, cancellationToken).ConfigureAwait(false);
2017-03-19 18:59:05 +00:00
var commandLineArgs = GetCommandLineArguments(encodingJob);
2015-01-02 06:12:58 +00:00
2016-11-01 04:07:12 +00:00
var process = ProcessFactory.Create(new ProcessOptions
2015-01-02 06:12:58 +00:00
{
2016-11-01 04:07:12 +00:00
CreateNoWindow = true,
UseShellExecute = false,
2015-01-02 06:12:58 +00:00
2016-11-01 04:07:12 +00:00
// Must consume both stdout and stderr or deadlocks may occur
//RedirectStandardOutput = true,
RedirectStandardError = true,
RedirectStandardInput = true,
2015-01-02 06:12:58 +00:00
2016-11-01 04:07:12 +00:00
FileName = MediaEncoder.EncoderPath,
Arguments = commandLineArgs,
2015-01-02 06:12:58 +00:00
2016-11-01 04:07:12 +00:00
IsHidden = true,
ErrorDialog = false,
2015-01-02 06:12:58 +00:00
EnableRaisingEvents = true
2016-11-01 04:07:12 +00:00
});
2015-01-02 06:12:58 +00: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");
2017-05-04 18:14:45 +00:00
FileSystem.CreateDirectory(FileSystem.GetDirectoryName(logFilePath));
2015-01-02 06:12:58 +00: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 19:02:04 +00:00
encodingJob.LogFileStream = FileSystem.GetFileStream(logFilePath, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read, true);
2015-01-02 06:12:58 +00: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-05 06:00:13 +00:00
cancellationToken.Register(() => Cancel(process, encodingJob));
2016-06-19 06:18:29 +00:00
2015-01-02 06:12:58 +00:00
// MUST read both stdout and stderr asynchronously or a deadlock may occurr
2016-07-02 02:16:05 +00:00
//process.BeginOutputReadLine();
2015-01-02 06:12:58 +00: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-19 06:18:29 +00:00
while (!FileSystem.FileExists(encodingJob.OutputFilePath) && !encodingJob.HasExited)
2015-01-02 06:12:58 +00:00
{
await Task.Delay(100, cancellationToken).ConfigureAwait(false);
}
return encodingJob;
}
2016-11-01 04:07:12 +00:00
private void Cancel(IProcess process, EncodingJob job)
2015-01-05 06:00:13 +00:00
{
Logger.Info("Killing ffmpeg process for {0}", job.OutputFilePath);
//process.Kill();
process.StandardInput.WriteLine("q");
job.IsCancelled = true;
}
2015-01-02 06:12:58 +00:00
/// <summary>
/// Processes the exited.
/// </summary>
/// <param name="process">The process.</param>
/// <param name="job">The job.</param>
2016-11-01 04:07:12 +00:00
private void OnFfMpegProcessExited(IProcess process, EncodingJob job)
2015-01-02 06:12:58 +00:00
{
job.HasExited = true;
Logger.Debug("Disposing stream resources");
job.Dispose();
2015-01-05 06:00:13 +00:00
var isSuccesful = false;
2015-01-02 06:12:58 +00:00
try
{
2015-01-05 06:00:13 +00:00
var exitCode = process.ExitCode;
Logger.Info("FFMpeg exited with code {0}", exitCode);
2015-01-02 06:12:58 +00:00
2015-01-05 06:00:13 +00: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-02 06:12:58 +00:00
try
{
2015-01-05 06:00:13 +00:00
job.TaskCompletionSource.TrySetException(new OperationCanceledException());
2015-01-02 06:12:58 +00:00
}
catch
{
}
}
2015-01-05 06:00:13 +00:00
else
2015-01-02 06:12:58 +00:00
{
try
{
2015-01-05 06:00:13 +00:00
DeleteFiles(job);
}
catch
{
}
try
{
2016-10-30 07:11:37 +00:00
job.TaskCompletionSource.TrySetException(new Exception("Encoding failed"));
2015-01-02 06:12:58 +00: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-05 06:00:13 +00:00
protected virtual void DeleteFiles(EncodingJob job)
{
FileSystem.DeleteFile(job.OutputFilePath);
2015-01-05 06:00:13 +00:00
}
2015-01-02 06:12:58 +00:00
private void OnTranscodeBeginning(EncodingJob job)
{
2017-03-24 15:03:49 +00:00
job.ReportTranscodingProgress(null, null, null, null, null);
2015-01-02 06:12:58 +00:00
}
private void OnTranscodeFailedToStart(string path, EncodingJob job)
{
if (!string.IsNullOrWhiteSpace(job.Options.DeviceId))
{
SessionManager.ClearTranscodingInfo(job.Options.DeviceId);
}
}
2015-01-05 06:00:13 +00:00
protected abstract bool IsVideoEncoder { get; }
2015-01-02 06:12:58 +00:00
protected virtual string GetWorkingDirectory(EncodingJobOptions options)
{
return null;
}
protected EncodingOptions GetEncodingOptions()
{
return ConfigurationManager.GetConfiguration<EncodingOptions>("encoding");
}
2017-03-19 18:59:05 +00:00
protected abstract string GetCommandLineArguments(EncodingJob job);
2015-01-02 06:12:58 +00:00
private string GetOutputFilePath(EncodingJob state)
{
2016-06-19 06:18:29 +00:00
var folder = string.IsNullOrWhiteSpace(state.Options.OutputDirectory) ?
2015-01-17 04:29:53 +00:00
ConfigurationManager.ApplicationPaths.TranscodingTempPath :
state.Options.OutputDirectory;
2015-01-02 06:12:58 +00:00
var outputFileExtension = GetOutputFileExtension(state);
var filename = state.Id + (outputFileExtension ?? string.Empty).ToLower();
2015-01-17 04:29:53 +00:00
return Path.Combine(folder, filename);
2015-01-02 06:12:58 +00:00
}
protected virtual string GetOutputFileExtension(EncodingJob state)
{
if (!string.IsNullOrWhiteSpace(state.Options.OutputContainer))
{
return "." + state.Options.OutputContainer;
}
return null;
}
2015-09-20 02:06:56 +00: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-30 04:00:45 +00:00
if (string.Equals(state.OutputVideoCodec, "copy", StringComparison.OrdinalIgnoreCase))
2015-09-20 02:06:56 +00:00
{
2016-06-19 06:18:29 +00:00
return null;
2016-04-30 04:00:45 +00: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-30 04:00:45 +00:00
if (state.VideoStream != null && !string.IsNullOrWhiteSpace(state.VideoStream.Codec))
{
if (string.Equals(GetEncodingOptions().HardwareAccelerationType, "qsv", StringComparison.OrdinalIgnoreCase))
2015-09-20 02:06:56 +00:00
{
switch (state.MediaSource.VideoStream.Codec.ToLower())
{
case "avc":
case "h264":
if (MediaEncoder.SupportsDecoder("h264_qsv"))
{
2016-04-30 04:00:45 +00:00
// Seeing stalls and failures with decoding. Not worth it compared to encoding.
2016-06-30 18:59:18 +00:00
return "-c:v h264_qsv ";
2015-09-20 02:06:56 +00: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-02 06:12:58 +00: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);
}
2017-04-04 06:01:20 +00:00
if (state.MediaSource.RequiresOpening && string.IsNullOrWhiteSpace(state.Options.LiveStreamId))
2015-01-02 06:12:58 +00:00
{
var liveStreamResponse = await MediaSourceManager.OpenLiveStream(new LiveStreamRequest
2015-01-02 06:12:58 +00:00
{
OpenToken = state.MediaSource.OpenToken
2015-01-02 06:12:58 +00:00
2017-04-17 19:01:16 +00:00
}, cancellationToken).ConfigureAwait(false);
2015-01-02 06:12:58 +00:00
EncodingHelper.AttachMediaSourceInfo(state, liveStreamResponse.MediaSource, null);
2015-01-02 06:12:58 +00:00
if (state.IsVideoRequest)
2015-01-02 06:12:58 +00:00
{
EncodingHelper.TryStreamCopy(state);
2015-01-02 06:12:58 +00:00
}
}
2015-01-02 06:12:58 +00:00
if (state.MediaSource.BufferMs.HasValue)
{
await Task.Delay(state.MediaSource.BufferMs.Value, cancellationToken).ConfigureAwait(false);
2015-01-02 06:12:58 +00:00
}
}
}
}