mirror of
https://github.com/jellyfin/jellyfin-plugin-dlna.git
synced 2024-11-26 16:00:55 +00:00
Use ITranscodeManager service
This commit is contained in:
parent
53142d6743
commit
c86de30105
@ -137,7 +137,7 @@ public class DlnaAudioController : ControllerBase
|
||||
[FromQuery] EncodingContext? context,
|
||||
[FromQuery] Dictionary<string, string>? streamOptions)
|
||||
{
|
||||
StreamingRequestDto streamingRequest = new StreamingRequestDto
|
||||
var streamingRequest = new DlnaStreamingRequestDto
|
||||
{
|
||||
Id = itemId,
|
||||
Container = container,
|
||||
@ -301,7 +301,7 @@ public class DlnaAudioController : ControllerBase
|
||||
[FromQuery] EncodingContext? context,
|
||||
[FromQuery] Dictionary<string, string>? streamOptions)
|
||||
{
|
||||
StreamingRequestDto streamingRequest = new StreamingRequestDto
|
||||
var streamingRequest = new DlnaStreamingRequestDto
|
||||
{
|
||||
Id = itemId,
|
||||
Container = container,
|
||||
|
@ -145,7 +145,7 @@ public class DynamicHlsController : ControllerBase
|
||||
[FromQuery] bool enableAdaptiveBitrateStreaming = true,
|
||||
[FromQuery] bool enableTrickplay = true)
|
||||
{
|
||||
var streamingRequest = new HlsVideoRequestDto
|
||||
var streamingRequest = new DlnaHlsVideoRequestDto
|
||||
{
|
||||
Id = itemId,
|
||||
Static = @static ?? false,
|
||||
@ -314,7 +314,7 @@ public class DynamicHlsController : ControllerBase
|
||||
[FromQuery] Dictionary<string, string> streamOptions,
|
||||
[FromQuery] bool enableAdaptiveBitrateStreaming = true)
|
||||
{
|
||||
var streamingRequest = new HlsAudioRequestDto
|
||||
var streamingRequest = new DlnaHlsAudioRequestDto
|
||||
{
|
||||
Id = itemId,
|
||||
Static = @static ?? false,
|
||||
|
@ -12,6 +12,7 @@ using MediaBrowser.Controller.Configuration;
|
||||
using MediaBrowser.Controller.Devices;
|
||||
using MediaBrowser.Controller.Library;
|
||||
using MediaBrowser.Controller.MediaEncoding;
|
||||
using MediaBrowser.Controller.Streaming;
|
||||
using MediaBrowser.Model.Dlna;
|
||||
using MediaBrowser.Model.MediaInfo;
|
||||
using MediaBrowser.Model.Net;
|
||||
@ -33,7 +34,7 @@ public class DlnaVideosController : ControllerBase
|
||||
private readonly IServerConfigurationManager _serverConfigurationManager;
|
||||
private readonly IMediaEncoder _mediaEncoder;
|
||||
private readonly IDeviceManager _deviceManager;
|
||||
private readonly TranscodingJobHelper _transcodingJobHelper;
|
||||
private readonly ITranscodeManager _transcodingJobHelper;
|
||||
private readonly IHttpClientFactory _httpClientFactory;
|
||||
private readonly EncodingHelper _encodingHelper;
|
||||
|
||||
@ -49,7 +50,7 @@ public class DlnaVideosController : ControllerBase
|
||||
/// <param name="serverConfigurationManager">Instance of the <see cref="IServerConfigurationManager"/> interface.</param>
|
||||
/// <param name="mediaEncoder">Instance of the <see cref="IMediaEncoder"/> interface.</param>
|
||||
/// <param name="deviceManager">Instance of the <see cref="IDeviceManager"/> interface.</param>
|
||||
/// <param name="transcodingJobHelper">Instance of the <see cref="TranscodingJobHelper"/> class.</param>
|
||||
/// <param name="transcodingJobHelper">Instance of the <see cref="ITranscodeManager"/> class.</param>
|
||||
/// <param name="httpClientFactory">Instance of the <see cref="IHttpClientFactory"/> interface.</param>
|
||||
/// <param name="encodingHelper">Instance of <see cref="EncodingHelper"/>.</param>
|
||||
public DlnaVideosController(
|
||||
@ -60,7 +61,7 @@ public class DlnaVideosController : ControllerBase
|
||||
IServerConfigurationManager serverConfigurationManager,
|
||||
IMediaEncoder mediaEncoder,
|
||||
IDeviceManager deviceManager,
|
||||
TranscodingJobHelper transcodingJobHelper,
|
||||
ITranscodeManager transcodingJobHelper,
|
||||
IHttpClientFactory httpClientFactory,
|
||||
EncodingHelper encodingHelper)
|
||||
{
|
||||
@ -191,7 +192,7 @@ public class DlnaVideosController : ControllerBase
|
||||
var isHeadRequest = Request.Method == System.Net.WebRequestMethods.Http.Head;
|
||||
// CTS lifecycle is managed internally.
|
||||
var cancellationTokenSource = new CancellationTokenSource();
|
||||
var streamingRequest = new VideoRequestDto
|
||||
var streamingRequest = new DlnaVideoRequestDto
|
||||
{
|
||||
Id = itemId,
|
||||
Container = container,
|
||||
|
@ -11,6 +11,7 @@ using MediaBrowser.Controller.Configuration;
|
||||
using MediaBrowser.Controller.Devices;
|
||||
using MediaBrowser.Controller.Library;
|
||||
using MediaBrowser.Controller.MediaEncoding;
|
||||
using MediaBrowser.Controller.Streaming;
|
||||
using MediaBrowser.Model.MediaInfo;
|
||||
using MediaBrowser.Model.Net;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
@ -30,7 +31,7 @@ public class AudioHelper
|
||||
private readonly IServerConfigurationManager _serverConfigurationManager;
|
||||
private readonly IMediaEncoder _mediaEncoder;
|
||||
private readonly IDeviceManager _deviceManager;
|
||||
private readonly TranscodingJobHelper _transcodingJobHelper;
|
||||
private readonly ITranscodeManager _transcodeManager;
|
||||
private readonly IHttpClientFactory _httpClientFactory;
|
||||
private readonly IHttpContextAccessor _httpContextAccessor;
|
||||
private readonly EncodingHelper _encodingHelper;
|
||||
@ -45,7 +46,7 @@ public class AudioHelper
|
||||
/// <param name="serverConfigurationManager">Instance of the <see cref="IServerConfigurationManager"/> interface.</param>
|
||||
/// <param name="mediaEncoder">Instance of the <see cref="IMediaEncoder"/> interface.</param>
|
||||
/// <param name="deviceManager">Instance of the <see cref="IDeviceManager"/> interface.</param>
|
||||
/// <param name="transcodingJobHelper">Instance of <see cref="TranscodingJobHelper"/>.</param>
|
||||
/// <param name="transcodeManager">Instance of <see cref="ITranscodeManager"/>.</param>
|
||||
/// <param name="httpClientFactory">Instance of the <see cref="IHttpClientFactory"/> interface.</param>
|
||||
/// <param name="httpContextAccessor">Instance of the <see cref="IHttpContextAccessor"/> interface.</param>
|
||||
/// <param name="encodingHelper">Instance of <see cref="EncodingHelper"/>.</param>
|
||||
@ -57,7 +58,7 @@ public class AudioHelper
|
||||
IServerConfigurationManager serverConfigurationManager,
|
||||
IMediaEncoder mediaEncoder,
|
||||
IDeviceManager deviceManager,
|
||||
TranscodingJobHelper transcodingJobHelper,
|
||||
ITranscodeManager transcodeManager,
|
||||
IHttpClientFactory httpClientFactory,
|
||||
IHttpContextAccessor httpContextAccessor,
|
||||
EncodingHelper encodingHelper)
|
||||
@ -69,7 +70,7 @@ public class AudioHelper
|
||||
_serverConfigurationManager = serverConfigurationManager;
|
||||
_mediaEncoder = mediaEncoder;
|
||||
_deviceManager = deviceManager;
|
||||
_transcodingJobHelper = transcodingJobHelper;
|
||||
_transcodeManager = transcodeManager;
|
||||
_httpClientFactory = httpClientFactory;
|
||||
_httpContextAccessor = httpContextAccessor;
|
||||
_encodingHelper = encodingHelper;
|
||||
@ -83,7 +84,7 @@ public class AudioHelper
|
||||
/// <returns>A <see cref="Task"/> containing the resulting <see cref="ActionResult"/>.</returns>
|
||||
public async Task<ActionResult> GetAudioStream(
|
||||
TranscodingJobType transcodingJobType,
|
||||
StreamingRequestDto streamingRequest)
|
||||
DlnaStreamingRequestDto streamingRequest)
|
||||
{
|
||||
if (_httpContextAccessor.HttpContext is null)
|
||||
{
|
||||
@ -106,7 +107,7 @@ public class AudioHelper
|
||||
_encodingHelper,
|
||||
_dlnaManager,
|
||||
_deviceManager,
|
||||
_transcodingJobHelper,
|
||||
_transcodeManager,
|
||||
transcodingJobType,
|
||||
cancellationTokenSource.Token)
|
||||
.ConfigureAwait(false);
|
||||
@ -143,7 +144,7 @@ public class AudioHelper
|
||||
var outputPath = state.OutputFilePath;
|
||||
var outputPathExists = File.Exists(outputPath);
|
||||
|
||||
var transcodingJob = _transcodingJobHelper.GetTranscodingJob(outputPath, TranscodingJobType.Progressive);
|
||||
var transcodingJob = _transcodeManager.GetTranscodingJob(outputPath, TranscodingJobType.Progressive);
|
||||
var isTranscodeCached = outputPathExists && transcodingJob is not null;
|
||||
|
||||
StreamingHelpers.AddDlnaHeaders(state, _httpContextAccessor.HttpContext.Response.Headers, streamingRequest.Static || isTranscodeCached, streamingRequest.StartTimeTicks, _httpContextAccessor.HttpContext.Request, _dlnaManager);
|
||||
@ -155,7 +156,7 @@ public class AudioHelper
|
||||
|
||||
if (state.MediaSource.IsInfiniteStream)
|
||||
{
|
||||
var stream = new ProgressiveFileStream(state.MediaPath, null, _transcodingJobHelper);
|
||||
var stream = new ProgressiveFileStream(state.MediaPath, null, _transcodeManager);
|
||||
return new FileStreamResult(stream, contentType);
|
||||
}
|
||||
|
||||
@ -171,7 +172,7 @@ public class AudioHelper
|
||||
state,
|
||||
isHeadRequest,
|
||||
_httpContextAccessor.HttpContext,
|
||||
_transcodingJobHelper,
|
||||
_transcodeManager,
|
||||
ffmpegCommandLineArguments,
|
||||
transcodingJobType,
|
||||
cancellationTokenSource).ConfigureAwait(false);
|
||||
|
@ -20,6 +20,7 @@ using MediaBrowser.Controller.Configuration;
|
||||
using MediaBrowser.Controller.Devices;
|
||||
using MediaBrowser.Controller.Library;
|
||||
using MediaBrowser.Controller.MediaEncoding;
|
||||
using MediaBrowser.Controller.Streaming;
|
||||
using MediaBrowser.Controller.Trickplay;
|
||||
using MediaBrowser.Model.Dlna;
|
||||
using MediaBrowser.Model.Entities;
|
||||
@ -43,7 +44,7 @@ public class DynamicHlsHelper
|
||||
private readonly IServerConfigurationManager _serverConfigurationManager;
|
||||
private readonly IMediaEncoder _mediaEncoder;
|
||||
private readonly IDeviceManager _deviceManager;
|
||||
private readonly TranscodingJobHelper _transcodingJobHelper;
|
||||
private readonly ITranscodeManager _transcodeManager;
|
||||
private readonly INetworkManager _networkManager;
|
||||
private readonly ILogger<DynamicHlsHelper> _logger;
|
||||
private readonly IHttpContextAccessor _httpContextAccessor;
|
||||
@ -60,7 +61,7 @@ public class DynamicHlsHelper
|
||||
/// <param name="serverConfigurationManager">Instance of the <see cref="IServerConfigurationManager"/> interface.</param>
|
||||
/// <param name="mediaEncoder">Instance of the <see cref="IMediaEncoder"/> interface.</param>
|
||||
/// <param name="deviceManager">Instance of the <see cref="IDeviceManager"/> interface.</param>
|
||||
/// <param name="transcodingJobHelper">Instance of <see cref="TranscodingJobHelper"/>.</param>
|
||||
/// <param name="transcodeManager">Instance of <see cref="ITranscodeManager"/>.</param>
|
||||
/// <param name="networkManager">Instance of the <see cref="INetworkManager"/> interface.</param>
|
||||
/// <param name="logger">Instance of the <see cref="ILogger{DynamicHlsHelper}"/> interface.</param>
|
||||
/// <param name="httpContextAccessor">Instance of the <see cref="IHttpContextAccessor"/> interface.</param>
|
||||
@ -74,7 +75,7 @@ public class DynamicHlsHelper
|
||||
IServerConfigurationManager serverConfigurationManager,
|
||||
IMediaEncoder mediaEncoder,
|
||||
IDeviceManager deviceManager,
|
||||
TranscodingJobHelper transcodingJobHelper,
|
||||
ITranscodeManager transcodeManager,
|
||||
INetworkManager networkManager,
|
||||
ILogger<DynamicHlsHelper> logger,
|
||||
IHttpContextAccessor httpContextAccessor,
|
||||
@ -88,7 +89,7 @@ public class DynamicHlsHelper
|
||||
_serverConfigurationManager = serverConfigurationManager;
|
||||
_mediaEncoder = mediaEncoder;
|
||||
_deviceManager = deviceManager;
|
||||
_transcodingJobHelper = transcodingJobHelper;
|
||||
_transcodeManager = transcodeManager;
|
||||
_networkManager = networkManager;
|
||||
_logger = logger;
|
||||
_httpContextAccessor = httpContextAccessor;
|
||||
@ -105,7 +106,7 @@ public class DynamicHlsHelper
|
||||
/// <returns>A <see cref="Task"/> containing the resulting <see cref="ActionResult"/>.</returns>
|
||||
public async Task<ActionResult> GetMasterHlsPlaylist(
|
||||
TranscodingJobType transcodingJobType,
|
||||
StreamingRequestDto streamingRequest,
|
||||
DlnaStreamingRequestDto streamingRequest,
|
||||
bool enableAdaptiveBitrateStreaming)
|
||||
{
|
||||
var isHeadRequest = _httpContextAccessor.HttpContext?.Request.Method == WebRequestMethods.Http.Head;
|
||||
@ -120,7 +121,7 @@ public class DynamicHlsHelper
|
||||
}
|
||||
|
||||
private async Task<ActionResult> GetMasterPlaylistInternal(
|
||||
StreamingRequestDto streamingRequest,
|
||||
DlnaStreamingRequestDto streamingRequest,
|
||||
bool isHeadRequest,
|
||||
bool enableAdaptiveBitrateStreaming,
|
||||
TranscodingJobType transcodingJobType,
|
||||
@ -142,7 +143,7 @@ public class DynamicHlsHelper
|
||||
_encodingHelper,
|
||||
_dlnaManager,
|
||||
_deviceManager,
|
||||
_transcodingJobHelper,
|
||||
_transcodeManager,
|
||||
transcodingJobType,
|
||||
cancellationTokenSource.Token)
|
||||
.ConfigureAwait(false);
|
||||
|
@ -4,8 +4,9 @@ using System.Net.Http;
|
||||
using System.Net.Mime;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Jellyfin.Plugin.Dlna.Playback.Model;
|
||||
using Jellyfin.Plugin.Dlna.Playback.Extensions;
|
||||
using MediaBrowser.Controller.MediaEncoding;
|
||||
using MediaBrowser.Controller.Streaming;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.Net.Http.Headers;
|
||||
@ -64,7 +65,7 @@ public static class FileStreamResponseHelpers
|
||||
/// <param name="state">The current <see cref="StreamState"/>.</param>
|
||||
/// <param name="isHeadRequest">Whether the current request is a HTTP HEAD request so only the headers get returned.</param>
|
||||
/// <param name="httpContext">The current http context.</param>
|
||||
/// <param name="transcodingJobHelper">The <see cref="TranscodingJobHelper"/> singleton.</param>
|
||||
/// <param name="transcodeManager">The <see cref="ITranscodeManager"/> singleton.</param>
|
||||
/// <param name="ffmpegCommandLineArguments">The command line arguments to start ffmpeg.</param>
|
||||
/// <param name="transcodingJobType">The <see cref="TranscodingJobType"/>.</param>
|
||||
/// <param name="cancellationTokenSource">The <see cref="CancellationTokenSource"/>.</param>
|
||||
@ -73,7 +74,7 @@ public static class FileStreamResponseHelpers
|
||||
StreamState state,
|
||||
bool isHeadRequest,
|
||||
HttpContext httpContext,
|
||||
TranscodingJobHelper transcodingJobHelper,
|
||||
ITranscodeManager transcodeManager,
|
||||
string ffmpegCommandLineArguments,
|
||||
TranscodingJobType transcodingJobType,
|
||||
CancellationTokenSource cancellationTokenSource)
|
||||
@ -92,22 +93,28 @@ public static class FileStreamResponseHelpers
|
||||
return new OkResult();
|
||||
}
|
||||
|
||||
var transcodingLock = transcodingJobHelper.GetTranscodingLock(outputPath);
|
||||
var transcodingLock = transcodeManager.GetTranscodingLock(outputPath);
|
||||
await transcodingLock.WaitAsync(cancellationTokenSource.Token).ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
TranscodingJobDto? job;
|
||||
TranscodingJob? job;
|
||||
if (!File.Exists(outputPath))
|
||||
{
|
||||
job = await transcodingJobHelper.StartFfMpeg(state, outputPath, ffmpegCommandLineArguments, httpContext.Request, transcodingJobType, cancellationTokenSource).ConfigureAwait(false);
|
||||
job = await transcodeManager.StartFfMpeg(
|
||||
state,
|
||||
outputPath,
|
||||
ffmpegCommandLineArguments,
|
||||
httpContext.User.GetUserId(),
|
||||
transcodingJobType,
|
||||
cancellationTokenSource).ConfigureAwait(false);
|
||||
}
|
||||
else
|
||||
{
|
||||
job = transcodingJobHelper.OnTranscodeBeginRequest(outputPath, TranscodingJobType.Progressive);
|
||||
job = transcodeManager.OnTranscodeBeginRequest(outputPath, TranscodingJobType.Progressive);
|
||||
state.Dispose();
|
||||
}
|
||||
|
||||
var stream = new ProgressiveFileStream(outputPath, job, transcodingJobHelper);
|
||||
var stream = new ProgressiveFileStream(outputPath, job, transcodeManager);
|
||||
return new FileStreamResult(stream, contentType);
|
||||
}
|
||||
finally
|
||||
|
@ -3,7 +3,7 @@
|
||||
/// <summary>
|
||||
/// The hls video request dto.
|
||||
/// </summary>
|
||||
public class HlsVideoRequestDto : VideoRequestDto
|
||||
public class DlnaHlsAudioRequestDto : DlnaStreamingRequestDto
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets or sets a value indicating whether enable adaptive bitrate streaming.
|
@ -3,7 +3,7 @@
|
||||
/// <summary>
|
||||
/// The hls video request dto.
|
||||
/// </summary>
|
||||
public class HlsAudioRequestDto : StreamingRequestDto
|
||||
public class DlnaHlsVideoRequestDto : DlnaVideoRequestDto
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets or sets a value indicating whether enable adaptive bitrate streaming.
|
27
src/Jellyfin.Plugin.Dlna.Playback/Model/DlnaStreamState.cs
Normal file
27
src/Jellyfin.Plugin.Dlna.Playback/Model/DlnaStreamState.cs
Normal file
@ -0,0 +1,27 @@
|
||||
using Jellyfin.Plugin.Dlna.Model;
|
||||
using MediaBrowser.Controller.Library;
|
||||
using MediaBrowser.Controller.MediaEncoding;
|
||||
using MediaBrowser.Controller.Streaming;
|
||||
|
||||
namespace Jellyfin.Plugin.Dlna.Playback.Model;
|
||||
|
||||
public class DlnaStreamState : StreamState
|
||||
{
|
||||
public DlnaStreamState(
|
||||
IMediaSourceManager mediaSourceManager,
|
||||
TranscodingJobType transcodingType,
|
||||
ITranscodeManager transcodeManager)
|
||||
: base(mediaSourceManager, transcodingType, transcodeManager)
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets a value indicating whether to enable dlna headers.
|
||||
/// </summary>
|
||||
public bool EnableDlnaHeaders { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the device profile.
|
||||
/// </summary>
|
||||
public DlnaDeviceProfile? DeviceProfile { get; set; }
|
||||
}
|
@ -0,0 +1,14 @@
|
||||
using MediaBrowser.Controller.Streaming;
|
||||
|
||||
namespace Jellyfin.Plugin.Dlna.Playback.Model;
|
||||
|
||||
/// <summary>
|
||||
/// The audio streaming request dto.
|
||||
/// </summary>
|
||||
public class DlnaStreamingRequestDto : StreamingRequestDto
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets or sets the device profile.
|
||||
/// </summary>
|
||||
public string? DeviceProfileId { get; set; }
|
||||
}
|
@ -3,7 +3,7 @@ namespace Jellyfin.Plugin.Dlna.Playback.Model;
|
||||
/// <summary>
|
||||
/// The video request dto.
|
||||
/// </summary>
|
||||
public class VideoRequestDto : StreamingRequestDto
|
||||
public class DlnaVideoRequestDto : DlnaStreamingRequestDto
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets a value indicating whether this instance has fixed resolution.
|
@ -1,194 +0,0 @@
|
||||
using System;
|
||||
using Jellyfin.Plugin.Dlna.Model;
|
||||
using MediaBrowser.Controller.Library;
|
||||
using MediaBrowser.Controller.MediaEncoding;
|
||||
using MediaBrowser.Model.Dlna;
|
||||
|
||||
namespace Jellyfin.Plugin.Dlna.Playback.Model;
|
||||
|
||||
/// <summary>
|
||||
/// The stream state dto.
|
||||
/// </summary>
|
||||
public class StreamState : EncodingJobInfo, IDisposable
|
||||
{
|
||||
private readonly IMediaSourceManager _mediaSourceManager;
|
||||
private readonly TranscodingJobHelper _transcodingJobHelper;
|
||||
private bool _disposed;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="StreamState" /> class.
|
||||
/// </summary>
|
||||
/// <param name="mediaSourceManager">Instance of the <see cref="IMediaSourceManager" /> interface.</param>
|
||||
/// <param name="transcodingType">The <see cref="TranscodingJobType" />.</param>
|
||||
/// <param name="transcodingJobHelper">The <see cref="TranscodingJobHelper" /> singleton.</param>
|
||||
public StreamState(IMediaSourceManager mediaSourceManager, TranscodingJobType transcodingType, TranscodingJobHelper transcodingJobHelper)
|
||||
: base(transcodingType)
|
||||
{
|
||||
_mediaSourceManager = mediaSourceManager;
|
||||
_transcodingJobHelper = transcodingJobHelper;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the requested url.
|
||||
/// </summary>
|
||||
public string? RequestedUrl { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the request.
|
||||
/// </summary>
|
||||
public StreamingRequestDto Request
|
||||
{
|
||||
get => (StreamingRequestDto)BaseRequest;
|
||||
set
|
||||
{
|
||||
BaseRequest = value;
|
||||
IsVideoRequest = VideoRequest is not null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the video request.
|
||||
/// </summary>
|
||||
public VideoRequestDto? VideoRequest => Request as VideoRequestDto;
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the direct stream provicer.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Deprecated.
|
||||
/// </remarks>
|
||||
public IDirectStreamProvider? DirectStreamProvider { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the path to wait for.
|
||||
/// </summary>
|
||||
public string? WaitForPath { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets a value indicating whether the request outputs video.
|
||||
/// </summary>
|
||||
public bool IsOutputVideo => Request is VideoRequestDto;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the segment length.
|
||||
/// </summary>
|
||||
public int SegmentLength
|
||||
{
|
||||
get
|
||||
{
|
||||
if (Request.SegmentLength.HasValue)
|
||||
{
|
||||
return Request.SegmentLength.Value;
|
||||
}
|
||||
|
||||
if (EncodingHelper.IsCopyCodec(OutputVideoCodec))
|
||||
{
|
||||
var userAgent = UserAgent ?? string.Empty;
|
||||
|
||||
if (userAgent.IndexOf("AppleTV", StringComparison.OrdinalIgnoreCase) != -1
|
||||
|| userAgent.IndexOf("cfnetwork", StringComparison.OrdinalIgnoreCase) != -1
|
||||
|| userAgent.IndexOf("ipad", StringComparison.OrdinalIgnoreCase) != -1
|
||||
|| userAgent.IndexOf("iphone", StringComparison.OrdinalIgnoreCase) != -1
|
||||
|| userAgent.IndexOf("ipod", StringComparison.OrdinalIgnoreCase) != -1)
|
||||
{
|
||||
return 6;
|
||||
}
|
||||
|
||||
if (IsSegmentedLiveStream)
|
||||
{
|
||||
return 3;
|
||||
}
|
||||
|
||||
return 6;
|
||||
}
|
||||
|
||||
return 3;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the minimum number of segments.
|
||||
/// </summary>
|
||||
public int MinSegments
|
||||
{
|
||||
get
|
||||
{
|
||||
if (Request.MinSegments.HasValue)
|
||||
{
|
||||
return Request.MinSegments.Value;
|
||||
}
|
||||
|
||||
return SegmentLength >= 10 ? 2 : 3;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the user agent.
|
||||
/// </summary>
|
||||
public string? UserAgent { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets a value indicating whether to estimate the content length.
|
||||
/// </summary>
|
||||
public bool EstimateContentLength { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the transcode seek info.
|
||||
/// </summary>
|
||||
public TranscodeSeekInfo TranscodeSeekInfo { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets a value indicating whether to enable dlna headers.
|
||||
/// </summary>
|
||||
public bool EnableDlnaHeaders { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the device profile.
|
||||
/// </summary>
|
||||
public DlnaDeviceProfile? DeviceProfile { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the transcoding job.
|
||||
/// </summary>
|
||||
public TranscodingJobDto? TranscodingJob { get; set; }
|
||||
|
||||
/// <inheritdoc />
|
||||
public void Dispose()
|
||||
{
|
||||
Dispose(true);
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public override void ReportTranscodingProgress(TimeSpan? transcodingPosition, float? framerate, double? percentComplete, long? bytesTranscoded, int? bitRate)
|
||||
{
|
||||
_transcodingJobHelper.ReportTranscodingProgress(TranscodingJob!, this, transcodingPosition, framerate, percentComplete, bytesTranscoded, bitRate);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes the stream state.
|
||||
/// </summary>
|
||||
/// <param name="disposing">Whether the object is currently being disposed.</param>
|
||||
protected virtual void Dispose(bool disposing)
|
||||
{
|
||||
if (_disposed)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (disposing)
|
||||
{
|
||||
// REVIEW: Is this the right place for this?
|
||||
if (MediaSource.RequiresClosing
|
||||
&& string.IsNullOrWhiteSpace(Request.LiveStreamId)
|
||||
&& !string.IsNullOrWhiteSpace(MediaSource.LiveStreamId))
|
||||
{
|
||||
_mediaSourceManager.CloseLiveStream(MediaSource.LiveStreamId).GetAwaiter().GetResult();
|
||||
}
|
||||
}
|
||||
|
||||
TranscodingJob = null;
|
||||
|
||||
_disposed = true;
|
||||
}
|
||||
}
|
@ -1,54 +0,0 @@
|
||||
using MediaBrowser.Controller.MediaEncoding;
|
||||
|
||||
namespace Jellyfin.Plugin.Dlna.Playback.Model;
|
||||
|
||||
/// <summary>
|
||||
/// The audio streaming request dto.
|
||||
/// </summary>
|
||||
public class StreamingRequestDto : BaseEncodingJobOptions
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets or sets the device profile.
|
||||
/// </summary>
|
||||
public string? DeviceProfileId { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the params.
|
||||
/// </summary>
|
||||
public string? Params { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the play session id.
|
||||
/// </summary>
|
||||
public string? PlaySessionId { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the tag.
|
||||
/// </summary>
|
||||
public string? Tag { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the segment container.
|
||||
/// </summary>
|
||||
public string? SegmentContainer { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the segment length.
|
||||
/// </summary>
|
||||
public int? SegmentLength { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the min segments.
|
||||
/// </summary>
|
||||
public int? MinSegments { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the position of the requested segment in ticks.
|
||||
/// </summary>
|
||||
public long CurrentRuntimeTicks { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the actual segment length in ticks.
|
||||
/// </summary>
|
||||
public long ActualSegmentLengthTicks { get; set; }
|
||||
}
|
@ -1,283 +0,0 @@
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Threading;
|
||||
using MediaBrowser.Controller.MediaEncoding;
|
||||
using MediaBrowser.Model.Dto;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace Jellyfin.Plugin.Dlna.Playback.Model;
|
||||
|
||||
/// <summary>
|
||||
/// Class TranscodingJob.
|
||||
/// </summary>
|
||||
public class TranscodingJobDto : IDisposable
|
||||
{
|
||||
/// <summary>
|
||||
/// The process lock.
|
||||
/// </summary>
|
||||
[SuppressMessage("Microsoft.Performance", "CA1051:NoVisibleInstanceFields", MessageId = "ProcessLock", Justification = "Imported from ServiceStack")]
|
||||
[SuppressMessage("Microsoft.Performance", "SA1401:PrivateField", MessageId = "ProcessLock", Justification = "Imported from ServiceStack")]
|
||||
public readonly object ProcessLock = new object();
|
||||
|
||||
/// <summary>
|
||||
/// Timer lock.
|
||||
/// </summary>
|
||||
private readonly object _timerLock = new object();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="TranscodingJobDto"/> class.
|
||||
/// </summary>
|
||||
/// <param name="logger">Instance of the <see cref="ILogger{TranscodingJobDto}"/> interface.</param>
|
||||
public TranscodingJobDto(ILogger<TranscodingJobDto> logger)
|
||||
{
|
||||
Logger = logger;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the play session identifier.
|
||||
/// </summary>
|
||||
/// <value>The play session identifier.</value>
|
||||
public string? PlaySessionId { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the live stream identifier.
|
||||
/// </summary>
|
||||
/// <value>The live stream identifier.</value>
|
||||
public string? LiveStreamId { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets a value indicating whether is live output.
|
||||
/// </summary>
|
||||
public bool IsLiveOutput { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the path.
|
||||
/// </summary>
|
||||
/// <value>The path.</value>
|
||||
public MediaSourceInfo? MediaSource { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets path.
|
||||
/// </summary>
|
||||
public string? Path { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the type.
|
||||
/// </summary>
|
||||
/// <value>The type.</value>
|
||||
public TranscodingJobType Type { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the process.
|
||||
/// </summary>
|
||||
/// <value>The process.</value>
|
||||
public Process? Process { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets logger.
|
||||
/// </summary>
|
||||
public ILogger<TranscodingJobDto> Logger { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the active request count.
|
||||
/// </summary>
|
||||
/// <value>The active request count.</value>
|
||||
public int ActiveRequestCount { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the kill timer.
|
||||
/// </summary>
|
||||
/// <value>The kill timer.</value>
|
||||
private Timer? KillTimer { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets device id.
|
||||
/// </summary>
|
||||
public string? DeviceId { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets cancellation token source.
|
||||
/// </summary>
|
||||
public CancellationTokenSource? CancellationTokenSource { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets a value indicating whether has exited.
|
||||
/// </summary>
|
||||
public bool HasExited { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets exit code.
|
||||
/// </summary>
|
||||
public int ExitCode { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets a value indicating whether is user paused.
|
||||
/// </summary>
|
||||
public bool IsUserPaused { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets id.
|
||||
/// </summary>
|
||||
public string? Id { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets framerate.
|
||||
/// </summary>
|
||||
public float? Framerate { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets completion percentage.
|
||||
/// </summary>
|
||||
public double? CompletionPercentage { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets bytes downloaded.
|
||||
/// </summary>
|
||||
public long BytesDownloaded { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets bytes transcoded.
|
||||
/// </summary>
|
||||
public long? BytesTranscoded { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets bit rate.
|
||||
/// </summary>
|
||||
public int? BitRate { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets transcoding position ticks.
|
||||
/// </summary>
|
||||
public long? TranscodingPositionTicks { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets download position ticks.
|
||||
/// </summary>
|
||||
public long? DownloadPositionTicks { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets transcoding throttler.
|
||||
/// </summary>
|
||||
public TranscodingThrottler? TranscodingThrottler { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets last ping date.
|
||||
/// </summary>
|
||||
public DateTime LastPingDate { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets ping timeout.
|
||||
/// </summary>
|
||||
public int PingTimeout { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Stop kill timer.
|
||||
/// </summary>
|
||||
public void StopKillTimer()
|
||||
{
|
||||
lock (_timerLock)
|
||||
{
|
||||
KillTimer?.Change(Timeout.Infinite, Timeout.Infinite);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Dispose kill timer.
|
||||
/// </summary>
|
||||
public void DisposeKillTimer()
|
||||
{
|
||||
lock (_timerLock)
|
||||
{
|
||||
if (KillTimer is not null)
|
||||
{
|
||||
KillTimer.Dispose();
|
||||
KillTimer = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Start kill timer.
|
||||
/// </summary>
|
||||
/// <param name="callback">Callback action.</param>
|
||||
public void StartKillTimer(Action<object?> callback)
|
||||
{
|
||||
StartKillTimer(callback, PingTimeout);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Start kill timer.
|
||||
/// </summary>
|
||||
/// <param name="callback">Callback action.</param>
|
||||
/// <param name="intervalMs">Callback interval.</param>
|
||||
public void StartKillTimer(Action<object?> callback, int intervalMs)
|
||||
{
|
||||
if (HasExited)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
lock (_timerLock)
|
||||
{
|
||||
if (KillTimer is null)
|
||||
{
|
||||
Logger.LogDebug("Starting kill timer at {0}ms. JobId {1} PlaySessionId {2}", intervalMs, Id, PlaySessionId);
|
||||
KillTimer = new Timer(new TimerCallback(callback), this, intervalMs, Timeout.Infinite);
|
||||
}
|
||||
else
|
||||
{
|
||||
Logger.LogDebug("Changing kill timer to {0}ms. JobId {1} PlaySessionId {2}", intervalMs, Id, PlaySessionId);
|
||||
KillTimer.Change(intervalMs, Timeout.Infinite);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Change kill timer if started.
|
||||
/// </summary>
|
||||
public void ChangeKillTimerIfStarted()
|
||||
{
|
||||
if (HasExited)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
lock (_timerLock)
|
||||
{
|
||||
if (KillTimer is not null)
|
||||
{
|
||||
var intervalMs = PingTimeout;
|
||||
|
||||
Logger.LogDebug("Changing kill timer to {0}ms. JobId {1} PlaySessionId {2}", intervalMs, Id, PlaySessionId);
|
||||
KillTimer.Change(intervalMs, Timeout.Infinite);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public void Dispose()
|
||||
{
|
||||
Dispose(true);
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Dispose all resources.
|
||||
/// </summary>
|
||||
/// <param name="disposing">Whether to dispose all resources.</param>
|
||||
protected virtual void Dispose(bool disposing)
|
||||
{
|
||||
if (disposing)
|
||||
{
|
||||
Process?.Dispose();
|
||||
Process = null;
|
||||
KillTimer?.Dispose();
|
||||
KillTimer = null;
|
||||
CancellationTokenSource?.Dispose();
|
||||
CancellationTokenSource = null;
|
||||
TranscodingThrottler?.Dispose();
|
||||
TranscodingThrottler = null;
|
||||
}
|
||||
}
|
||||
}
|
@ -1,182 +0,0 @@
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Jellyfin.Plugin.Dlna.Playback.Model;
|
||||
using MediaBrowser.Model.IO;
|
||||
|
||||
namespace Jellyfin.Plugin.Dlna.Playback;
|
||||
|
||||
/// <summary>
|
||||
/// A progressive file stream for transferring transcoded files as they are written to.
|
||||
/// </summary>
|
||||
public class ProgressiveFileStream : Stream
|
||||
{
|
||||
private readonly Stream _stream;
|
||||
private readonly TranscodingJobDto? _job;
|
||||
private readonly TranscodingJobHelper? _transcodingJobHelper;
|
||||
private readonly int _timeoutMs;
|
||||
private bool _disposed;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ProgressiveFileStream"/> class.
|
||||
/// </summary>
|
||||
/// <param name="filePath">The path to the transcoded file.</param>
|
||||
/// <param name="job">The transcoding job information.</param>
|
||||
/// <param name="transcodingJobHelper">The transcoding job helper.</param>
|
||||
/// <param name="timeoutMs">The timeout duration in milliseconds.</param>
|
||||
public ProgressiveFileStream(string filePath, TranscodingJobDto? job, TranscodingJobHelper transcodingJobHelper, int timeoutMs = 30000)
|
||||
{
|
||||
_job = job;
|
||||
_transcodingJobHelper = transcodingJobHelper;
|
||||
_timeoutMs = timeoutMs;
|
||||
|
||||
_stream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, IODefaults.FileStreamBufferSize, FileOptions.Asynchronous | FileOptions.SequentialScan);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ProgressiveFileStream"/> class.
|
||||
/// </summary>
|
||||
/// <param name="stream">The stream to progressively copy.</param>
|
||||
/// <param name="timeoutMs">The timeout duration in milliseconds.</param>
|
||||
public ProgressiveFileStream(Stream stream, int timeoutMs = 30000)
|
||||
{
|
||||
_job = null;
|
||||
_transcodingJobHelper = null;
|
||||
_timeoutMs = timeoutMs;
|
||||
_stream = stream;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public override bool CanRead => _stream.CanRead;
|
||||
|
||||
/// <inheritdoc />
|
||||
public override bool CanSeek => false;
|
||||
|
||||
/// <inheritdoc />
|
||||
public override bool CanWrite => false;
|
||||
|
||||
/// <inheritdoc />
|
||||
public override long Length => throw new NotSupportedException();
|
||||
|
||||
/// <inheritdoc />
|
||||
public override long Position
|
||||
{
|
||||
get => throw new NotSupportedException();
|
||||
set => throw new NotSupportedException();
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public override void Flush()
|
||||
{
|
||||
// Not supported
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public override int Read(byte[] buffer, int offset, int count)
|
||||
=> Read(buffer.AsSpan(offset, count));
|
||||
|
||||
/// <inheritdoc />
|
||||
public override int Read(Span<byte> buffer)
|
||||
{
|
||||
int totalBytesRead = 0;
|
||||
var stopwatch = Stopwatch.StartNew();
|
||||
|
||||
while (true)
|
||||
{
|
||||
totalBytesRead += _stream.Read(buffer);
|
||||
if (StopReading(totalBytesRead, stopwatch.ElapsedMilliseconds))
|
||||
{
|
||||
break;
|
||||
}
|
||||
|
||||
Thread.Sleep(50);
|
||||
}
|
||||
|
||||
UpdateBytesWritten(totalBytesRead);
|
||||
|
||||
return totalBytesRead;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public override async Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
|
||||
=> await ReadAsync(buffer.AsMemory(offset, count), cancellationToken).ConfigureAwait(false);
|
||||
|
||||
/// <inheritdoc />
|
||||
public override async ValueTask<int> ReadAsync(Memory<byte> buffer, CancellationToken cancellationToken = default)
|
||||
{
|
||||
int totalBytesRead = 0;
|
||||
var stopwatch = Stopwatch.StartNew();
|
||||
|
||||
while (true)
|
||||
{
|
||||
totalBytesRead += await _stream.ReadAsync(buffer, cancellationToken).ConfigureAwait(false);
|
||||
if (StopReading(totalBytesRead, stopwatch.ElapsedMilliseconds))
|
||||
{
|
||||
break;
|
||||
}
|
||||
|
||||
await Task.Delay(50, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
UpdateBytesWritten(totalBytesRead);
|
||||
|
||||
return totalBytesRead;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public override long Seek(long offset, SeekOrigin origin)
|
||||
=> throw new NotSupportedException();
|
||||
|
||||
/// <inheritdoc />
|
||||
public override void SetLength(long value)
|
||||
=> throw new NotSupportedException();
|
||||
|
||||
/// <inheritdoc />
|
||||
public override void Write(byte[] buffer, int offset, int count)
|
||||
=> throw new NotSupportedException();
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void Dispose(bool disposing)
|
||||
{
|
||||
if (_disposed)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
if (disposing)
|
||||
{
|
||||
_stream.Dispose();
|
||||
|
||||
if (_job is not null)
|
||||
{
|
||||
_transcodingJobHelper?.OnTranscodeEndRequest(_job);
|
||||
}
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
_disposed = true;
|
||||
base.Dispose(disposing);
|
||||
}
|
||||
}
|
||||
|
||||
private void UpdateBytesWritten(int totalBytesRead)
|
||||
{
|
||||
if (_job is not null)
|
||||
{
|
||||
_job.BytesDownloaded += totalBytesRead;
|
||||
}
|
||||
}
|
||||
|
||||
private bool StopReading(int bytesRead, long elapsed)
|
||||
{
|
||||
// It should stop reading when anything has been successfully read or if the job has exited
|
||||
// If the job is null, however, it's a live stream and will require user action to close,
|
||||
// but don't keep it open indefinitely if it isn't reading anything
|
||||
return bytesRead > 0 || (_job?.HasExited ?? elapsed >= _timeoutMs);
|
||||
}
|
||||
}
|
@ -16,6 +16,7 @@ using MediaBrowser.Controller.Configuration;
|
||||
using MediaBrowser.Controller.Devices;
|
||||
using MediaBrowser.Controller.Library;
|
||||
using MediaBrowser.Controller.MediaEncoding;
|
||||
using MediaBrowser.Controller.Streaming;
|
||||
using MediaBrowser.Model.Dlna;
|
||||
using MediaBrowser.Model.Dto;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
@ -33,7 +34,7 @@ public static class StreamingHelpers
|
||||
/// <summary>
|
||||
/// Gets the current streaming state.
|
||||
/// </summary>
|
||||
/// <param name="streamingRequest">The <see cref="StreamingRequestDto"/>.</param>
|
||||
/// <param name="streamingRequest">The <see cref="DlnaStreamingRequestDto"/>.</param>
|
||||
/// <param name="httpContext">The <see cref="HttpContext"/>.</param>
|
||||
/// <param name="mediaSourceManager">Instance of the <see cref="IMediaSourceManager"/> interface.</param>
|
||||
/// <param name="userManager">Instance of the <see cref="IUserManager"/> interface.</param>
|
||||
@ -43,12 +44,12 @@ public static class StreamingHelpers
|
||||
/// <param name="encodingHelper">Instance of <see cref="EncodingHelper"/>.</param>
|
||||
/// <param name="dlnaManager">Instance of the <see cref="IDlnaManager"/> interface.</param>
|
||||
/// <param name="deviceManager">Instance of the <see cref="IDeviceManager"/> interface.</param>
|
||||
/// <param name="transcodingJobHelper">Initialized <see cref="TranscodingJobHelper"/>.</param>
|
||||
/// <param name="transcodeManager">Initialized <see cref="ITranscodeManager"/>.</param>
|
||||
/// <param name="transcodingJobType">The <see cref="TranscodingJobType"/>.</param>
|
||||
/// <param name="cancellationToken">The <see cref="CancellationToken"/>.</param>
|
||||
/// <returns>A <see cref="Task"/> containing the current <see cref="StreamState"/>.</returns>
|
||||
public static async Task<StreamState> GetStreamingState(
|
||||
StreamingRequestDto streamingRequest,
|
||||
public static async Task<DlnaStreamState> GetStreamingState(
|
||||
DlnaStreamingRequestDto streamingRequest,
|
||||
HttpContext httpContext,
|
||||
IMediaSourceManager mediaSourceManager,
|
||||
IUserManager userManager,
|
||||
@ -58,7 +59,7 @@ public static class StreamingHelpers
|
||||
EncodingHelper encodingHelper,
|
||||
IDlnaManager dlnaManager,
|
||||
IDeviceManager deviceManager,
|
||||
TranscodingJobHelper transcodingJobHelper,
|
||||
ITranscodeManager transcodeManager,
|
||||
TranscodingJobType transcodingJobType,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
@ -93,7 +94,7 @@ public static class StreamingHelpers
|
||||
streamingRequest.StreamOptions.ContainsKey("dlnaheaders") ||
|
||||
string.Equals(httpRequest.Headers["GetContentFeatures.DLNA.ORG"], "1", StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
var state = new StreamState(mediaSourceManager, transcodingJobType, transcodingJobHelper)
|
||||
var state = new DlnaStreamState(mediaSourceManager, transcodingJobType, transcodeManager)
|
||||
{
|
||||
Request = streamingRequest,
|
||||
RequestedUrl = url,
|
||||
@ -135,7 +136,7 @@ public static class StreamingHelpers
|
||||
if (string.IsNullOrWhiteSpace(streamingRequest.LiveStreamId))
|
||||
{
|
||||
var currentJob = !string.IsNullOrWhiteSpace(streamingRequest.PlaySessionId)
|
||||
? transcodingJobHelper.GetTranscodingJob(streamingRequest.PlaySessionId)
|
||||
? transcodeManager.GetTranscodingJob(streamingRequest.PlaySessionId)
|
||||
: null;
|
||||
|
||||
if (currentJob is not null)
|
||||
@ -264,7 +265,7 @@ public static class StreamingHelpers
|
||||
/// <param name="request">The <see cref="HttpRequest"/>.</param>
|
||||
/// <param name="dlnaManager">Instance of the <see cref="IDlnaManager"/> interface.</param>
|
||||
public static void AddDlnaHeaders(
|
||||
StreamState state,
|
||||
DlnaStreamState state,
|
||||
IHeaderDictionary responseHeaders,
|
||||
bool isStaticallyStreamed,
|
||||
long? startTimeTicks,
|
||||
@ -519,7 +520,7 @@ public static class StreamingHelpers
|
||||
return Path.Combine(folder, filename + ext);
|
||||
}
|
||||
|
||||
private static void ApplyDeviceProfileSettings(StreamState state, IDlnaManager dlnaManager, IDeviceManager deviceManager, HttpRequest request, string? deviceProfileId, bool? @static)
|
||||
private static void ApplyDeviceProfileSettings(DlnaStreamState state, IDlnaManager dlnaManager, IDeviceManager deviceManager, HttpRequest request, string? deviceProfileId, bool? @static)
|
||||
{
|
||||
if (!string.IsNullOrWhiteSpace(deviceProfileId))
|
||||
{
|
||||
@ -596,7 +597,7 @@ public static class StreamingHelpers
|
||||
/// Parses the parameters.
|
||||
/// </summary>
|
||||
/// <param name="request">The request.</param>
|
||||
private static void ParseParams(StreamingRequestDto request)
|
||||
private static void ParseParams(DlnaStreamingRequestDto request)
|
||||
{
|
||||
if (string.IsNullOrEmpty(request.Params))
|
||||
{
|
||||
@ -605,7 +606,7 @@ public static class StreamingHelpers
|
||||
|
||||
var vals = request.Params.Split(';');
|
||||
|
||||
var videoRequest = request as VideoRequestDto;
|
||||
var videoRequest = request as DlnaVideoRequestDto;
|
||||
|
||||
for (var i = 0; i < vals.Length; i++)
|
||||
{
|
||||
|
@ -1,874 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.Globalization;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Jellyfin.Data.Enums;
|
||||
using Jellyfin.Plugin.Dlna.Playback.Extensions;
|
||||
using Jellyfin.Plugin.Dlna.Playback.Model;
|
||||
using MediaBrowser.Common;
|
||||
using MediaBrowser.Common.Configuration;
|
||||
using MediaBrowser.Common.Extensions;
|
||||
using MediaBrowser.Controller.Configuration;
|
||||
using MediaBrowser.Controller.Library;
|
||||
using MediaBrowser.Controller.MediaEncoding;
|
||||
using MediaBrowser.Controller.Session;
|
||||
using MediaBrowser.Model.Dlna;
|
||||
using MediaBrowser.Model.Entities;
|
||||
using MediaBrowser.Model.IO;
|
||||
using MediaBrowser.Model.MediaInfo;
|
||||
using MediaBrowser.Model.Session;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace Jellyfin.Plugin.Dlna.Playback;
|
||||
|
||||
/// <summary>
|
||||
/// Transcoding job helpers.
|
||||
/// </summary>
|
||||
public class TranscodingJobHelper : IDisposable
|
||||
{
|
||||
/// <summary>
|
||||
/// The active transcoding jobs.
|
||||
/// </summary>
|
||||
private static readonly List<TranscodingJobDto> _activeTranscodingJobs = new List<TranscodingJobDto>();
|
||||
|
||||
/// <summary>
|
||||
/// The transcoding locks.
|
||||
/// </summary>
|
||||
private static readonly Dictionary<string, SemaphoreSlim> _transcodingLocks = new Dictionary<string, SemaphoreSlim>();
|
||||
|
||||
private readonly IAttachmentExtractor _attachmentExtractor;
|
||||
private readonly IApplicationPaths _appPaths;
|
||||
private readonly EncodingHelper _encodingHelper;
|
||||
private readonly IFileSystem _fileSystem;
|
||||
private readonly ILogger<TranscodingJobHelper> _logger;
|
||||
private readonly IMediaEncoder _mediaEncoder;
|
||||
private readonly IMediaSourceManager _mediaSourceManager;
|
||||
private readonly IServerConfigurationManager _serverConfigurationManager;
|
||||
private readonly ISessionManager _sessionManager;
|
||||
private readonly ILoggerFactory _loggerFactory;
|
||||
private readonly IUserManager _userManager;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="TranscodingJobHelper"/> class.
|
||||
/// </summary>
|
||||
/// <param name="attachmentExtractor">Instance of the <see cref="IAttachmentExtractor"/> interface.</param>
|
||||
/// <param name="appPaths">Instance of the <see cref="IApplicationPaths"/> interface.</param>
|
||||
/// <param name="logger">Instance of the <see cref="ILogger{TranscodingJobHelpers}"/> interface.</param>
|
||||
/// <param name="mediaSourceManager">Instance of the <see cref="IMediaSourceManager"/> interface.</param>
|
||||
/// <param name="fileSystem">Instance of the <see cref="IFileSystem"/> interface.</param>
|
||||
/// <param name="mediaEncoder">Instance of the <see cref="IMediaEncoder"/> interface.</param>
|
||||
/// <param name="serverConfigurationManager">Instance of the <see cref="IServerConfigurationManager"/> interface.</param>
|
||||
/// <param name="sessionManager">Instance of the <see cref="ISessionManager"/> interface.</param>
|
||||
/// <param name="encodingHelper">Instance of <see cref="EncodingHelper"/>.</param>
|
||||
/// <param name="loggerFactory">Instance of the <see cref="ILoggerFactory"/> interface.</param>
|
||||
/// <param name="userManager">Instance of the <see cref="IUserManager"/> interface.</param>
|
||||
public TranscodingJobHelper(
|
||||
IAttachmentExtractor attachmentExtractor,
|
||||
IApplicationPaths appPaths,
|
||||
ILogger<TranscodingJobHelper> logger,
|
||||
IMediaSourceManager mediaSourceManager,
|
||||
IFileSystem fileSystem,
|
||||
IMediaEncoder mediaEncoder,
|
||||
IServerConfigurationManager serverConfigurationManager,
|
||||
ISessionManager sessionManager,
|
||||
EncodingHelper encodingHelper,
|
||||
ILoggerFactory loggerFactory,
|
||||
IUserManager userManager)
|
||||
{
|
||||
_attachmentExtractor = attachmentExtractor;
|
||||
_appPaths = appPaths;
|
||||
_logger = logger;
|
||||
_mediaSourceManager = mediaSourceManager;
|
||||
_fileSystem = fileSystem;
|
||||
_mediaEncoder = mediaEncoder;
|
||||
_serverConfigurationManager = serverConfigurationManager;
|
||||
_sessionManager = sessionManager;
|
||||
_encodingHelper = encodingHelper;
|
||||
_loggerFactory = loggerFactory;
|
||||
_userManager = userManager;
|
||||
|
||||
DeleteEncodedMediaCache();
|
||||
|
||||
sessionManager.PlaybackProgress += OnPlaybackProgress;
|
||||
sessionManager.PlaybackStart += OnPlaybackProgress;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Get transcoding job.
|
||||
/// </summary>
|
||||
/// <param name="playSessionId">Playback session id.</param>
|
||||
/// <returns>The transcoding job.</returns>
|
||||
public TranscodingJobDto? GetTranscodingJob(string playSessionId)
|
||||
{
|
||||
lock (_activeTranscodingJobs)
|
||||
{
|
||||
return _activeTranscodingJobs.FirstOrDefault(j => string.Equals(j.PlaySessionId, playSessionId, StringComparison.OrdinalIgnoreCase));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Get transcoding job.
|
||||
/// </summary>
|
||||
/// <param name="path">Path to the transcoding file.</param>
|
||||
/// <param name="type">The <see cref="TranscodingJobType"/>.</param>
|
||||
/// <returns>The transcoding job.</returns>
|
||||
public TranscodingJobDto? GetTranscodingJob(string path, TranscodingJobType type)
|
||||
{
|
||||
lock (_activeTranscodingJobs)
|
||||
{
|
||||
return _activeTranscodingJobs.FirstOrDefault(j => j.Type == type && string.Equals(j.Path, path, StringComparison.OrdinalIgnoreCase));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Ping transcoding job.
|
||||
/// </summary>
|
||||
/// <param name="playSessionId">Play session id.</param>
|
||||
/// <param name="isUserPaused">Is user paused.</param>
|
||||
/// <exception cref="ArgumentNullException">Play session id is null.</exception>
|
||||
public void PingTranscodingJob(string playSessionId, bool? isUserPaused)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrEmpty(playSessionId);
|
||||
|
||||
_logger.LogDebug("PingTranscodingJob PlaySessionId={0} isUsedPaused: {1}", playSessionId, isUserPaused);
|
||||
|
||||
List<TranscodingJobDto> jobs;
|
||||
|
||||
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)
|
||||
{
|
||||
_logger.LogDebug("Setting job.IsUserPaused to {0}. jobId: {1}", isUserPaused, job.Id);
|
||||
job.IsUserPaused = isUserPaused.Value;
|
||||
}
|
||||
|
||||
PingTimer(job, true);
|
||||
}
|
||||
}
|
||||
|
||||
private void PingTimer(TranscodingJobDto job, bool isProgressCheckIn)
|
||||
{
|
||||
if (job.HasExited)
|
||||
{
|
||||
job.StopKillTimer();
|
||||
return;
|
||||
}
|
||||
|
||||
var timerDuration = 10000;
|
||||
|
||||
if (job.Type != TranscodingJobType.Progressive)
|
||||
{
|
||||
timerDuration = 60000;
|
||||
}
|
||||
|
||||
job.PingTimeout = timerDuration;
|
||||
job.LastPingDate = DateTime.UtcNow;
|
||||
|
||||
// Don't start the timer for playback checkins with progressive streaming
|
||||
if (job.Type != TranscodingJobType.Progressive || !isProgressCheckIn)
|
||||
{
|
||||
job.StartKillTimer(OnTranscodeKillTimerStopped);
|
||||
}
|
||||
else
|
||||
{
|
||||
job.ChangeKillTimerIfStarted();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Called when [transcode kill timer stopped].
|
||||
/// </summary>
|
||||
/// <param name="state">The state.</param>
|
||||
private async void OnTranscodeKillTimerStopped(object? state)
|
||||
{
|
||||
var job = state as TranscodingJobDto ?? throw new ArgumentException($"{nameof(state)} is not of type {nameof(TranscodingJobDto)}", nameof(state));
|
||||
if (!job.HasExited && job.Type != TranscodingJobType.Progressive)
|
||||
{
|
||||
var timeSinceLastPing = (DateTime.UtcNow - job.LastPingDate).TotalMilliseconds;
|
||||
|
||||
if (timeSinceLastPing < job.PingTimeout)
|
||||
{
|
||||
job.StartKillTimer(OnTranscodeKillTimerStopped, job.PingTimeout);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
_logger.LogInformation("Transcoding kill timer stopped for JobId {0} PlaySessionId {1}. Killing transcoding", job.Id, job.PlaySessionId);
|
||||
|
||||
await KillTranscodingJob(job, true, path => true).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Kills the transcoding job.
|
||||
/// </summary>
|
||||
/// <param name="job">The job.</param>
|
||||
/// <param name="closeLiveStream">if set to <c>true</c> [close live stream].</param>
|
||||
/// <param name="delete">The delete.</param>
|
||||
private async Task KillTranscodingJob(TranscodingJobDto job, bool closeLiveStream, Func<string, bool> delete)
|
||||
{
|
||||
job.DisposeKillTimer();
|
||||
|
||||
_logger.LogDebug("KillTranscodingJob - JobId {0} PlaySessionId {1}. Killing transcoding", job.Id, job.PlaySessionId);
|
||||
|
||||
lock (_activeTranscodingJobs)
|
||||
{
|
||||
_activeTranscodingJobs.Remove(job);
|
||||
|
||||
if (job.CancellationTokenSource?.IsCancellationRequested == false)
|
||||
{
|
||||
job.CancellationTokenSource.Cancel();
|
||||
}
|
||||
}
|
||||
|
||||
lock (_transcodingLocks)
|
||||
{
|
||||
_transcodingLocks.Remove(job.Path!);
|
||||
}
|
||||
|
||||
lock (job.ProcessLock!)
|
||||
{
|
||||
#pragma warning disable CA1849 // Can't await in lock block
|
||||
job.TranscodingThrottler?.Stop().GetAwaiter().GetResult();
|
||||
|
||||
var process = job.Process;
|
||||
|
||||
var hasExited = job.HasExited;
|
||||
|
||||
if (!hasExited)
|
||||
{
|
||||
try
|
||||
{
|
||||
_logger.LogInformation("Stopping ffmpeg process with q command for {Path}", job.Path);
|
||||
|
||||
process!.StandardInput.WriteLine("q");
|
||||
|
||||
// Need to wait because killing is asynchronous.
|
||||
if (!process.WaitForExit(5000))
|
||||
{
|
||||
_logger.LogInformation("Killing FFmpeg process for {Path}", job.Path);
|
||||
process.Kill();
|
||||
}
|
||||
}
|
||||
catch (InvalidOperationException)
|
||||
{
|
||||
}
|
||||
}
|
||||
#pragma warning restore CA1849
|
||||
}
|
||||
|
||||
if (delete(job.Path!))
|
||||
{
|
||||
await DeletePartialStreamFiles(job.Path!, job.Type, 0, 1500).ConfigureAwait(false);
|
||||
if (job.MediaSource?.VideoType == VideoType.Dvd || job.MediaSource?.VideoType == VideoType.BluRay)
|
||||
{
|
||||
var concatFilePath = Path.Join(_serverConfigurationManager.GetTranscodePath(), job.MediaSource.Id + ".concat");
|
||||
if (File.Exists(concatFilePath))
|
||||
{
|
||||
_logger.LogInformation("Deleting ffmpeg concat configuration at {Path}", concatFilePath);
|
||||
File.Delete(concatFilePath);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (closeLiveStream && !string.IsNullOrWhiteSpace(job.LiveStreamId))
|
||||
{
|
||||
try
|
||||
{
|
||||
await _mediaSourceManager.CloseLiveStream(job.LiveStreamId).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error closing live stream for {Path}", job.Path);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async Task DeletePartialStreamFiles(string path, TranscodingJobType jobType, int retryCount, int delayMs)
|
||||
{
|
||||
if (retryCount >= 10)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_logger.LogInformation("Deleting partial stream file(s) {Path}", path);
|
||||
|
||||
await Task.Delay(delayMs).ConfigureAwait(false);
|
||||
|
||||
try
|
||||
{
|
||||
if (jobType == TranscodingJobType.Progressive)
|
||||
{
|
||||
DeleteProgressivePartialStreamFiles(path);
|
||||
}
|
||||
else
|
||||
{
|
||||
DeleteHlsPartialStreamFiles(path);
|
||||
}
|
||||
}
|
||||
catch (IOException ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error deleting partial stream file(s) {Path}", path);
|
||||
|
||||
await DeletePartialStreamFiles(path, jobType, retryCount + 1, 500).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error deleting partial stream file(s) {Path}", path);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Deletes the progressive partial stream files.
|
||||
/// </summary>
|
||||
/// <param name="outputFilePath">The output file path.</param>
|
||||
private void DeleteProgressivePartialStreamFiles(string outputFilePath)
|
||||
{
|
||||
if (File.Exists(outputFilePath))
|
||||
{
|
||||
_fileSystem.DeleteFile(outputFilePath);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Deletes the HLS partial stream files.
|
||||
/// </summary>
|
||||
/// <param name="outputFilePath">The output file path.</param>
|
||||
private void DeleteHlsPartialStreamFiles(string outputFilePath)
|
||||
{
|
||||
var directory = Path.GetDirectoryName(outputFilePath)
|
||||
?? throw new ArgumentException("Path can't be a root directory.", nameof(outputFilePath));
|
||||
|
||||
var name = Path.GetFileNameWithoutExtension(outputFilePath);
|
||||
|
||||
var filesToDelete = _fileSystem.GetFilePaths(directory)
|
||||
.Where(f => f.IndexOf(name, StringComparison.OrdinalIgnoreCase) != -1);
|
||||
|
||||
List<Exception>? exs = null;
|
||||
foreach (var file in filesToDelete)
|
||||
{
|
||||
try
|
||||
{
|
||||
_logger.LogDebug("Deleting HLS file {0}", file);
|
||||
_fileSystem.DeleteFile(file);
|
||||
}
|
||||
catch (IOException ex)
|
||||
{
|
||||
(exs ??= new List<Exception>(4)).Add(ex);
|
||||
_logger.LogError(ex, "Error deleting HLS file {Path}", file);
|
||||
}
|
||||
}
|
||||
|
||||
if (exs is not null)
|
||||
{
|
||||
throw new AggregateException("Error deleting HLS files", exs);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Report the transcoding progress to the session manager.
|
||||
/// </summary>
|
||||
/// <param name="job">The <see cref="TranscodingJobDto"/> of which the progress will be reported.</param>
|
||||
/// <param name="state">The <see cref="StreamState"/> of the current transcoding job.</param>
|
||||
/// <param name="transcodingPosition">The current transcoding position.</param>
|
||||
/// <param name="framerate">The framerate of the transcoding job.</param>
|
||||
/// <param name="percentComplete">The completion percentage of the transcode.</param>
|
||||
/// <param name="bytesTranscoded">The number of bytes transcoded.</param>
|
||||
/// <param name="bitRate">The bitrate of the transcoding job.</param>
|
||||
public void ReportTranscodingProgress(
|
||||
TranscodingJobDto job,
|
||||
StreamState state,
|
||||
TimeSpan? transcodingPosition,
|
||||
float? framerate,
|
||||
double? percentComplete,
|
||||
long? bytesTranscoded,
|
||||
int? bitRate)
|
||||
{
|
||||
var ticks = transcodingPosition?.Ticks;
|
||||
|
||||
if (job is not null)
|
||||
{
|
||||
job.Framerate = framerate;
|
||||
job.CompletionPercentage = percentComplete;
|
||||
job.TranscodingPositionTicks = ticks;
|
||||
job.BytesTranscoded = bytesTranscoded;
|
||||
job.BitRate = bitRate;
|
||||
}
|
||||
|
||||
var deviceId = state.Request.DeviceId;
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(deviceId))
|
||||
{
|
||||
var audioCodec = state.ActualOutputAudioCodec;
|
||||
var videoCodec = state.ActualOutputVideoCodec;
|
||||
var hardwareAccelerationTypeString = _serverConfigurationManager.GetEncodingOptions().HardwareAccelerationType;
|
||||
HardwareEncodingType? hardwareAccelerationType = null;
|
||||
if (Enum.TryParse<HardwareEncodingType>(hardwareAccelerationTypeString, out var parsedHardwareAccelerationType))
|
||||
{
|
||||
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
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Starts FFmpeg.
|
||||
/// </summary>
|
||||
/// <param name="state">The state.</param>
|
||||
/// <param name="outputPath">The output path.</param>
|
||||
/// <param name="commandLineArguments">The command line arguments for FFmpeg.</param>
|
||||
/// <param name="request">The <see cref="HttpRequest"/>.</param>
|
||||
/// <param name="transcodingJobType">The <see cref="TranscodingJobType"/>.</param>
|
||||
/// <param name="cancellationTokenSource">The cancellation token source.</param>
|
||||
/// <param name="workingDirectory">The working directory.</param>
|
||||
/// <returns>Task.</returns>
|
||||
public async Task<TranscodingJobDto> StartFfMpeg(
|
||||
StreamState state,
|
||||
string outputPath,
|
||||
string commandLineArguments,
|
||||
HttpRequest request,
|
||||
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);
|
||||
|
||||
await AcquireResources(state, cancellationTokenSource).ConfigureAwait(false);
|
||||
|
||||
if (state.VideoRequest is not null && !EncodingHelper.IsCopyCodec(state.OutputVideoCodec))
|
||||
{
|
||||
var userId = request.HttpContext.User.GetUserId();
|
||||
var user = userId.Equals(default) ? null : _userManager.GetUserById(userId);
|
||||
if (user is not null && !user.HasPermission(PermissionKind.EnableVideoPlaybackTranscoding))
|
||||
{
|
||||
this.OnTranscodeFailedToStart(outputPath, transcodingJobType, state);
|
||||
|
||||
throw new ArgumentException("User does not have access to video transcoding.");
|
||||
}
|
||||
}
|
||||
|
||||
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);
|
||||
if (state.VideoType != VideoType.Dvd)
|
||||
{
|
||||
await _attachmentExtractor.ExtractAllAttachments(state.MediaPath, state.MediaSource, attachmentPath, cancellationTokenSource.Token).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
if (state.SubtitleStream.IsExternal && Path.GetExtension(state.SubtitleStream.Path.AsSpan()).Equals(".mks", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
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);
|
||||
|
||||
await _attachmentExtractor.ExtractAllAttachmentsExternal(subtitlePathArgument, subtitleId, attachmentPath, cancellationTokenSource.Token).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
var process = new Process
|
||||
{
|
||||
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
|
||||
};
|
||||
|
||||
var transcodingJob = this.OnTranscodeBeginning(
|
||||
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-";
|
||||
}
|
||||
|
||||
var logFilePath = Path.Combine(
|
||||
_serverConfigurationManager.ApplicationPaths.LogDirectoryPath,
|
||||
$"{logFilePrefix}{DateTime.Now:yyyy-MM-dd_HH-mm-ss}_{state.Request.MediaSourceId}_{Guid.NewGuid().ToString()[..8]}.log");
|
||||
|
||||
// FFmpeg writes debug/error info to stderr. This is useful when debugging so let's put it in the log directory.
|
||||
Stream logStream = new FileStream(logFilePath, FileMode.Create, FileAccess.Write, FileShare.Read, IODefaults.FileStreamBufferSize, FileOptions.Asynchronous);
|
||||
|
||||
var commandLineLogMessage = process.StartInfo.FileName + " " + process.StartInfo.Arguments;
|
||||
var commandLineLogMessageBytes = Encoding.UTF8.GetBytes(request.Path + Environment.NewLine + Environment.NewLine + JsonSerializer.Serialize(state.MediaSource) + Environment.NewLine + Environment.NewLine + commandLineLogMessage + Environment.NewLine + Environment.NewLine);
|
||||
await logStream.WriteAsync(commandLineLogMessageBytes, cancellationTokenSource.Token).ConfigureAwait(false);
|
||||
|
||||
process.Exited += (sender, args) => OnFfMpegProcessExited(process, transcodingJob, state);
|
||||
|
||||
try
|
||||
{
|
||||
process.Start();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error starting FFmpeg");
|
||||
|
||||
this.OnTranscodeFailedToStart(outputPath, transcodingJobType, state);
|
||||
|
||||
throw;
|
||||
}
|
||||
|
||||
_logger.LogDebug("Launched FFmpeg process");
|
||||
state.TranscodingJob = transcodingJob;
|
||||
|
||||
// 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(state, process.StandardError, logStream);
|
||||
|
||||
// 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);
|
||||
}
|
||||
|
||||
_logger.LogDebug("File {0} created or transcoding has finished", ffmpegTargetFile);
|
||||
|
||||
if (state.IsInputVideo && transcodingJob.Type == TranscodingJobType.Progressive && !transcodingJob.HasExited)
|
||||
{
|
||||
await Task.Delay(1000, cancellationTokenSource.Token).ConfigureAwait(false);
|
||||
|
||||
if (state.ReadInputAtNativeFramerate && !transcodingJob.HasExited)
|
||||
{
|
||||
await Task.Delay(1500, cancellationTokenSource.Token).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
if (!transcodingJob.HasExited)
|
||||
{
|
||||
StartThrottler(state, transcodingJob);
|
||||
}
|
||||
else if (transcodingJob.ExitCode != 0)
|
||||
{
|
||||
throw new FfmpegException(string.Format(CultureInfo.InvariantCulture, "FFmpeg exited with code {0}", transcodingJob.ExitCode));
|
||||
}
|
||||
|
||||
_logger.LogDebug("StartFfMpeg() finished successfully");
|
||||
|
||||
return transcodingJob;
|
||||
}
|
||||
|
||||
private void StartThrottler(StreamState state, TranscodingJobDto transcodingJob)
|
||||
{
|
||||
if (EnableThrottling(state))
|
||||
{
|
||||
transcodingJob.TranscodingThrottler = new TranscodingThrottler(transcodingJob, _loggerFactory.CreateLogger<TranscodingThrottler>(), _serverConfigurationManager, _fileSystem, _mediaEncoder);
|
||||
transcodingJob.TranscodingThrottler.Start();
|
||||
}
|
||||
}
|
||||
|
||||
private bool EnableThrottling(StreamState state)
|
||||
{
|
||||
var encodingOptions = _serverConfigurationManager.GetEncodingOptions();
|
||||
|
||||
return state.InputProtocol == MediaProtocol.File &&
|
||||
state.RunTimeTicks.HasValue &&
|
||||
state.RunTimeTicks.Value >= TimeSpan.FromMinutes(5).Ticks &&
|
||||
state.IsInputVideo &&
|
||||
state.VideoType == VideoType.VideoFile;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Called when [transcode beginning].
|
||||
/// </summary>
|
||||
/// <param name="path">The path.</param>
|
||||
/// <param name="playSessionId">The play session identifier.</param>
|
||||
/// <param name="liveStreamId">The live stream identifier.</param>
|
||||
/// <param name="transcodingJobId">The transcoding job identifier.</param>
|
||||
/// <param name="type">The type.</param>
|
||||
/// <param name="process">The process.</param>
|
||||
/// <param name="deviceId">The device id.</param>
|
||||
/// <param name="state">The state.</param>
|
||||
/// <param name="cancellationTokenSource">The cancellation token source.</param>
|
||||
/// <returns>TranscodingJob.</returns>
|
||||
public TranscodingJobDto OnTranscodeBeginning(
|
||||
string path,
|
||||
string? playSessionId,
|
||||
string? liveStreamId,
|
||||
string transcodingJobId,
|
||||
TranscodingJobType type,
|
||||
Process process,
|
||||
string? deviceId,
|
||||
StreamState state,
|
||||
CancellationTokenSource cancellationTokenSource)
|
||||
{
|
||||
lock (_activeTranscodingJobs)
|
||||
{
|
||||
var job = new TranscodingJobDto(_loggerFactory.CreateLogger<TranscodingJobDto>())
|
||||
{
|
||||
Type = type,
|
||||
Path = path,
|
||||
Process = process,
|
||||
ActiveRequestCount = 1,
|
||||
DeviceId = deviceId,
|
||||
CancellationTokenSource = cancellationTokenSource,
|
||||
Id = transcodingJobId,
|
||||
PlaySessionId = playSessionId,
|
||||
LiveStreamId = liveStreamId,
|
||||
MediaSource = state.MediaSource
|
||||
};
|
||||
|
||||
_activeTranscodingJobs.Add(job);
|
||||
|
||||
ReportTranscodingProgress(job, state, null, null, null, null, null);
|
||||
|
||||
return job;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Called when [transcode end].
|
||||
/// </summary>
|
||||
/// <param name="job">The transcode job.</param>
|
||||
public void OnTranscodeEndRequest(TranscodingJobDto job)
|
||||
{
|
||||
job.ActiveRequestCount--;
|
||||
_logger.LogDebug("OnTranscodeEndRequest job.ActiveRequestCount={ActiveRequestCount}", job.ActiveRequestCount);
|
||||
if (job.ActiveRequestCount <= 0)
|
||||
{
|
||||
PingTimer(job, false);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// <summary>
|
||||
/// The progressive
|
||||
/// </summary>
|
||||
/// Called when [transcode failed to start].
|
||||
/// </summary>
|
||||
/// <param name="path">The path.</param>
|
||||
/// <param name="type">The type.</param>
|
||||
/// <param name="state">The state.</param>
|
||||
public void OnTranscodeFailedToStart(string path, TranscodingJobType type, StreamState state)
|
||||
{
|
||||
lock (_activeTranscodingJobs)
|
||||
{
|
||||
var job = _activeTranscodingJobs.FirstOrDefault(j => j.Type == type && string.Equals(j.Path, path, StringComparison.OrdinalIgnoreCase));
|
||||
|
||||
if (job is not null)
|
||||
{
|
||||
_activeTranscodingJobs.Remove(job);
|
||||
}
|
||||
}
|
||||
|
||||
lock (_transcodingLocks)
|
||||
{
|
||||
_transcodingLocks.Remove(path);
|
||||
}
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(state.Request.DeviceId))
|
||||
{
|
||||
_sessionManager.ClearTranscodingInfo(state.Request.DeviceId);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Processes the exited.
|
||||
/// </summary>
|
||||
/// <param name="process">The process.</param>
|
||||
/// <param name="job">The job.</param>
|
||||
/// <param name="state">The state.</param>
|
||||
private void OnFfMpegProcessExited(Process process, TranscodingJobDto job, StreamState state)
|
||||
{
|
||||
job.HasExited = true;
|
||||
job.ExitCode = process.ExitCode;
|
||||
|
||||
ReportTranscodingProgress(job, state, null, null, null, null, null);
|
||||
|
||||
_logger.LogDebug("Disposing stream resources");
|
||||
state.Dispose();
|
||||
|
||||
if (process.ExitCode == 0)
|
||||
{
|
||||
_logger.LogInformation("FFmpeg exited with code 0");
|
||||
}
|
||||
else
|
||||
{
|
||||
_logger.LogError("FFmpeg exited with code {0}", process.ExitCode);
|
||||
}
|
||||
|
||||
job.Dispose();
|
||||
}
|
||||
|
||||
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);
|
||||
|
||||
if (state.VideoRequest is not null)
|
||||
{
|
||||
_encodingHelper.TryStreamCopy(state);
|
||||
}
|
||||
}
|
||||
|
||||
if (state.MediaSource.BufferMs.HasValue)
|
||||
{
|
||||
await Task.Delay(state.MediaSource.BufferMs.Value, cancellationTokenSource.Token).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Called when [transcode begin request].
|
||||
/// </summary>
|
||||
/// <param name="path">The path.</param>
|
||||
/// <param name="type">The type.</param>
|
||||
/// <returns>The <see cref="TranscodingJobDto"/>.</returns>
|
||||
public TranscodingJobDto? OnTranscodeBeginRequest(string path, TranscodingJobType type)
|
||||
{
|
||||
lock (_activeTranscodingJobs)
|
||||
{
|
||||
var job = _activeTranscodingJobs.FirstOrDefault(j => j.Type == type && string.Equals(j.Path, path, StringComparison.OrdinalIgnoreCase));
|
||||
|
||||
if (job is null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
OnTranscodeBeginRequest(job);
|
||||
|
||||
return job;
|
||||
}
|
||||
}
|
||||
|
||||
private void OnTranscodeBeginRequest(TranscodingJobDto job)
|
||||
{
|
||||
job.ActiveRequestCount++;
|
||||
|
||||
if (string.IsNullOrWhiteSpace(job.PlaySessionId) || job.Type == TranscodingJobType.Progressive)
|
||||
{
|
||||
job.StopKillTimer();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the transcoding lock.
|
||||
/// </summary>
|
||||
/// <param name="outputPath">The output path of the transcoded file.</param>
|
||||
/// <returns>A <see cref="SemaphoreSlim"/>.</returns>
|
||||
public SemaphoreSlim GetTranscodingLock(string outputPath)
|
||||
{
|
||||
lock (_transcodingLocks)
|
||||
{
|
||||
if (!_transcodingLocks.TryGetValue(outputPath, out SemaphoreSlim? result))
|
||||
{
|
||||
result = new SemaphoreSlim(1, 1);
|
||||
_transcodingLocks[outputPath] = result;
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
private void OnPlaybackProgress(object? sender, PlaybackProgressEventArgs e)
|
||||
{
|
||||
if (!string.IsNullOrWhiteSpace(e.PlaySessionId))
|
||||
{
|
||||
PingTranscodingJob(e.PlaySessionId, e.IsPaused);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Deletes the encoded media cache.
|
||||
/// </summary>
|
||||
private void DeleteEncodedMediaCache()
|
||||
{
|
||||
var path = _serverConfigurationManager.GetTranscodePath();
|
||||
if (!Directory.Exists(path))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
foreach (var file in _fileSystem.GetFilePaths(path, true))
|
||||
{
|
||||
_fileSystem.DeleteFile(file);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Dispose transcoding job helper.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
Dispose(true);
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Dispose throttler.
|
||||
/// </summary>
|
||||
/// <param name="disposing">Disposing.</param>
|
||||
protected virtual void Dispose(bool disposing)
|
||||
{
|
||||
if (disposing)
|
||||
{
|
||||
_loggerFactory.Dispose();
|
||||
_sessionManager.PlaybackProgress -= OnPlaybackProgress;
|
||||
_sessionManager.PlaybackStart -= OnPlaybackProgress;
|
||||
}
|
||||
}
|
||||
}
|
@ -1,220 +0,0 @@
|
||||
using System;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Jellyfin.Plugin.Dlna.Playback.Model;
|
||||
using MediaBrowser.Common.Configuration;
|
||||
using MediaBrowser.Controller.MediaEncoding;
|
||||
using MediaBrowser.Model.Configuration;
|
||||
using MediaBrowser.Model.IO;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace Jellyfin.Plugin.Dlna.Playback;
|
||||
|
||||
/// <summary>
|
||||
/// Transcoding throttler.
|
||||
/// </summary>
|
||||
public class TranscodingThrottler : IDisposable
|
||||
{
|
||||
private readonly TranscodingJobDto _job;
|
||||
private readonly ILogger<TranscodingThrottler> _logger;
|
||||
private readonly IConfigurationManager _config;
|
||||
private readonly IFileSystem _fileSystem;
|
||||
private readonly IMediaEncoder _mediaEncoder;
|
||||
private Timer? _timer;
|
||||
private bool _isPaused;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="TranscodingThrottler"/> class.
|
||||
/// </summary>
|
||||
/// <param name="job">Transcoding job dto.</param>
|
||||
/// <param name="logger">Instance of the <see cref="ILogger{TranscodingThrottler}"/> interface.</param>
|
||||
/// <param name="config">Instance of the <see cref="IConfigurationManager"/> interface.</param>
|
||||
/// <param name="fileSystem">Instance of the <see cref="IFileSystem"/> interface.</param>
|
||||
/// <param name="mediaEncoder">Instance of the <see cref="IMediaEncoder"/> interface.</param>
|
||||
public TranscodingThrottler(TranscodingJobDto job, ILogger<TranscodingThrottler> logger, IConfigurationManager config, IFileSystem fileSystem, IMediaEncoder mediaEncoder)
|
||||
{
|
||||
_job = job;
|
||||
_logger = logger;
|
||||
_config = config;
|
||||
_fileSystem = fileSystem;
|
||||
_mediaEncoder = mediaEncoder;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Start timer.
|
||||
/// </summary>
|
||||
public void Start()
|
||||
{
|
||||
_timer = new Timer(TimerCallback, null, 5000, 5000);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Unpause transcoding.
|
||||
/// </summary>
|
||||
/// <returns>A <see cref="Task"/>.</returns>
|
||||
public async Task UnpauseTranscoding()
|
||||
{
|
||||
if (_isPaused)
|
||||
{
|
||||
_logger.LogDebug("Sending resume command to ffmpeg");
|
||||
|
||||
try
|
||||
{
|
||||
var resumeKey = _mediaEncoder.IsPkeyPauseSupported ? "u" : Environment.NewLine;
|
||||
await _job.Process!.StandardInput.WriteAsync(resumeKey).ConfigureAwait(false);
|
||||
_isPaused = false;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error resuming transcoding");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Stop throttler.
|
||||
/// </summary>
|
||||
/// <returns>A <see cref="Task"/>.</returns>
|
||||
public async Task Stop()
|
||||
{
|
||||
DisposeTimer();
|
||||
await UnpauseTranscoding().ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Dispose throttler.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
Dispose(true);
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Dispose throttler.
|
||||
/// </summary>
|
||||
/// <param name="disposing">Disposing.</param>
|
||||
protected virtual void Dispose(bool disposing)
|
||||
{
|
||||
if (disposing)
|
||||
{
|
||||
DisposeTimer();
|
||||
}
|
||||
}
|
||||
|
||||
private EncodingOptions GetOptions()
|
||||
{
|
||||
return _config.GetEncodingOptions();
|
||||
}
|
||||
|
||||
private async void TimerCallback(object? state)
|
||||
{
|
||||
if (_job.HasExited)
|
||||
{
|
||||
DisposeTimer();
|
||||
return;
|
||||
}
|
||||
|
||||
var options = GetOptions();
|
||||
|
||||
if (options.EnableThrottling && IsThrottleAllowed(_job, options.ThrottleDelaySeconds))
|
||||
{
|
||||
await PauseTranscoding().ConfigureAwait(false);
|
||||
}
|
||||
else
|
||||
{
|
||||
await UnpauseTranscoding().ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
private async Task PauseTranscoding()
|
||||
{
|
||||
if (!_isPaused)
|
||||
{
|
||||
var pauseKey = _mediaEncoder.IsPkeyPauseSupported ? "p" : "c";
|
||||
|
||||
_logger.LogDebug("Sending pause command [{Key}] to ffmpeg", pauseKey);
|
||||
|
||||
try
|
||||
{
|
||||
await _job.Process!.StandardInput.WriteAsync(pauseKey).ConfigureAwait(false);
|
||||
_isPaused = true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error pausing transcoding");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private bool IsThrottleAllowed(TranscodingJobDto job, int thresholdSeconds)
|
||||
{
|
||||
var bytesDownloaded = job.BytesDownloaded;
|
||||
var transcodingPositionTicks = job.TranscodingPositionTicks ?? 0;
|
||||
var downloadPositionTicks = job.DownloadPositionTicks ?? 0;
|
||||
|
||||
var path = job.Path ?? throw new ArgumentException("Path can't be null.");
|
||||
|
||||
var gapLengthInTicks = TimeSpan.FromSeconds(thresholdSeconds).Ticks;
|
||||
|
||||
if (downloadPositionTicks > 0 && transcodingPositionTicks > 0)
|
||||
{
|
||||
// HLS - time-based consideration
|
||||
|
||||
var targetGap = gapLengthInTicks;
|
||||
var gap = transcodingPositionTicks - downloadPositionTicks;
|
||||
|
||||
if (gap < targetGap)
|
||||
{
|
||||
_logger.LogDebug("Not throttling transcoder gap {0} target gap {1}", gap, targetGap);
|
||||
return false;
|
||||
}
|
||||
|
||||
_logger.LogDebug("Throttling transcoder gap {0} target gap {1}", gap, targetGap);
|
||||
return true;
|
||||
}
|
||||
|
||||
if (bytesDownloaded > 0 && transcodingPositionTicks > 0)
|
||||
{
|
||||
// Progressive Streaming - byte-based consideration
|
||||
|
||||
try
|
||||
{
|
||||
var bytesTranscoded = job.BytesTranscoded ?? _fileSystem.GetFileInfo(path).Length;
|
||||
|
||||
// Estimate the bytes the transcoder should be ahead
|
||||
double gapFactor = gapLengthInTicks;
|
||||
gapFactor /= transcodingPositionTicks;
|
||||
var targetGap = bytesTranscoded * gapFactor;
|
||||
|
||||
var gap = bytesTranscoded - bytesDownloaded;
|
||||
|
||||
if (gap < targetGap)
|
||||
{
|
||||
_logger.LogDebug("Not throttling transcoder gap {0} target gap {1} bytes downloaded {2}", gap, targetGap, bytesDownloaded);
|
||||
return false;
|
||||
}
|
||||
|
||||
_logger.LogDebug("Throttling transcoder gap {0} target gap {1} bytes downloaded {2}", gap, targetGap, bytesDownloaded);
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error getting output size");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
_logger.LogDebug("No throttle data for {Path}", path);
|
||||
return false;
|
||||
}
|
||||
|
||||
private void DisposeTimer()
|
||||
{
|
||||
if (_timer is not null)
|
||||
{
|
||||
_timer.Dispose();
|
||||
_timer = null;
|
||||
}
|
||||
}
|
||||
}
|
@ -49,7 +49,6 @@ public class DlnaServiceRegistrator : IPluginServiceRegistrator
|
||||
services.AddSingleton<IConnectionManager, ConnectionManagerService>();
|
||||
services.AddSingleton<IMediaReceiverRegistrar, MediaReceiverRegistrarService>();
|
||||
|
||||
services.AddSingleton<TranscodingJobHelper>();
|
||||
services.AddScoped<AudioHelper>();
|
||||
services.AddScoped<DynamicHlsHelper>();
|
||||
|
||||
|
Loading…
Reference in New Issue
Block a user