jellyfin/Emby.Server.Implementations/LiveTv/EmbyTV/EncodedRecorder.cs

329 lines
12 KiB
C#
Raw Normal View History

#nullable disable
#pragma warning disable CS1591
using System;
2016-02-12 07:01:38 +00:00
using System.Collections.Generic;
using System.Diagnostics;
2016-02-12 07:01:38 +00:00
using System.Globalization;
using System.IO;
using System.Text;
using System.Text.Json;
2016-02-12 07:01:38 +00:00
using System.Threading;
using System.Threading.Tasks;
using Jellyfin.Extensions;
using Jellyfin.Extensions.Json;
2020-11-18 09:01:03 +00:00
using MediaBrowser.Common.Configuration;
using MediaBrowser.Controller;
2020-11-17 13:46:23 +00:00
using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Library;
2016-02-12 07:01:38 +00:00
using MediaBrowser.Controller.MediaEncoding;
using MediaBrowser.Model.Dto;
using MediaBrowser.Model.IO;
using Microsoft.Extensions.Logging;
2016-02-12 07:01:38 +00:00
2016-11-03 23:35:19 +00:00
namespace Emby.Server.Implementations.LiveTv.EmbyTV
2016-02-12 07:01:38 +00:00
{
public class EncodedRecorder : IRecorder
{
private readonly ILogger _logger;
private readonly IMediaEncoder _mediaEncoder;
private readonly IServerApplicationPaths _appPaths;
2020-08-31 20:20:19 +00:00
private readonly TaskCompletionSource<bool> _taskCompletionSource = new TaskCompletionSource<bool>();
2020-11-17 13:46:23 +00:00
private readonly IServerConfigurationManager _serverConfigurationManager;
2021-03-09 04:57:38 +00:00
private readonly JsonSerializerOptions _jsonOptions = JsonDefaults.Options;
2016-02-12 07:01:38 +00:00
private bool _hasExited;
2016-11-30 19:50:39 +00:00
private Stream _logFileStream;
2016-02-12 07:01:38 +00:00
private string _targetPath;
private Process _process;
2016-02-12 07:01:38 +00:00
2019-02-06 19:38:42 +00:00
public EncodedRecorder(
ILogger logger,
IMediaEncoder mediaEncoder,
IServerApplicationPaths appPaths,
2020-11-17 13:46:23 +00:00
IServerConfigurationManager serverConfigurationManager)
2016-02-12 07:01:38 +00:00
{
_logger = logger;
_mediaEncoder = mediaEncoder;
_appPaths = appPaths;
2020-11-17 13:46:23 +00:00
_serverConfigurationManager = serverConfigurationManager;
2016-09-08 06:41:49 +00:00
}
private static bool CopySubtitles => false;
2017-02-21 18:04:35 +00:00
2016-05-10 05:15:06 +00:00
public string GetOutputPath(MediaSourceInfo mediaSource, string targetFile)
{
2018-09-12 17:26:21 +00:00
return Path.ChangeExtension(targetFile, ".ts");
2016-05-10 05:15:06 +00:00
}
2017-05-15 19:45:39 +00:00
public async Task Record(IDirectStreamProvider directStreamProvider, MediaSourceInfo mediaSource, string targetFile, TimeSpan duration, Action onStarted, CancellationToken cancellationToken)
2016-02-12 07:01:38 +00:00
{
2018-09-12 17:26:21 +00:00
// The media source is infinite so we need to handle stopping ourselves
2020-08-31 20:20:19 +00:00
using var durationToken = new CancellationTokenSource(duration);
using var cancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, durationToken.Token);
2016-09-05 20:07:36 +00:00
2020-08-31 20:20:19 +00:00
await RecordFromFile(mediaSource, mediaSource.Path, targetFile, duration, onStarted, cancellationTokenSource.Token).ConfigureAwait(false);
_logger.LogInformation("Recording completed to file {0}", targetFile);
}
private async Task RecordFromFile(MediaSourceInfo mediaSource, string inputFile, string targetFile, TimeSpan duration, Action onStarted, CancellationToken cancellationToken)
{
2016-02-12 07:01:38 +00:00
_targetPath = targetFile;
Directory.CreateDirectory(Path.GetDirectoryName(targetFile));
2016-02-12 07:01:38 +00:00
var processStartInfo = new ProcessStartInfo
2016-02-12 07:01:38 +00:00
{
2016-11-03 23:35:19 +00:00
CreateNoWindow = true,
2016-11-30 19:50:39 +00:00
UseShellExecute = false,
2016-02-12 07:01:38 +00:00
2016-11-30 19:50:39 +00:00
RedirectStandardError = true,
RedirectStandardInput = true,
2016-02-12 07:01:38 +00:00
2016-11-03 23:35:19 +00:00
FileName = _mediaEncoder.EncoderPath,
Arguments = GetCommandLineArgs(mediaSource, inputFile, targetFile, duration),
2016-02-12 07:01:38 +00:00
WindowStyle = ProcessWindowStyle.Hidden,
ErrorDialog = false
};
2016-02-12 07:01:38 +00:00
var commandLineLogMessage = processStartInfo.FileName + " " + processStartInfo.Arguments;
_logger.LogInformation(commandLineLogMessage);
2016-02-12 07:01:38 +00:00
2016-11-30 19:50:39 +00:00
var logFilePath = Path.Combine(_appPaths.LogDirectoryPath, "record-transcode-" + Guid.NewGuid() + ".txt");
Directory.CreateDirectory(Path.GetDirectoryName(logFilePath));
2016-02-12 07:01:38 +00:00
2016-11-30 19:50:39 +00:00
// FFMpeg writes debug/error info to stderr. This is useful when debugging so let's put it in the log directory.
2021-03-09 16:31:31 +00:00
_logFileStream = new FileStream(logFilePath, FileMode.Create, FileAccess.Write, FileShare.Read, IODefaults.FileStreamBufferSize, true);
2016-11-30 19:50:39 +00:00
await JsonSerializer.SerializeAsync(_logFileStream, mediaSource, _jsonOptions, cancellationToken).ConfigureAwait(false);
2020-12-27 10:15:46 +00:00
await _logFileStream.WriteAsync(Encoding.UTF8.GetBytes(Environment.NewLine + Environment.NewLine + commandLineLogMessage + Environment.NewLine + Environment.NewLine), cancellationToken).ConfigureAwait(false);
2016-02-12 07:01:38 +00:00
_process = new Process
{
StartInfo = processStartInfo,
EnableRaisingEvents = true
};
2020-08-31 20:20:19 +00:00
_process.Exited += (sender, args) => OnFfMpegProcessExited(_process);
2016-02-12 07:01:38 +00:00
_process.Start();
2016-02-12 07:01:38 +00:00
cancellationToken.Register(Stop);
2016-02-29 16:25:21 +00:00
onStarted();
2016-11-30 19:50:39 +00:00
// Important - don't await the log task or we won't be able to kill ffmpeg when the user stops playback
2020-05-25 21:52:51 +00:00
_ = StartStreamingLog(_process.StandardError.BaseStream, _logFileStream);
2016-11-30 19:50:39 +00:00
_logger.LogInformation("ffmpeg recording process started for {0}", _targetPath);
2016-02-12 07:01:38 +00:00
}
2016-06-22 04:40:11 +00:00
private string GetCommandLineArgs(MediaSourceInfo mediaSource, string inputTempFile, string targetFile, TimeSpan duration)
2016-02-12 07:01:38 +00:00
{
string videoArgs;
if (EncodeVideo(mediaSource))
{
2019-08-29 20:28:33 +00:00
const int MaxBitrate = 25000000;
2016-02-12 07:01:38 +00:00
videoArgs = string.Format(
2019-08-29 20:28:33 +00:00
CultureInfo.InvariantCulture,
"-codec:v:0 libx264 -force_key_frames \"expr:gte(t,n_forced*5)\" {0} -pix_fmt yuv420p -preset superfast -crf 23 -b:v {1} -maxrate {1} -bufsize ({1}*2) -vsync -1 -profile:v high -level 41",
GetOutputSizeParam(),
MaxBitrate);
2016-02-12 07:01:38 +00:00
}
else
{
videoArgs = "-codec:v:0 copy";
}
2017-05-15 19:45:39 +00:00
videoArgs += " -fflags +genpts";
2017-05-02 12:53:21 +00:00
var flags = new List<string>();
if (mediaSource.IgnoreDts)
2017-04-21 20:03:07 +00:00
{
2017-05-02 12:53:21 +00:00
flags.Add("+igndts");
}
2019-08-29 20:28:33 +00:00
2017-05-02 12:53:21 +00:00
if (mediaSource.IgnoreIndex)
{
flags.Add("+ignidx");
2017-04-21 20:03:07 +00:00
}
2019-08-29 20:28:33 +00:00
2017-05-15 19:45:39 +00:00
if (mediaSource.GenPtsInput)
{
flags.Add("+genpts");
}
2017-04-21 20:03:07 +00:00
2017-05-21 07:25:49 +00:00
var inputModifier = "-async 1 -vsync -1";
2016-09-30 06:50:06 +00:00
2017-05-02 12:53:21 +00:00
if (flags.Count > 0)
{
2019-08-29 20:28:33 +00:00
inputModifier += " -fflags " + string.Join(string.Empty, flags);
2017-05-02 12:53:21 +00:00
}
2016-02-12 07:01:38 +00:00
2017-05-02 12:53:21 +00:00
if (mediaSource.ReadAtNativeFramerate)
2016-09-30 06:50:06 +00:00
{
2017-05-21 07:25:49 +00:00
inputModifier += " -re";
}
if (mediaSource.RequiresLooping)
{
2018-09-12 17:26:21 +00:00
inputModifier += " -stream_loop -1 -reconnect_at_eof 1 -reconnect_streamed 1 -reconnect_delay_max 2";
2016-02-12 07:01:38 +00:00
}
2016-11-09 17:25:33 +00:00
var analyzeDurationSeconds = 5;
var analyzeDuration = " -analyzeduration " +
(analyzeDurationSeconds * 1000000).ToString(CultureInfo.InvariantCulture);
2017-05-21 07:25:49 +00:00
inputModifier += analyzeDuration;
2016-11-09 17:25:33 +00:00
2017-02-21 18:04:35 +00:00
var subtitleArgs = CopySubtitles ? " -codec:s copy" : " -sn";
2020-06-14 09:11:11 +00:00
// var outputParam = string.Equals(Path.GetExtension(targetFile), ".mp4", StringComparison.OrdinalIgnoreCase) ?
// " -f mp4 -movflags frag_keyframe+empty_moov" :
// string.Empty;
var outputParam = string.Empty;
2017-03-26 04:22:30 +00:00
2020-11-17 13:46:23 +00:00
var threads = EncodingHelper.GetNumberOfThreads(null, _serverConfigurationManager.GetEncodingOptions(), null);
2019-08-29 20:28:33 +00:00
var commandLineArgs = string.Format(
CultureInfo.InvariantCulture,
2020-11-17 13:46:23 +00:00
"-i \"{0}\" {2} -map_metadata -1 -threads {6} {3}{4}{5} -y \"{1}\"",
2019-01-07 23:27:46 +00:00
inputTempFile,
targetFile,
videoArgs,
GetAudioArgs(mediaSource),
subtitleArgs,
2020-11-17 13:46:23 +00:00
outputParam,
threads);
2016-02-12 07:01:38 +00:00
2017-05-21 07:25:49 +00:00
return inputModifier + " " + commandLineArgs;
2016-02-12 07:01:38 +00:00
}
private static string GetAudioArgs(MediaSourceInfo mediaSource)
2016-02-12 07:01:38 +00:00
{
2018-09-12 17:26:21 +00:00
return "-codec:a:0 copy";
2016-02-12 07:01:38 +00:00
2020-06-14 09:11:11 +00:00
// var audioChannels = 2;
// var audioStream = mediaStreams.FirstOrDefault(i => i.Type == MediaStreamType.Audio);
// if (audioStream != null)
2018-09-12 17:26:21 +00:00
//{
// audioChannels = audioStream.Channels ?? audioChannels;
//}
2020-06-14 09:11:11 +00:00
// return "-codec:a:0 aac -strict experimental -ab 320000";
2016-02-12 07:01:38 +00:00
}
private static bool EncodeVideo(MediaSourceInfo mediaSource)
2016-02-12 07:01:38 +00:00
{
2018-09-12 17:26:21 +00:00
return false;
2016-02-12 07:01:38 +00:00
}
protected string GetOutputSizeParam()
2020-08-31 20:20:19 +00:00
=> "-vf \"yadif=0:-1:0\"";
2016-02-12 07:01:38 +00:00
private void Stop()
{
if (!_hasExited)
{
try
{
2018-12-20 12:11:26 +00:00
_logger.LogInformation("Stopping ffmpeg recording process for {path}", _targetPath);
2016-02-12 07:01:38 +00:00
2016-11-30 19:50:39 +00:00
_process.StandardInput.WriteLine("q");
2016-02-12 07:01:38 +00:00
}
catch (Exception ex)
{
2018-12-20 12:11:26 +00:00
_logger.LogError(ex, "Error stopping recording transcoding job for {path}", _targetPath);
2017-01-20 17:53:48 +00:00
}
if (_hasExited)
{
return;
}
try
{
2018-12-20 12:11:26 +00:00
_logger.LogInformation("Calling recording process.WaitForExit for {path}", _targetPath);
2017-01-20 17:53:48 +00:00
2017-02-17 21:11:13 +00:00
if (_process.WaitForExit(10000))
2017-01-20 17:53:48 +00:00
{
return;
}
}
catch (Exception ex)
{
2018-12-20 12:11:26 +00:00
_logger.LogError(ex, "Error waiting for recording process to exit for {path}", _targetPath);
2017-01-20 17:53:48 +00:00
}
if (_hasExited)
{
return;
}
try
{
2018-12-20 12:11:26 +00:00
_logger.LogInformation("Killing ffmpeg recording process for {path}", _targetPath);
2017-01-20 17:53:48 +00:00
_process.Kill();
}
catch (Exception ex)
{
2018-12-20 12:11:26 +00:00
_logger.LogError(ex, "Error killing recording transcoding job for {path}", _targetPath);
2016-02-12 07:01:38 +00:00
}
}
}
/// <summary>
/// Processes the exited.
/// </summary>
2020-08-31 20:20:19 +00:00
private void OnFfMpegProcessExited(Process process)
2016-02-12 07:01:38 +00:00
{
2020-04-11 17:46:31 +00:00
using (process)
{
_hasExited = true;
2016-02-12 07:01:38 +00:00
_logFileStream?.Dispose();
_logFileStream = null;
2016-11-30 19:50:39 +00:00
var exitCode = process.ExitCode;
2016-03-07 04:56:45 +00:00
_logger.LogInformation("FFMpeg recording exited with code {ExitCode} for {Path}", exitCode, _targetPath);
2016-03-07 04:56:45 +00:00
if (exitCode == 0)
{
_taskCompletionSource.TrySetResult(true);
}
else
{
_taskCompletionSource.TrySetException(
new Exception(
string.Format(
CultureInfo.InvariantCulture,
"Recording for {0} failed. Exit code {1}",
_targetPath,
exitCode)));
}
}
2016-11-30 19:50:39 +00:00
}
2020-05-25 21:52:51 +00:00
private async Task StartStreamingLog(Stream source, Stream target)
2016-11-30 19:50:39 +00:00
{
try
{
using (var reader = new StreamReader(source))
{
2021-01-08 22:57:27 +00:00
await foreach (var line in reader.ReadAllLinesAsync().ConfigureAwait(false))
2016-11-30 19:50:39 +00:00
{
var bytes = Encoding.UTF8.GetBytes(Environment.NewLine + line);
2021-01-08 22:57:27 +00:00
await target.WriteAsync(bytes.AsMemory()).ConfigureAwait(false);
2016-11-30 19:50:39 +00:00
await target.FlushAsync().ConfigureAwait(false);
}
}
}
catch (Exception ex)
{
2018-12-20 12:11:26 +00:00
_logger.LogError(ex, "Error reading ffmpeg recording log");
2016-11-30 19:50:39 +00:00
}
}
2016-02-12 07:01:38 +00:00
}
}