2020-11-18 08:23:45 -05:00
|
|
|
using System;
|
2020-06-26 23:04:02 -04:00
|
|
|
using System.Collections.Generic;
|
|
|
|
using System.Diagnostics;
|
2020-07-12 05:14:38 -04:00
|
|
|
using System.Globalization;
|
2020-06-26 23:04:02 -04:00
|
|
|
using System.IO;
|
|
|
|
using System.Linq;
|
2024-01-03 10:47:25 -05:00
|
|
|
using System.Runtime.CompilerServices;
|
2020-07-12 05:14:38 -04:00
|
|
|
using System.Text;
|
|
|
|
using System.Text.Json;
|
2020-06-26 23:04:02 -04:00
|
|
|
using System.Threading;
|
|
|
|
using System.Threading.Tasks;
|
2024-01-03 10:47:25 -05:00
|
|
|
using AsyncKeyedLock;
|
2020-07-12 05:14:38 -04:00
|
|
|
using Jellyfin.Data.Enums;
|
2024-01-17 10:51:39 -05:00
|
|
|
using Jellyfin.Extensions;
|
2021-10-10 12:48:48 -04:00
|
|
|
using MediaBrowser.Common;
|
2020-07-12 05:14:38 -04:00
|
|
|
using MediaBrowser.Common.Configuration;
|
2022-03-09 14:47:03 -05:00
|
|
|
using MediaBrowser.Common.Extensions;
|
2020-07-12 05:14:38 -04:00
|
|
|
using MediaBrowser.Controller.Configuration;
|
2020-06-26 23:04:02 -04:00
|
|
|
using MediaBrowser.Controller.Library;
|
|
|
|
using MediaBrowser.Controller.MediaEncoding;
|
2020-07-12 05:14:38 -04:00
|
|
|
using MediaBrowser.Controller.Session;
|
2023-10-31 13:26:37 -04:00
|
|
|
using MediaBrowser.Controller.Streaming;
|
2022-02-06 08:02:01 -05:00
|
|
|
using MediaBrowser.Model.Dlna;
|
2020-07-12 05:14:38 -04:00
|
|
|
using MediaBrowser.Model.Entities;
|
2020-06-26 23:04:02 -04:00
|
|
|
using MediaBrowser.Model.IO;
|
2020-07-12 05:14:38 -04:00
|
|
|
using MediaBrowser.Model.MediaInfo;
|
2020-07-11 05:14:23 -04:00
|
|
|
using MediaBrowser.Model.Session;
|
2020-06-26 23:04:02 -04:00
|
|
|
using Microsoft.Extensions.Logging;
|
|
|
|
|
2023-10-31 13:26:37 -04:00
|
|
|
namespace MediaBrowser.MediaEncoding.Transcoding;
|
2023-01-31 06:18:10 -05:00
|
|
|
|
2023-10-31 13:26:37 -04:00
|
|
|
/// <inheritdoc cref="ITranscodeManager"/>
|
|
|
|
public sealed class TranscodeManager : ITranscodeManager, IDisposable
|
2020-06-26 23:04:02 -04:00
|
|
|
{
|
2023-10-31 13:26:37 -04:00
|
|
|
private readonly ILoggerFactory _loggerFactory;
|
|
|
|
private readonly ILogger<TranscodeManager> _logger;
|
|
|
|
private readonly IFileSystem _fileSystem;
|
2023-01-31 06:18:10 -05:00
|
|
|
private readonly IApplicationPaths _appPaths;
|
2023-10-31 13:26:37 -04:00
|
|
|
private readonly IServerConfigurationManager _serverConfigurationManager;
|
|
|
|
private readonly IUserManager _userManager;
|
|
|
|
private readonly ISessionManager _sessionManager;
|
2023-01-31 06:18:10 -05:00
|
|
|
private readonly EncodingHelper _encodingHelper;
|
|
|
|
private readonly IMediaEncoder _mediaEncoder;
|
|
|
|
private readonly IMediaSourceManager _mediaSourceManager;
|
2023-10-31 13:26:37 -04:00
|
|
|
private readonly IAttachmentExtractor _attachmentExtractor;
|
|
|
|
|
|
|
|
private readonly List<TranscodingJob> _activeTranscodingJobs = new();
|
2024-01-03 10:47:25 -05:00
|
|
|
private readonly AsyncKeyedLocker<string> _transcodingLocks = new(o =>
|
|
|
|
{
|
|
|
|
o.PoolSize = 20;
|
|
|
|
o.PoolInitialFill = 1;
|
|
|
|
});
|
2023-01-31 06:18:10 -05:00
|
|
|
|
|
|
|
/// <summary>
|
2023-10-31 13:26:37 -04:00
|
|
|
/// Initializes a new instance of the <see cref="TranscodeManager"/> class.
|
2023-01-31 06:18:10 -05:00
|
|
|
/// </summary>
|
2023-10-31 13:26:37 -04:00
|
|
|
/// <param name="loggerFactory">The <see cref="ILoggerFactory"/>.</param>
|
|
|
|
/// <param name="fileSystem">The <see cref="IFileSystem"/>.</param>
|
|
|
|
/// <param name="appPaths">The <see cref="IApplicationPaths"/>.</param>
|
|
|
|
/// <param name="serverConfigurationManager">The <see cref="IServerConfigurationManager"/>.</param>
|
|
|
|
/// <param name="userManager">The <see cref="IUserManager"/>.</param>
|
|
|
|
/// <param name="sessionManager">The <see cref="ISessionManager"/>.</param>
|
|
|
|
/// <param name="encodingHelper">The <see cref="EncodingHelper"/>.</param>
|
|
|
|
/// <param name="mediaEncoder">The <see cref="IMediaEncoder"/>.</param>
|
|
|
|
/// <param name="mediaSourceManager">The <see cref="IMediaSourceManager"/>.</param>
|
|
|
|
/// <param name="attachmentExtractor">The <see cref="IAttachmentExtractor"/>.</param>
|
|
|
|
public TranscodeManager(
|
|
|
|
ILoggerFactory loggerFactory,
|
2023-01-31 06:18:10 -05:00
|
|
|
IFileSystem fileSystem,
|
2023-10-31 13:26:37 -04:00
|
|
|
IApplicationPaths appPaths,
|
2023-01-31 06:18:10 -05:00
|
|
|
IServerConfigurationManager serverConfigurationManager,
|
2023-10-31 13:26:37 -04:00
|
|
|
IUserManager userManager,
|
2023-01-31 06:18:10 -05:00
|
|
|
ISessionManager sessionManager,
|
|
|
|
EncodingHelper encodingHelper,
|
2023-10-31 13:26:37 -04:00
|
|
|
IMediaEncoder mediaEncoder,
|
|
|
|
IMediaSourceManager mediaSourceManager,
|
|
|
|
IAttachmentExtractor attachmentExtractor)
|
2020-06-26 23:04:02 -04:00
|
|
|
{
|
2023-10-31 13:26:37 -04:00
|
|
|
_loggerFactory = loggerFactory;
|
2023-01-31 06:18:10 -05:00
|
|
|
_fileSystem = fileSystem;
|
2023-10-31 13:26:37 -04:00
|
|
|
_appPaths = appPaths;
|
2023-01-31 06:18:10 -05:00
|
|
|
_serverConfigurationManager = serverConfigurationManager;
|
2023-10-31 13:26:37 -04:00
|
|
|
_userManager = userManager;
|
2023-01-31 06:18:10 -05:00
|
|
|
_sessionManager = sessionManager;
|
|
|
|
_encodingHelper = encodingHelper;
|
2023-10-31 13:26:37 -04:00
|
|
|
_mediaEncoder = mediaEncoder;
|
|
|
|
_mediaSourceManager = mediaSourceManager;
|
|
|
|
_attachmentExtractor = attachmentExtractor;
|
2023-01-31 06:18:10 -05:00
|
|
|
|
2023-10-31 13:26:37 -04:00
|
|
|
_logger = loggerFactory.CreateLogger<TranscodeManager>();
|
2023-01-31 06:18:10 -05:00
|
|
|
DeleteEncodedMediaCache();
|
2023-10-31 13:26:37 -04:00
|
|
|
_sessionManager.PlaybackProgress += OnPlaybackProgress;
|
|
|
|
_sessionManager.PlaybackStart += OnPlaybackProgress;
|
2023-01-31 06:18:10 -05:00
|
|
|
}
|
2020-06-26 23:04:02 -04:00
|
|
|
|
2023-10-31 13:26:37 -04:00
|
|
|
/// <inheritdoc />
|
2023-10-31 11:31:09 -04:00
|
|
|
public TranscodingJob? GetTranscodingJob(string playSessionId)
|
2023-01-31 06:18:10 -05:00
|
|
|
{
|
|
|
|
lock (_activeTranscodingJobs)
|
2020-07-11 05:14:23 -04:00
|
|
|
{
|
2023-01-31 06:18:10 -05:00
|
|
|
return _activeTranscodingJobs.FirstOrDefault(j => string.Equals(j.PlaySessionId, playSessionId, StringComparison.OrdinalIgnoreCase));
|
2020-07-11 05:14:23 -04:00
|
|
|
}
|
2023-01-31 06:18:10 -05:00
|
|
|
}
|
2020-07-11 05:14:23 -04:00
|
|
|
|
2023-10-31 13:26:37 -04:00
|
|
|
/// <inheritdoc />
|
2023-10-31 11:31:09 -04:00
|
|
|
public TranscodingJob? GetTranscodingJob(string path, TranscodingJobType type)
|
2023-01-31 06:18:10 -05:00
|
|
|
{
|
|
|
|
lock (_activeTranscodingJobs)
|
2020-06-26 23:04:02 -04:00
|
|
|
{
|
2023-01-31 06:18:10 -05:00
|
|
|
return _activeTranscodingJobs.FirstOrDefault(j => j.Type == type && string.Equals(j.Path, path, StringComparison.OrdinalIgnoreCase));
|
|
|
|
}
|
|
|
|
}
|
2020-06-26 23:04:02 -04:00
|
|
|
|
2023-10-31 13:26:37 -04:00
|
|
|
/// <inheritdoc />
|
2023-01-31 06:18:10 -05:00
|
|
|
public void PingTranscodingJob(string playSessionId, bool? isUserPaused)
|
|
|
|
{
|
|
|
|
ArgumentException.ThrowIfNullOrEmpty(playSessionId);
|
2020-06-26 23:04:02 -04:00
|
|
|
|
2023-01-31 06:18:10 -05:00
|
|
|
_logger.LogDebug("PingTranscodingJob PlaySessionId={0} isUsedPaused: {1}", playSessionId, isUserPaused);
|
2020-06-26 23:04:02 -04:00
|
|
|
|
2023-10-31 11:31:09 -04:00
|
|
|
List<TranscodingJob> jobs;
|
2020-06-26 23:04:02 -04:00
|
|
|
|
2023-01-31 06:18:10 -05:00
|
|
|
lock (_activeTranscodingJobs)
|
|
|
|
{
|
|
|
|
// This is really only needed for HLS.
|
|
|
|
// Progressive streams can stop on their own reliably.
|
|
|
|
jobs = _activeTranscodingJobs.Where(j => string.Equals(playSessionId, j.PlaySessionId, StringComparison.OrdinalIgnoreCase)).ToList();
|
|
|
|
}
|
|
|
|
|
|
|
|
foreach (var job in jobs)
|
|
|
|
{
|
|
|
|
if (isUserPaused.HasValue)
|
2020-06-26 23:04:02 -04:00
|
|
|
{
|
2023-01-31 06:18:10 -05:00
|
|
|
_logger.LogDebug("Setting job.IsUserPaused to {0}. jobId: {1}", isUserPaused, job.Id);
|
|
|
|
job.IsUserPaused = isUserPaused.Value;
|
2020-06-26 23:04:02 -04:00
|
|
|
}
|
|
|
|
|
2023-01-31 06:18:10 -05:00
|
|
|
PingTimer(job, true);
|
|
|
|
}
|
|
|
|
}
|
2020-06-26 23:04:02 -04:00
|
|
|
|
2023-10-31 11:31:09 -04:00
|
|
|
private void PingTimer(TranscodingJob job, bool isProgressCheckIn)
|
2023-01-31 06:18:10 -05:00
|
|
|
{
|
|
|
|
if (job.HasExited)
|
|
|
|
{
|
|
|
|
job.StopKillTimer();
|
|
|
|
return;
|
2020-06-26 23:04:02 -04:00
|
|
|
}
|
|
|
|
|
2023-01-31 06:18:10 -05:00
|
|
|
var timerDuration = 10000;
|
|
|
|
|
|
|
|
if (job.Type != TranscodingJobType.Progressive)
|
2020-06-26 23:04:02 -04:00
|
|
|
{
|
2023-01-31 06:18:10 -05:00
|
|
|
timerDuration = 60000;
|
|
|
|
}
|
2020-06-26 23:04:02 -04:00
|
|
|
|
2023-01-31 06:18:10 -05:00
|
|
|
job.PingTimeout = timerDuration;
|
|
|
|
job.LastPingDate = DateTime.UtcNow;
|
2020-06-26 23:04:02 -04:00
|
|
|
|
2023-01-31 06:18:10 -05:00
|
|
|
// Don't start the timer for playback checkins with progressive streaming
|
|
|
|
if (job.Type != TranscodingJobType.Progressive || !isProgressCheckIn)
|
|
|
|
{
|
|
|
|
job.StartKillTimer(OnTranscodeKillTimerStopped);
|
|
|
|
}
|
|
|
|
else
|
|
|
|
{
|
|
|
|
job.ChangeKillTimerIfStarted();
|
|
|
|
}
|
|
|
|
}
|
2020-06-26 23:04:02 -04:00
|
|
|
|
2023-01-31 06:18:10 -05:00
|
|
|
private async void OnTranscodeKillTimerStopped(object? state)
|
|
|
|
{
|
2023-10-31 11:31:09 -04:00
|
|
|
var job = state as TranscodingJob ?? throw new ArgumentException($"{nameof(state)} is not of type {nameof(TranscodingJob)}", nameof(state));
|
2023-01-31 06:18:10 -05:00
|
|
|
if (!job.HasExited && job.Type != TranscodingJobType.Progressive)
|
|
|
|
{
|
|
|
|
var timeSinceLastPing = (DateTime.UtcNow - job.LastPingDate).TotalMilliseconds;
|
2020-06-26 23:04:02 -04:00
|
|
|
|
2023-01-31 06:18:10 -05:00
|
|
|
if (timeSinceLastPing < job.PingTimeout)
|
2020-06-26 23:04:02 -04:00
|
|
|
{
|
2023-01-31 06:18:10 -05:00
|
|
|
job.StartKillTimer(OnTranscodeKillTimerStopped, job.PingTimeout);
|
|
|
|
return;
|
2020-06-26 23:04:02 -04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-01-31 06:18:10 -05:00
|
|
|
_logger.LogInformation("Transcoding kill timer stopped for JobId {0} PlaySessionId {1}. Killing transcoding", job.Id, job.PlaySessionId);
|
2020-06-26 23:04:02 -04:00
|
|
|
|
2023-01-31 06:18:10 -05:00
|
|
|
await KillTranscodingJob(job, true, path => true).ConfigureAwait(false);
|
|
|
|
}
|
2020-06-26 23:04:02 -04:00
|
|
|
|
2023-10-31 13:26:37 -04:00
|
|
|
/// <inheritdoc />
|
2023-01-31 06:18:10 -05:00
|
|
|
public Task KillTranscodingJobs(string deviceId, string? playSessionId, Func<string, bool> deleteFiles)
|
|
|
|
{
|
2023-10-31 11:31:09 -04:00
|
|
|
var jobs = new List<TranscodingJob>();
|
2020-06-26 23:04:02 -04:00
|
|
|
|
2023-01-31 06:18:10 -05:00
|
|
|
lock (_activeTranscodingJobs)
|
2020-06-26 23:04:02 -04:00
|
|
|
{
|
2023-01-31 06:18:10 -05:00
|
|
|
// This is really only needed for HLS.
|
|
|
|
// Progressive streams can stop on their own reliably.
|
2023-10-31 13:26:37 -04:00
|
|
|
jobs.AddRange(_activeTranscodingJobs.Where(j => string.IsNullOrWhiteSpace(playSessionId)
|
|
|
|
? string.Equals(deviceId, j.DeviceId, StringComparison.OrdinalIgnoreCase)
|
|
|
|
: string.Equals(playSessionId, j.PlaySessionId, StringComparison.OrdinalIgnoreCase)));
|
2020-06-26 23:04:02 -04:00
|
|
|
}
|
|
|
|
|
2023-10-31 13:26:37 -04:00
|
|
|
return Task.WhenAll(GetKillJobs());
|
2020-06-26 23:04:02 -04:00
|
|
|
|
2023-01-31 06:18:10 -05:00
|
|
|
IEnumerable<Task> GetKillJobs()
|
2020-06-26 23:04:02 -04:00
|
|
|
{
|
2023-01-31 06:18:10 -05:00
|
|
|
foreach (var job in jobs)
|
2020-06-26 23:04:02 -04:00
|
|
|
{
|
2023-01-31 06:18:10 -05:00
|
|
|
yield return KillTranscodingJob(job, false, deleteFiles);
|
2020-06-26 23:04:02 -04:00
|
|
|
}
|
2023-01-31 06:18:10 -05:00
|
|
|
}
|
|
|
|
}
|
2020-06-26 23:04:02 -04:00
|
|
|
|
2023-10-31 11:31:09 -04:00
|
|
|
private async Task KillTranscodingJob(TranscodingJob job, bool closeLiveStream, Func<string, bool> delete)
|
2023-01-31 06:18:10 -05:00
|
|
|
{
|
|
|
|
job.DisposeKillTimer();
|
2020-06-26 23:04:02 -04:00
|
|
|
|
2023-01-31 06:18:10 -05:00
|
|
|
_logger.LogDebug("KillTranscodingJob - JobId {0} PlaySessionId {1}. Killing transcoding", job.Id, job.PlaySessionId);
|
2020-06-26 23:04:02 -04:00
|
|
|
|
2023-01-31 06:18:10 -05:00
|
|
|
lock (_activeTranscodingJobs)
|
2020-06-26 23:04:02 -04:00
|
|
|
{
|
2023-01-31 06:18:10 -05:00
|
|
|
_activeTranscodingJobs.Remove(job);
|
2020-06-26 23:04:02 -04:00
|
|
|
|
2023-01-31 06:18:10 -05:00
|
|
|
if (job.CancellationTokenSource?.IsCancellationRequested == false)
|
2020-06-26 23:04:02 -04:00
|
|
|
{
|
2023-10-23 18:10:31 -04:00
|
|
|
#pragma warning disable CA1849 // Can't await in lock block
|
2023-01-31 06:18:10 -05:00
|
|
|
job.CancellationTokenSource.Cancel();
|
2023-10-31 11:31:09 -04:00
|
|
|
#pragma warning restore CA1849
|
2020-06-26 23:04:02 -04:00
|
|
|
}
|
2023-01-31 06:18:10 -05:00
|
|
|
}
|
2020-06-26 23:04:02 -04:00
|
|
|
|
2023-10-31 11:31:09 -04:00
|
|
|
job.Stop();
|
2020-06-26 23:04:02 -04:00
|
|
|
|
2023-01-31 06:18:10 -05:00
|
|
|
if (delete(job.Path!))
|
|
|
|
{
|
|
|
|
await DeletePartialStreamFiles(job.Path!, job.Type, 0, 1500).ConfigureAwait(false);
|
2023-02-03 18:08:51 -05:00
|
|
|
if (job.MediaSource?.VideoType == VideoType.Dvd || job.MediaSource?.VideoType == VideoType.BluRay)
|
2020-06-26 23:04:02 -04:00
|
|
|
{
|
2023-02-16 18:26:03 -05:00
|
|
|
var concatFilePath = Path.Join(_serverConfigurationManager.GetTranscodePath(), job.MediaSource.Id + ".concat");
|
|
|
|
if (File.Exists(concatFilePath))
|
2020-06-26 23:04:02 -04:00
|
|
|
{
|
2023-02-16 18:26:03 -05:00
|
|
|
_logger.LogInformation("Deleting ffmpeg concat configuration at {Path}", concatFilePath);
|
2023-02-18 08:42:35 -05:00
|
|
|
File.Delete(concatFilePath);
|
2020-06-26 23:04:02 -04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-01-31 06:18:10 -05:00
|
|
|
if (closeLiveStream && !string.IsNullOrWhiteSpace(job.LiveStreamId))
|
2020-06-26 23:04:02 -04:00
|
|
|
{
|
2023-01-31 06:18:10 -05:00
|
|
|
try
|
2020-06-26 23:04:02 -04:00
|
|
|
{
|
2023-01-31 06:18:10 -05:00
|
|
|
await _mediaSourceManager.CloseLiveStream(job.LiveStreamId).ConfigureAwait(false);
|
2020-06-26 23:04:02 -04:00
|
|
|
}
|
2023-01-31 06:18:10 -05:00
|
|
|
catch (Exception ex)
|
2020-06-26 23:04:02 -04:00
|
|
|
{
|
2023-01-31 06:18:10 -05:00
|
|
|
_logger.LogError(ex, "Error closing live stream for {Path}", job.Path);
|
2020-06-26 23:04:02 -04:00
|
|
|
}
|
|
|
|
}
|
2023-01-31 06:18:10 -05:00
|
|
|
}
|
2020-06-26 23:04:02 -04:00
|
|
|
|
2023-01-31 06:18:10 -05:00
|
|
|
private async Task DeletePartialStreamFiles(string path, TranscodingJobType jobType, int retryCount, int delayMs)
|
|
|
|
{
|
|
|
|
if (retryCount >= 10)
|
2020-06-26 23:04:02 -04:00
|
|
|
{
|
2023-01-31 06:18:10 -05:00
|
|
|
return;
|
|
|
|
}
|
2020-06-26 23:04:02 -04:00
|
|
|
|
2023-01-31 06:18:10 -05:00
|
|
|
_logger.LogInformation("Deleting partial stream file(s) {Path}", path);
|
2020-06-26 23:04:02 -04:00
|
|
|
|
2023-01-31 06:18:10 -05:00
|
|
|
await Task.Delay(delayMs).ConfigureAwait(false);
|
2020-06-26 23:04:02 -04:00
|
|
|
|
2023-01-31 06:18:10 -05:00
|
|
|
try
|
|
|
|
{
|
|
|
|
if (jobType == TranscodingJobType.Progressive)
|
2020-06-26 23:04:02 -04:00
|
|
|
{
|
2023-01-31 06:18:10 -05:00
|
|
|
DeleteProgressivePartialStreamFiles(path);
|
2020-06-26 23:04:02 -04:00
|
|
|
}
|
2023-01-31 06:18:10 -05:00
|
|
|
else
|
2020-06-26 23:04:02 -04:00
|
|
|
{
|
2023-01-31 06:18:10 -05:00
|
|
|
DeleteHlsPartialStreamFiles(path);
|
2020-06-26 23:04:02 -04:00
|
|
|
}
|
|
|
|
}
|
2023-01-31 06:18:10 -05:00
|
|
|
catch (IOException ex)
|
|
|
|
{
|
|
|
|
_logger.LogError(ex, "Error deleting partial stream file(s) {Path}", path);
|
2020-06-26 23:04:02 -04:00
|
|
|
|
2023-01-31 06:18:10 -05:00
|
|
|
await DeletePartialStreamFiles(path, jobType, retryCount + 1, 500).ConfigureAwait(false);
|
|
|
|
}
|
|
|
|
catch (Exception ex)
|
2020-06-26 23:04:02 -04:00
|
|
|
{
|
2023-01-31 06:18:10 -05:00
|
|
|
_logger.LogError(ex, "Error deleting partial stream file(s) {Path}", path);
|
2020-06-26 23:04:02 -04:00
|
|
|
}
|
2023-01-31 06:18:10 -05:00
|
|
|
}
|
2020-06-26 23:04:02 -04:00
|
|
|
|
2023-01-31 06:18:10 -05:00
|
|
|
private void DeleteProgressivePartialStreamFiles(string outputFilePath)
|
|
|
|
{
|
|
|
|
if (File.Exists(outputFilePath))
|
2020-06-26 23:04:02 -04:00
|
|
|
{
|
2023-01-31 06:18:10 -05:00
|
|
|
_fileSystem.DeleteFile(outputFilePath);
|
|
|
|
}
|
|
|
|
}
|
2021-05-20 15:28:18 -04:00
|
|
|
|
2023-01-31 06:18:10 -05:00
|
|
|
private void DeleteHlsPartialStreamFiles(string outputFilePath)
|
|
|
|
{
|
|
|
|
var directory = Path.GetDirectoryName(outputFilePath)
|
|
|
|
?? throw new ArgumentException("Path can't be a root directory.", nameof(outputFilePath));
|
2020-06-26 23:04:02 -04:00
|
|
|
|
2023-01-31 06:18:10 -05:00
|
|
|
var name = Path.GetFileNameWithoutExtension(outputFilePath);
|
2020-06-26 23:04:02 -04:00
|
|
|
|
2023-01-31 06:18:10 -05:00
|
|
|
var filesToDelete = _fileSystem.GetFilePaths(directory)
|
2023-11-14 14:21:34 -05:00
|
|
|
.Where(f => f.Contains(name, StringComparison.OrdinalIgnoreCase));
|
2020-06-26 23:04:02 -04:00
|
|
|
|
2023-01-31 06:18:10 -05:00
|
|
|
List<Exception>? exs = null;
|
|
|
|
foreach (var file in filesToDelete)
|
|
|
|
{
|
|
|
|
try
|
2020-06-26 23:04:02 -04:00
|
|
|
{
|
2023-01-31 06:18:10 -05:00
|
|
|
_logger.LogDebug("Deleting HLS file {0}", file);
|
|
|
|
_fileSystem.DeleteFile(file);
|
2020-06-26 23:04:02 -04:00
|
|
|
}
|
2023-01-31 06:18:10 -05:00
|
|
|
catch (IOException ex)
|
2020-06-26 23:04:02 -04:00
|
|
|
{
|
2023-01-31 06:18:10 -05:00
|
|
|
(exs ??= new List<Exception>(4)).Add(ex);
|
|
|
|
_logger.LogError(ex, "Error deleting HLS file {Path}", file);
|
2020-06-26 23:04:02 -04:00
|
|
|
}
|
|
|
|
}
|
2020-07-11 05:14:23 -04:00
|
|
|
|
2023-01-31 06:18:10 -05:00
|
|
|
if (exs is not null)
|
|
|
|
{
|
|
|
|
throw new AggregateException("Error deleting HLS files", exs);
|
|
|
|
}
|
|
|
|
}
|
2020-07-11 05:14:23 -04:00
|
|
|
|
2023-10-31 13:26:37 -04:00
|
|
|
/// <inheritdoc />
|
2023-01-31 06:18:10 -05:00
|
|
|
public void ReportTranscodingProgress(
|
2023-10-31 11:31:09 -04:00
|
|
|
TranscodingJob job,
|
2023-01-31 06:18:10 -05:00
|
|
|
StreamState state,
|
|
|
|
TimeSpan? transcodingPosition,
|
|
|
|
float? framerate,
|
|
|
|
double? percentComplete,
|
|
|
|
long? bytesTranscoded,
|
|
|
|
int? bitRate)
|
|
|
|
{
|
|
|
|
var ticks = transcodingPosition?.Ticks;
|
2020-07-11 05:14:23 -04:00
|
|
|
|
2023-01-31 06:18:10 -05:00
|
|
|
if (job is not null)
|
|
|
|
{
|
|
|
|
job.Framerate = framerate;
|
|
|
|
job.CompletionPercentage = percentComplete;
|
|
|
|
job.TranscodingPositionTicks = ticks;
|
|
|
|
job.BytesTranscoded = bytesTranscoded;
|
|
|
|
job.BitRate = bitRate;
|
|
|
|
}
|
2020-07-11 05:14:23 -04:00
|
|
|
|
2023-01-31 06:18:10 -05:00
|
|
|
var deviceId = state.Request.DeviceId;
|
2020-07-11 05:14:23 -04:00
|
|
|
|
2023-01-31 06:18:10 -05:00
|
|
|
if (!string.IsNullOrWhiteSpace(deviceId))
|
|
|
|
{
|
|
|
|
var audioCodec = state.ActualOutputAudioCodec;
|
|
|
|
var videoCodec = state.ActualOutputVideoCodec;
|
|
|
|
var hardwareAccelerationTypeString = _serverConfigurationManager.GetEncodingOptions().HardwareAccelerationType;
|
|
|
|
HardwareEncodingType? hardwareAccelerationType = null;
|
2023-02-19 10:52:29 -05:00
|
|
|
if (Enum.TryParse<HardwareEncodingType>(hardwareAccelerationTypeString, out var parsedHardwareAccelerationType))
|
2023-01-31 06:18:10 -05:00
|
|
|
{
|
|
|
|
hardwareAccelerationType = parsedHardwareAccelerationType;
|
|
|
|
}
|
|
|
|
|
|
|
|
_sessionManager.ReportTranscodingInfo(deviceId, new TranscodingInfo
|
|
|
|
{
|
|
|
|
Bitrate = bitRate ?? state.TotalOutputBitrate,
|
|
|
|
AudioCodec = audioCodec,
|
|
|
|
VideoCodec = videoCodec,
|
|
|
|
Container = state.OutputContainer,
|
|
|
|
Framerate = framerate,
|
|
|
|
CompletionPercentage = percentComplete,
|
|
|
|
Width = state.OutputWidth,
|
|
|
|
Height = state.OutputHeight,
|
|
|
|
AudioChannels = state.OutputAudioChannels,
|
|
|
|
IsAudioDirect = EncodingHelper.IsCopyCodec(state.OutputAudioCodec),
|
|
|
|
IsVideoDirect = EncodingHelper.IsCopyCodec(state.OutputVideoCodec),
|
|
|
|
HardwareAccelerationType = hardwareAccelerationType,
|
|
|
|
TranscodeReasons = state.TranscodeReasons
|
|
|
|
});
|
2020-07-11 05:14:23 -04:00
|
|
|
}
|
2023-01-31 06:18:10 -05:00
|
|
|
}
|
2020-07-12 05:14:38 -04:00
|
|
|
|
2023-10-31 13:26:37 -04:00
|
|
|
/// <inheritdoc />
|
2023-10-31 11:31:09 -04:00
|
|
|
public async Task<TranscodingJob> StartFfMpeg(
|
2023-01-31 06:18:10 -05:00
|
|
|
StreamState state,
|
|
|
|
string outputPath,
|
|
|
|
string commandLineArguments,
|
2023-10-31 13:26:37 -04:00
|
|
|
Guid userId,
|
2023-01-31 06:18:10 -05:00
|
|
|
TranscodingJobType transcodingJobType,
|
|
|
|
CancellationTokenSource cancellationTokenSource,
|
|
|
|
string? workingDirectory = null)
|
|
|
|
{
|
|
|
|
var directory = Path.GetDirectoryName(outputPath) ?? throw new ArgumentException($"Provided path ({outputPath}) is not valid.", nameof(outputPath));
|
|
|
|
Directory.CreateDirectory(directory);
|
2020-07-12 05:14:38 -04:00
|
|
|
|
2023-01-31 06:18:10 -05:00
|
|
|
await AcquireResources(state, cancellationTokenSource).ConfigureAwait(false);
|
2020-07-12 05:14:38 -04:00
|
|
|
|
2023-01-31 06:18:10 -05:00
|
|
|
if (state.VideoRequest is not null && !EncodingHelper.IsCopyCodec(state.OutputVideoCodec))
|
|
|
|
{
|
2024-01-17 10:51:39 -05:00
|
|
|
var user = userId.IsEmpty() ? null : _userManager.GetUserById(userId);
|
2023-01-31 06:18:10 -05:00
|
|
|
if (user is not null && !user.HasPermission(PermissionKind.EnableVideoPlaybackTranscoding))
|
2020-09-19 11:44:35 -04:00
|
|
|
{
|
2024-02-10 10:52:21 -05:00
|
|
|
OnTranscodeFailedToStart(outputPath, transcodingJobType, state);
|
2022-03-09 14:47:03 -05:00
|
|
|
|
2023-01-31 06:18:10 -05:00
|
|
|
throw new ArgumentException("User does not have access to video transcoding.");
|
2020-09-19 11:44:35 -04:00
|
|
|
}
|
2023-01-31 06:18:10 -05:00
|
|
|
}
|
2020-09-19 11:44:35 -04:00
|
|
|
|
2023-01-31 06:18:10 -05:00
|
|
|
ArgumentException.ThrowIfNullOrEmpty(_mediaEncoder.EncoderPath);
|
|
|
|
|
|
|
|
// If subtitles get burned in fonts may need to be extracted from the media file
|
|
|
|
if (state.SubtitleStream is not null && state.SubtitleDeliveryMethod == SubtitleDeliveryMethod.Encode)
|
|
|
|
{
|
|
|
|
var attachmentPath = Path.Combine(_appPaths.CachePath, "attachments", state.MediaSource.Id);
|
2024-02-10 10:52:21 -05:00
|
|
|
if (state.MediaSource.VideoType == VideoType.Dvd || state.MediaSource.VideoType == VideoType.BluRay)
|
|
|
|
{
|
|
|
|
var concatPath = Path.Join(_serverConfigurationManager.GetTranscodePath(), state.MediaSource.Id + ".concat");
|
|
|
|
await _attachmentExtractor.ExtractAllAttachments(concatPath, state.MediaSource, attachmentPath, cancellationTokenSource.Token).ConfigureAwait(false);
|
|
|
|
}
|
|
|
|
else
|
2022-02-06 08:02:01 -05:00
|
|
|
{
|
2022-03-12 04:19:57 -05:00
|
|
|
await _attachmentExtractor.ExtractAllAttachments(state.MediaPath, state.MediaSource, attachmentPath, cancellationTokenSource.Token).ConfigureAwait(false);
|
2022-02-06 08:02:01 -05:00
|
|
|
}
|
|
|
|
|
2023-10-05 18:40:09 -04:00
|
|
|
if (state.SubtitleStream.IsExternal && Path.GetExtension(state.SubtitleStream.Path.AsSpan()).Equals(".mks", StringComparison.OrdinalIgnoreCase))
|
2020-07-12 05:14:38 -04:00
|
|
|
{
|
2023-01-31 06:18:10 -05:00
|
|
|
string subtitlePath = state.SubtitleStream.Path;
|
|
|
|
string subtitlePathArgument = string.Format(CultureInfo.InvariantCulture, "file:\"{0}\"", subtitlePath.Replace("\"", "\\\"", StringComparison.Ordinal));
|
|
|
|
string subtitleId = subtitlePath.GetMD5().ToString("N", CultureInfo.InvariantCulture);
|
2020-07-12 05:14:38 -04:00
|
|
|
|
2023-01-31 06:18:10 -05:00
|
|
|
await _attachmentExtractor.ExtractAllAttachmentsExternal(subtitlePathArgument, subtitleId, attachmentPath, cancellationTokenSource.Token).ConfigureAwait(false);
|
2020-07-12 05:14:38 -04:00
|
|
|
}
|
2023-01-31 06:18:10 -05:00
|
|
|
}
|
2020-07-12 05:14:38 -04:00
|
|
|
|
2024-02-10 10:52:21 -05:00
|
|
|
using var process = new Process
|
2023-01-31 06:18:10 -05:00
|
|
|
{
|
|
|
|
StartInfo = new ProcessStartInfo
|
|
|
|
{
|
|
|
|
WindowStyle = ProcessWindowStyle.Hidden,
|
|
|
|
CreateNoWindow = true,
|
|
|
|
UseShellExecute = false,
|
|
|
|
|
|
|
|
// Must consume both stdout and stderr or deadlocks may occur
|
|
|
|
// RedirectStandardOutput = true,
|
|
|
|
RedirectStandardError = true,
|
|
|
|
RedirectStandardInput = true,
|
|
|
|
FileName = _mediaEncoder.EncoderPath,
|
|
|
|
Arguments = commandLineArguments,
|
|
|
|
WorkingDirectory = string.IsNullOrWhiteSpace(workingDirectory) ? string.Empty : workingDirectory,
|
|
|
|
ErrorDialog = false
|
|
|
|
},
|
|
|
|
EnableRaisingEvents = true
|
|
|
|
};
|
|
|
|
|
2024-02-10 10:52:21 -05:00
|
|
|
var transcodingJob = OnTranscodeBeginning(
|
2023-01-31 06:18:10 -05:00
|
|
|
outputPath,
|
|
|
|
state.Request.PlaySessionId,
|
|
|
|
state.MediaSource.LiveStreamId,
|
|
|
|
Guid.NewGuid().ToString("N", CultureInfo.InvariantCulture),
|
|
|
|
transcodingJobType,
|
|
|
|
process,
|
|
|
|
state.Request.DeviceId,
|
|
|
|
state,
|
|
|
|
cancellationTokenSource);
|
|
|
|
|
|
|
|
_logger.LogInformation("{Filename} {Arguments}", process.StartInfo.FileName, process.StartInfo.Arguments);
|
|
|
|
|
|
|
|
var logFilePrefix = "FFmpeg.Transcode-";
|
|
|
|
if (state.VideoRequest is not null
|
|
|
|
&& EncodingHelper.IsCopyCodec(state.OutputVideoCodec))
|
|
|
|
{
|
|
|
|
logFilePrefix = EncodingHelper.IsCopyCodec(state.OutputAudioCodec)
|
|
|
|
? "FFmpeg.Remux-"
|
|
|
|
: "FFmpeg.DirectStream-";
|
|
|
|
}
|
2020-07-12 05:14:38 -04:00
|
|
|
|
2023-01-31 06:18:10 -05:00
|
|
|
var logFilePath = Path.Combine(
|
|
|
|
_serverConfigurationManager.ApplicationPaths.LogDirectoryPath,
|
|
|
|
$"{logFilePrefix}{DateTime.Now:yyyy-MM-dd_HH-mm-ss}_{state.Request.MediaSourceId}_{Guid.NewGuid().ToString()[..8]}.log");
|
2020-07-12 05:14:38 -04:00
|
|
|
|
2023-01-31 06:18:10 -05:00
|
|
|
// FFmpeg writes debug/error info to stderr. This is useful when debugging so let's put it in the log directory.
|
2023-10-31 13:26:37 -04:00
|
|
|
Stream logStream = new FileStream(
|
|
|
|
logFilePath,
|
|
|
|
FileMode.Create,
|
|
|
|
FileAccess.Write,
|
|
|
|
FileShare.Read,
|
|
|
|
IODefaults.FileStreamBufferSize,
|
|
|
|
FileOptions.Asynchronous);
|
2020-07-12 05:14:38 -04:00
|
|
|
|
2023-01-31 06:18:10 -05:00
|
|
|
var commandLineLogMessage = process.StartInfo.FileName + " " + process.StartInfo.Arguments;
|
2023-10-31 13:26:37 -04:00
|
|
|
var commandLineLogMessageBytes = Encoding.UTF8.GetBytes(
|
|
|
|
JsonSerializer.Serialize(state.MediaSource)
|
|
|
|
+ Environment.NewLine
|
|
|
|
+ Environment.NewLine
|
|
|
|
+ commandLineLogMessage
|
|
|
|
+ Environment.NewLine
|
|
|
|
+ Environment.NewLine);
|
|
|
|
|
2023-01-31 06:18:10 -05:00
|
|
|
await logStream.WriteAsync(commandLineLogMessageBytes, cancellationTokenSource.Token).ConfigureAwait(false);
|
2020-07-12 05:14:38 -04:00
|
|
|
|
2023-10-31 13:26:37 -04:00
|
|
|
process.Exited += (_, _) => OnFfMpegProcessExited(process, transcodingJob, state);
|
2020-07-12 05:14:38 -04:00
|
|
|
|
2023-01-31 06:18:10 -05:00
|
|
|
try
|
|
|
|
{
|
|
|
|
process.Start();
|
|
|
|
}
|
|
|
|
catch (Exception ex)
|
|
|
|
{
|
|
|
|
_logger.LogError(ex, "Error starting FFmpeg");
|
2024-02-10 10:52:21 -05:00
|
|
|
OnTranscodeFailedToStart(outputPath, transcodingJobType, state);
|
2020-07-12 05:14:38 -04:00
|
|
|
|
2023-01-31 06:18:10 -05:00
|
|
|
throw;
|
|
|
|
}
|
2020-07-12 05:14:38 -04:00
|
|
|
|
2023-01-31 06:18:10 -05:00
|
|
|
_logger.LogDebug("Launched FFmpeg process");
|
|
|
|
state.TranscodingJob = transcodingJob;
|
2020-07-12 05:14:38 -04:00
|
|
|
|
2023-01-31 06:18:10 -05:00
|
|
|
// Important - don't await the log task or we won't be able to kill FFmpeg when the user stops playback
|
2023-08-20 14:06:57 -04:00
|
|
|
_ = new JobLogger(_logger).StartStreamingLog(state, process.StandardError, logStream);
|
2020-07-12 05:14:38 -04:00
|
|
|
|
2023-01-31 06:18:10 -05:00
|
|
|
// Wait for the file to exist before proceeding
|
|
|
|
var ffmpegTargetFile = state.WaitForPath ?? outputPath;
|
|
|
|
_logger.LogDebug("Waiting for the creation of {0}", ffmpegTargetFile);
|
|
|
|
while (!File.Exists(ffmpegTargetFile) && !transcodingJob.HasExited)
|
|
|
|
{
|
|
|
|
await Task.Delay(100, cancellationTokenSource.Token).ConfigureAwait(false);
|
|
|
|
}
|
2020-07-12 05:14:38 -04:00
|
|
|
|
2023-01-31 06:18:10 -05:00
|
|
|
_logger.LogDebug("File {0} created or transcoding has finished", ffmpegTargetFile);
|
2020-07-12 05:14:38 -04:00
|
|
|
|
2023-01-31 06:18:10 -05:00
|
|
|
if (state.IsInputVideo && transcodingJob.Type == TranscodingJobType.Progressive && !transcodingJob.HasExited)
|
|
|
|
{
|
|
|
|
await Task.Delay(1000, cancellationTokenSource.Token).ConfigureAwait(false);
|
2020-07-12 05:14:38 -04:00
|
|
|
|
2023-01-31 06:18:10 -05:00
|
|
|
if (state.ReadInputAtNativeFramerate && !transcodingJob.HasExited)
|
2020-07-12 05:14:38 -04:00
|
|
|
{
|
2023-01-31 06:18:10 -05:00
|
|
|
await Task.Delay(1500, cancellationTokenSource.Token).ConfigureAwait(false);
|
2020-07-12 05:14:38 -04:00
|
|
|
}
|
2023-01-31 06:18:10 -05:00
|
|
|
}
|
2020-07-12 05:14:38 -04:00
|
|
|
|
2023-01-31 06:18:10 -05:00
|
|
|
if (!transcodingJob.HasExited)
|
|
|
|
{
|
|
|
|
StartThrottler(state, transcodingJob);
|
2020-07-12 05:14:38 -04:00
|
|
|
}
|
2023-01-31 06:18:10 -05:00
|
|
|
else if (transcodingJob.ExitCode != 0)
|
|
|
|
{
|
|
|
|
throw new FfmpegException(string.Format(CultureInfo.InvariantCulture, "FFmpeg exited with code {0}", transcodingJob.ExitCode));
|
2020-07-12 05:14:38 -04:00
|
|
|
}
|
|
|
|
|
2023-01-31 06:18:10 -05:00
|
|
|
_logger.LogDebug("StartFfMpeg() finished successfully");
|
2020-07-12 05:14:38 -04:00
|
|
|
|
2023-01-31 06:18:10 -05:00
|
|
|
return transcodingJob;
|
|
|
|
}
|
|
|
|
|
2023-10-31 11:31:09 -04:00
|
|
|
private void StartThrottler(StreamState state, TranscodingJob transcodingJob)
|
2023-01-31 06:18:10 -05:00
|
|
|
{
|
|
|
|
if (EnableThrottling(state))
|
2020-07-12 05:14:38 -04:00
|
|
|
{
|
2023-06-15 13:38:42 -04:00
|
|
|
transcodingJob.TranscodingThrottler = new TranscodingThrottler(transcodingJob, _loggerFactory.CreateLogger<TranscodingThrottler>(), _serverConfigurationManager, _fileSystem, _mediaEncoder);
|
2023-01-31 06:18:10 -05:00
|
|
|
transcodingJob.TranscodingThrottler.Start();
|
2020-07-12 05:14:38 -04:00
|
|
|
}
|
2023-01-31 06:18:10 -05:00
|
|
|
}
|
|
|
|
|
2023-10-31 13:26:37 -04:00
|
|
|
private static bool EnableThrottling(StreamState state)
|
|
|
|
=> state.InputProtocol == MediaProtocol.File
|
|
|
|
&& state.RunTimeTicks.HasValue
|
|
|
|
&& state.RunTimeTicks.Value >= TimeSpan.FromMinutes(5).Ticks
|
|
|
|
&& state.IsInputVideo
|
|
|
|
&& state.VideoType == VideoType.VideoFile;
|
2020-07-12 05:14:38 -04:00
|
|
|
|
2023-10-31 13:26:37 -04:00
|
|
|
private TranscodingJob OnTranscodeBeginning(
|
2023-01-31 06:18:10 -05:00
|
|
|
string path,
|
|
|
|
string? playSessionId,
|
|
|
|
string? liveStreamId,
|
|
|
|
string transcodingJobId,
|
|
|
|
TranscodingJobType type,
|
|
|
|
Process process,
|
|
|
|
string? deviceId,
|
|
|
|
StreamState state,
|
|
|
|
CancellationTokenSource cancellationTokenSource)
|
|
|
|
{
|
|
|
|
lock (_activeTranscodingJobs)
|
2020-07-12 05:14:38 -04:00
|
|
|
{
|
2023-10-31 11:31:09 -04:00
|
|
|
var job = new TranscodingJob(_loggerFactory.CreateLogger<TranscodingJob>())
|
2023-01-31 06:18:10 -05:00
|
|
|
{
|
|
|
|
Type = type,
|
|
|
|
Path = path,
|
|
|
|
Process = process,
|
|
|
|
ActiveRequestCount = 1,
|
|
|
|
DeviceId = deviceId,
|
|
|
|
CancellationTokenSource = cancellationTokenSource,
|
|
|
|
Id = transcodingJobId,
|
|
|
|
PlaySessionId = playSessionId,
|
|
|
|
LiveStreamId = liveStreamId,
|
|
|
|
MediaSource = state.MediaSource
|
|
|
|
};
|
2020-07-12 05:14:38 -04:00
|
|
|
|
2023-01-31 06:18:10 -05:00
|
|
|
_activeTranscodingJobs.Add(job);
|
|
|
|
|
|
|
|
ReportTranscodingProgress(job, state, null, null, null, null, null);
|
|
|
|
|
|
|
|
return job;
|
2020-07-12 05:14:38 -04:00
|
|
|
}
|
2023-01-31 06:18:10 -05:00
|
|
|
}
|
2020-07-12 05:14:38 -04:00
|
|
|
|
2023-10-31 13:26:37 -04:00
|
|
|
/// <inheritdoc />
|
2023-10-31 11:31:09 -04:00
|
|
|
public void OnTranscodeEndRequest(TranscodingJob job)
|
2023-01-31 06:18:10 -05:00
|
|
|
{
|
|
|
|
job.ActiveRequestCount--;
|
|
|
|
_logger.LogDebug("OnTranscodeEndRequest job.ActiveRequestCount={ActiveRequestCount}", job.ActiveRequestCount);
|
|
|
|
if (job.ActiveRequestCount <= 0)
|
2020-07-27 15:42:40 -04:00
|
|
|
{
|
2023-01-31 06:18:10 -05:00
|
|
|
PingTimer(job, false);
|
2020-07-27 15:42:40 -04:00
|
|
|
}
|
2023-01-31 06:18:10 -05:00
|
|
|
}
|
2020-07-27 15:42:40 -04:00
|
|
|
|
2023-10-31 13:26:37 -04:00
|
|
|
private void OnTranscodeFailedToStart(string path, TranscodingJobType type, StreamState state)
|
2023-01-31 06:18:10 -05:00
|
|
|
{
|
|
|
|
lock (_activeTranscodingJobs)
|
2020-07-12 05:14:38 -04:00
|
|
|
{
|
2023-01-31 06:18:10 -05:00
|
|
|
var job = _activeTranscodingJobs.FirstOrDefault(j => j.Type == type && string.Equals(j.Path, path, StringComparison.OrdinalIgnoreCase));
|
2020-07-12 05:14:38 -04:00
|
|
|
|
2023-01-31 06:18:10 -05:00
|
|
|
if (job is not null)
|
2020-07-12 05:14:38 -04:00
|
|
|
{
|
2023-01-31 06:18:10 -05:00
|
|
|
_activeTranscodingJobs.Remove(job);
|
2020-07-12 05:14:38 -04:00
|
|
|
}
|
2023-01-31 06:18:10 -05:00
|
|
|
}
|
2020-07-12 05:14:38 -04:00
|
|
|
|
2023-01-31 06:18:10 -05:00
|
|
|
if (!string.IsNullOrWhiteSpace(state.Request.DeviceId))
|
2020-07-12 05:14:38 -04:00
|
|
|
{
|
2023-01-31 06:18:10 -05:00
|
|
|
_sessionManager.ClearTranscodingInfo(state.Request.DeviceId);
|
|
|
|
}
|
|
|
|
}
|
2020-07-12 05:14:38 -04:00
|
|
|
|
2023-10-31 11:31:09 -04:00
|
|
|
private void OnFfMpegProcessExited(Process process, TranscodingJob job, StreamState state)
|
2023-01-31 06:18:10 -05:00
|
|
|
{
|
|
|
|
job.HasExited = true;
|
|
|
|
job.ExitCode = process.ExitCode;
|
2022-02-13 18:24:52 -05:00
|
|
|
|
2023-01-31 06:18:10 -05:00
|
|
|
ReportTranscodingProgress(job, state, null, null, null, null, null);
|
2020-07-12 05:14:38 -04:00
|
|
|
|
2023-01-31 06:18:10 -05:00
|
|
|
_logger.LogDebug("Disposing stream resources");
|
|
|
|
state.Dispose();
|
2020-07-12 05:14:38 -04:00
|
|
|
|
2023-01-31 06:18:10 -05:00
|
|
|
if (process.ExitCode == 0)
|
|
|
|
{
|
|
|
|
_logger.LogInformation("FFmpeg exited with code 0");
|
2020-07-12 05:14:38 -04:00
|
|
|
}
|
2023-01-31 06:18:10 -05:00
|
|
|
else
|
2020-07-12 05:14:38 -04:00
|
|
|
{
|
2023-01-31 06:18:10 -05:00
|
|
|
_logger.LogError("FFmpeg exited with code {0}", process.ExitCode);
|
|
|
|
}
|
2020-07-12 05:14:38 -04:00
|
|
|
|
2023-01-31 06:18:10 -05:00
|
|
|
job.Dispose();
|
|
|
|
}
|
2020-07-12 05:14:38 -04:00
|
|
|
|
2023-01-31 06:18:10 -05:00
|
|
|
private async Task AcquireResources(StreamState state, CancellationTokenSource cancellationTokenSource)
|
|
|
|
{
|
|
|
|
if (state.MediaSource.RequiresOpening && string.IsNullOrWhiteSpace(state.Request.LiveStreamId))
|
|
|
|
{
|
|
|
|
var liveStreamResponse = await _mediaSourceManager.OpenLiveStream(
|
|
|
|
new LiveStreamRequest { OpenToken = state.MediaSource.OpenToken },
|
|
|
|
cancellationTokenSource.Token)
|
|
|
|
.ConfigureAwait(false);
|
|
|
|
var encodingOptions = _serverConfigurationManager.GetEncodingOptions();
|
|
|
|
|
|
|
|
_encodingHelper.AttachMediaSourceInfo(state, encodingOptions, liveStreamResponse.MediaSource, state.RequestedUrl);
|
2020-07-12 05:14:38 -04:00
|
|
|
|
2023-01-31 06:18:10 -05:00
|
|
|
if (state.VideoRequest is not null)
|
2020-07-12 05:14:38 -04:00
|
|
|
{
|
2023-01-31 06:18:10 -05:00
|
|
|
_encodingHelper.TryStreamCopy(state);
|
2020-07-12 05:14:38 -04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-01-31 06:18:10 -05:00
|
|
|
if (state.MediaSource.BufferMs.HasValue)
|
2020-07-12 05:14:38 -04:00
|
|
|
{
|
2023-01-31 06:18:10 -05:00
|
|
|
await Task.Delay(state.MediaSource.BufferMs.Value, cancellationTokenSource.Token).ConfigureAwait(false);
|
2020-07-12 05:14:38 -04:00
|
|
|
}
|
2023-01-31 06:18:10 -05:00
|
|
|
}
|
2020-07-12 05:14:38 -04:00
|
|
|
|
2023-10-31 13:26:37 -04:00
|
|
|
/// <inheritdoc />
|
2023-10-31 11:31:09 -04:00
|
|
|
public TranscodingJob? OnTranscodeBeginRequest(string path, TranscodingJobType type)
|
2023-01-31 06:18:10 -05:00
|
|
|
{
|
|
|
|
lock (_activeTranscodingJobs)
|
2020-07-12 05:14:38 -04:00
|
|
|
{
|
2023-10-31 13:26:37 -04:00
|
|
|
var job = _activeTranscodingJobs
|
|
|
|
.FirstOrDefault(j => j.Type == type && string.Equals(j.Path, path, StringComparison.OrdinalIgnoreCase));
|
2020-07-12 05:14:38 -04:00
|
|
|
|
2023-01-31 06:18:10 -05:00
|
|
|
if (job is null)
|
2020-07-12 05:14:38 -04:00
|
|
|
{
|
2023-01-31 06:18:10 -05:00
|
|
|
return null;
|
2020-07-12 05:14:38 -04:00
|
|
|
}
|
2023-01-31 06:18:10 -05:00
|
|
|
|
2023-10-31 13:26:37 -04:00
|
|
|
job.ActiveRequestCount++;
|
|
|
|
if (string.IsNullOrWhiteSpace(job.PlaySessionId) || job.Type == TranscodingJobType.Progressive)
|
|
|
|
{
|
|
|
|
job.StopKillTimer();
|
|
|
|
}
|
2023-01-31 06:18:10 -05:00
|
|
|
|
|
|
|
return job;
|
2020-07-12 05:14:38 -04:00
|
|
|
}
|
2023-01-31 06:18:10 -05:00
|
|
|
}
|
2020-07-12 05:14:38 -04:00
|
|
|
|
2023-01-31 06:18:10 -05:00
|
|
|
private void OnPlaybackProgress(object? sender, PlaybackProgressEventArgs e)
|
|
|
|
{
|
|
|
|
if (!string.IsNullOrWhiteSpace(e.PlaySessionId))
|
2020-07-12 05:14:38 -04:00
|
|
|
{
|
2023-01-31 06:18:10 -05:00
|
|
|
PingTranscodingJob(e.PlaySessionId, e.IsPaused);
|
|
|
|
}
|
|
|
|
}
|
2020-07-12 05:14:38 -04:00
|
|
|
|
2023-01-31 06:18:10 -05:00
|
|
|
private void DeleteEncodedMediaCache()
|
|
|
|
{
|
|
|
|
var path = _serverConfigurationManager.GetTranscodePath();
|
|
|
|
if (!Directory.Exists(path))
|
|
|
|
{
|
|
|
|
return;
|
2020-07-12 05:14:38 -04:00
|
|
|
}
|
2020-08-01 10:21:48 -04:00
|
|
|
|
2023-01-31 06:18:10 -05:00
|
|
|
foreach (var file in _fileSystem.GetFilePaths(path, true))
|
2020-08-01 10:21:48 -04:00
|
|
|
{
|
2023-01-31 06:18:10 -05:00
|
|
|
_fileSystem.DeleteFile(file);
|
2020-08-01 10:21:48 -04:00
|
|
|
}
|
2023-01-31 06:18:10 -05:00
|
|
|
}
|
2020-08-01 10:21:48 -04:00
|
|
|
|
2024-01-03 10:47:25 -05:00
|
|
|
/// <summary>
|
|
|
|
/// Transcoding lock.
|
|
|
|
/// </summary>
|
|
|
|
/// <param name="outputPath">The output path of the transcoded file.</param>
|
|
|
|
/// <param name="cancellationToken">The cancellation token.</param>
|
2024-01-14 06:11:16 -05:00
|
|
|
/// <returns>An <see cref="IDisposable"/>.</returns>
|
2024-01-03 10:47:25 -05:00
|
|
|
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
|
|
|
public ValueTask<IDisposable> LockAsync(string outputPath, CancellationToken cancellationToken)
|
|
|
|
{
|
|
|
|
return _transcodingLocks.LockAsync(outputPath, cancellationToken);
|
|
|
|
}
|
|
|
|
|
2023-10-31 13:26:37 -04:00
|
|
|
/// <inheritdoc />
|
2023-01-31 06:18:10 -05:00
|
|
|
public void Dispose()
|
|
|
|
{
|
2023-10-31 13:26:37 -04:00
|
|
|
_sessionManager.PlaybackProgress -= OnPlaybackProgress;
|
|
|
|
_sessionManager.PlaybackStart -= OnPlaybackProgress;
|
2024-01-03 10:47:25 -05:00
|
|
|
_transcodingLocks.Dispose();
|
2020-06-26 23:04:02 -04:00
|
|
|
}
|
|
|
|
}
|