repo creation with initial code after cloning public repo
This commit is contained in:
@@ -0,0 +1,61 @@
|
||||
#pragma warning disable CA1826 // Do not use Enumerable methods on indexable collections
|
||||
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using Jellyfin.MediaEncoding.Hls.Extractors;
|
||||
using Jellyfin.MediaEncoding.Keyframes;
|
||||
using MediaBrowser.Controller.Persistence;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace Jellyfin.MediaEncoding.Hls.Cache;
|
||||
|
||||
/// <inheritdoc />
|
||||
public class CacheDecorator : IKeyframeExtractor
|
||||
{
|
||||
private readonly IKeyframeRepository _keyframeRepository;
|
||||
private readonly IKeyframeExtractor _keyframeExtractor;
|
||||
private readonly ILogger<CacheDecorator> _logger;
|
||||
private readonly string _keyframeExtractorName;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="CacheDecorator"/> class.
|
||||
/// </summary>
|
||||
/// <param name="keyframeRepository">An instance of the <see cref="IKeyframeRepository"/> interface.</param>
|
||||
/// <param name="keyframeExtractor">An instance of the <see cref="IKeyframeExtractor"/> interface.</param>
|
||||
/// <param name="logger">An instance of the <see cref="ILogger{CacheDecorator}"/> interface.</param>
|
||||
public CacheDecorator(IKeyframeRepository keyframeRepository, IKeyframeExtractor keyframeExtractor, ILogger<CacheDecorator> logger)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(keyframeRepository);
|
||||
ArgumentNullException.ThrowIfNull(keyframeExtractor);
|
||||
|
||||
_keyframeRepository = keyframeRepository;
|
||||
_keyframeExtractor = keyframeExtractor;
|
||||
_logger = logger;
|
||||
_keyframeExtractorName = keyframeExtractor.GetType().Name;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public bool IsMetadataBased => _keyframeExtractor.IsMetadataBased;
|
||||
|
||||
/// <inheritdoc />
|
||||
public bool TryExtractKeyframes(Guid itemId, string filePath, [NotNullWhen(true)] out KeyframeData? keyframeData)
|
||||
{
|
||||
keyframeData = _keyframeRepository.GetKeyframeData(itemId).FirstOrDefault();
|
||||
if (keyframeData is null)
|
||||
{
|
||||
if (!_keyframeExtractor.TryExtractKeyframes(itemId, filePath, out var result))
|
||||
{
|
||||
_logger.LogDebug("Failed to extract keyframes using {ExtractorName}", _keyframeExtractorName);
|
||||
return false;
|
||||
}
|
||||
|
||||
_logger.LogDebug("Successfully extracted keyframes using {ExtractorName}", _keyframeExtractorName);
|
||||
keyframeData = result;
|
||||
_keyframeRepository.SaveKeyframeDataAsync(itemId, keyframeData, CancellationToken.None).GetAwaiter().GetResult();
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
+36
@@ -0,0 +1,36 @@
|
||||
using System;
|
||||
using Jellyfin.MediaEncoding.Hls.Cache;
|
||||
using Jellyfin.MediaEncoding.Hls.Extractors;
|
||||
using Jellyfin.MediaEncoding.Hls.Playlist;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
|
||||
namespace Jellyfin.MediaEncoding.Hls.Extensions;
|
||||
|
||||
/// <summary>
|
||||
/// Extensions for the <see cref="IServiceCollection"/> interface.
|
||||
/// </summary>
|
||||
public static class MediaEncodingHlsServiceCollectionExtensions
|
||||
{
|
||||
/// <summary>
|
||||
/// Adds the hls playlist generators to the <see cref="IServiceCollection"/>.
|
||||
/// </summary>
|
||||
/// <param name="serviceCollection">An instance of the <see cref="IServiceCollection"/> interface.</param>
|
||||
/// <returns>The updated service collection.</returns>
|
||||
public static IServiceCollection AddHlsPlaylistGenerator(this IServiceCollection serviceCollection)
|
||||
{
|
||||
serviceCollection.AddSingletonWithDecorator(typeof(FfProbeKeyframeExtractor));
|
||||
serviceCollection.AddSingletonWithDecorator(typeof(MatroskaKeyframeExtractor));
|
||||
serviceCollection.AddSingleton<IDynamicHlsPlaylistGenerator, DynamicHlsPlaylistGenerator>();
|
||||
return serviceCollection;
|
||||
}
|
||||
|
||||
private static void AddSingletonWithDecorator(this IServiceCollection serviceCollection, Type type)
|
||||
{
|
||||
serviceCollection.AddSingleton<IKeyframeExtractor>(serviceProvider =>
|
||||
{
|
||||
var extractor = ActivatorUtilities.CreateInstance(serviceProvider, type);
|
||||
var decorator = ActivatorUtilities.CreateInstance<CacheDecorator>(serviceProvider, extractor);
|
||||
return decorator;
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.IO;
|
||||
using Emby.Naming.Common;
|
||||
using Jellyfin.Extensions;
|
||||
using Jellyfin.MediaEncoding.Keyframes;
|
||||
using MediaBrowser.Controller.MediaEncoding;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Extractor = Jellyfin.MediaEncoding.Keyframes.FfProbe.FfProbeKeyframeExtractor;
|
||||
|
||||
namespace Jellyfin.MediaEncoding.Hls.Extractors;
|
||||
|
||||
/// <inheritdoc />
|
||||
public class FfProbeKeyframeExtractor : IKeyframeExtractor
|
||||
{
|
||||
private readonly IMediaEncoder _mediaEncoder;
|
||||
private readonly NamingOptions _namingOptions;
|
||||
private readonly ILogger<FfProbeKeyframeExtractor> _logger;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="FfProbeKeyframeExtractor"/> class.
|
||||
/// </summary>
|
||||
/// <param name="mediaEncoder">An instance of the <see cref="IMediaEncoder"/> interface.</param>
|
||||
/// <param name="namingOptions">An instance of <see cref="NamingOptions"/>.</param>
|
||||
/// <param name="logger">An instance of the <see cref="ILogger{FfprobeKeyframeExtractor}"/> interface.</param>
|
||||
public FfProbeKeyframeExtractor(IMediaEncoder mediaEncoder, NamingOptions namingOptions, ILogger<FfProbeKeyframeExtractor> logger)
|
||||
{
|
||||
_mediaEncoder = mediaEncoder;
|
||||
_namingOptions = namingOptions;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public bool IsMetadataBased => false;
|
||||
|
||||
/// <inheritdoc />
|
||||
public bool TryExtractKeyframes(Guid itemId, string filePath, [NotNullWhen(true)] out KeyframeData? keyframeData)
|
||||
{
|
||||
if (!_namingOptions.VideoFileExtensions.Contains(Path.GetExtension(filePath.AsSpan()), StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
keyframeData = null;
|
||||
return false;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
keyframeData = Extractor.GetKeyframeData(_mediaEncoder.ProbePath, filePath);
|
||||
return keyframeData.KeyframeTicks.Count > 0;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Extracting keyframes from {FilePath} using ffprobe failed", filePath);
|
||||
}
|
||||
|
||||
keyframeData = null;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using Jellyfin.MediaEncoding.Keyframes;
|
||||
|
||||
namespace Jellyfin.MediaEncoding.Hls.Extractors;
|
||||
|
||||
/// <summary>
|
||||
/// Keyframe extractor.
|
||||
/// </summary>
|
||||
public interface IKeyframeExtractor
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets a value indicating whether the extractor is based on container metadata.
|
||||
/// </summary>
|
||||
bool IsMetadataBased { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Attempt to extract keyframes.
|
||||
/// </summary>
|
||||
/// <param name="itemId">The item id.</param>
|
||||
/// <param name="filePath">The path to the file.</param>
|
||||
/// <param name="keyframeData">The keyframes.</param>
|
||||
/// <returns>A value indicating whether the keyframe extraction was successful.</returns>
|
||||
bool TryExtractKeyframes(Guid itemId, string filePath, [NotNullWhen(true)] out KeyframeData? keyframeData);
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using Jellyfin.MediaEncoding.Keyframes;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Extractor = Jellyfin.MediaEncoding.Keyframes.Matroska.MatroskaKeyframeExtractor;
|
||||
|
||||
namespace Jellyfin.MediaEncoding.Hls.Extractors;
|
||||
|
||||
/// <inheritdoc />
|
||||
public class MatroskaKeyframeExtractor : IKeyframeExtractor
|
||||
{
|
||||
private readonly ILogger<MatroskaKeyframeExtractor> _logger;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="MatroskaKeyframeExtractor"/> class.
|
||||
/// </summary>
|
||||
/// <param name="logger">An instance of the <see cref="ILogger{MatroskaKeyframeExtractor}"/> interface.</param>
|
||||
public MatroskaKeyframeExtractor(ILogger<MatroskaKeyframeExtractor> logger)
|
||||
{
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public bool IsMetadataBased => true;
|
||||
|
||||
/// <inheritdoc />
|
||||
public bool TryExtractKeyframes(Guid itemId, string filePath, [NotNullWhen(true)] out KeyframeData? keyframeData)
|
||||
{
|
||||
if (!filePath.AsSpan().EndsWith(".mkv", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
keyframeData = null;
|
||||
return false;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
keyframeData = Extractor.GetKeyframeData(filePath);
|
||||
return keyframeData.KeyframeTicks.Count > 0;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Extracting keyframes from {FilePath} using matroska metadata failed", filePath);
|
||||
}
|
||||
|
||||
keyframeData = null;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<GenerateDocumentationFile>true</GenerateDocumentationFile>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="../../MediaBrowser.Common/MediaBrowser.Common.csproj" />
|
||||
<ProjectReference Include="../../MediaBrowser.Model/MediaBrowser.Model.csproj" />
|
||||
<ProjectReference Include="../../MediaBrowser.Controller/MediaBrowser.Controller.csproj" />
|
||||
<ProjectReference Include="../Jellyfin.MediaEncoding.Keyframes/Jellyfin.MediaEncoding.Keyframes.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
|
||||
<ItemGroup>
|
||||
<AssemblyAttribute Include="System.Runtime.CompilerServices.InternalsVisibleTo">
|
||||
<_Parameter1>Jellyfin.MediaEncoding.Hls.Tests</_Parameter1>
|
||||
</AssemblyAttribute>
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -0,0 +1,72 @@
|
||||
using System;
|
||||
|
||||
namespace Jellyfin.MediaEncoding.Hls.Playlist;
|
||||
|
||||
/// <summary>
|
||||
/// Request class for the <see cref="IDynamicHlsPlaylistGenerator.CreateMainPlaylist(CreateMainPlaylistRequest)"/> method.
|
||||
/// </summary>
|
||||
public class CreateMainPlaylistRequest
|
||||
{
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="CreateMainPlaylistRequest"/> class.
|
||||
/// </summary>
|
||||
/// <param name="mediaSourceId">The media source id.</param>
|
||||
/// <param name="filePath">The absolute file path to the file.</param>
|
||||
/// <param name="desiredSegmentLengthMs">The desired segment length in milliseconds.</param>
|
||||
/// <param name="totalRuntimeTicks">The total duration of the file in ticks.</param>
|
||||
/// <param name="segmentContainer">The desired segment container eg. "ts".</param>
|
||||
/// <param name="endpointPrefix">The URI prefix for the relative URL in the playlist.</param>
|
||||
/// <param name="queryString">The desired query string to append (must start with ?).</param>
|
||||
/// <param name="isRemuxingVideo">Whether the video is being remuxed.</param>
|
||||
public CreateMainPlaylistRequest(Guid? mediaSourceId, string filePath, int desiredSegmentLengthMs, long totalRuntimeTicks, string segmentContainer, string endpointPrefix, string queryString, bool isRemuxingVideo)
|
||||
{
|
||||
MediaSourceId = mediaSourceId;
|
||||
FilePath = filePath;
|
||||
DesiredSegmentLengthMs = desiredSegmentLengthMs;
|
||||
TotalRuntimeTicks = totalRuntimeTicks;
|
||||
SegmentContainer = segmentContainer;
|
||||
EndpointPrefix = endpointPrefix;
|
||||
QueryString = queryString;
|
||||
IsRemuxingVideo = isRemuxingVideo;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the media source id.
|
||||
/// </summary>
|
||||
public Guid? MediaSourceId { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the file path.
|
||||
/// </summary>
|
||||
public string FilePath { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the desired segment length in milliseconds.
|
||||
/// </summary>
|
||||
public int DesiredSegmentLengthMs { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the total runtime in ticks.
|
||||
/// </summary>
|
||||
public long TotalRuntimeTicks { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the segment container.
|
||||
/// </summary>
|
||||
public string SegmentContainer { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the endpoint prefix for the URL.
|
||||
/// </summary>
|
||||
public string EndpointPrefix { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the query string.
|
||||
/// </summary>
|
||||
public string QueryString { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets a value indicating whether the video is being remuxed.
|
||||
/// </summary>
|
||||
public bool IsRemuxingVideo { get; }
|
||||
}
|
||||
@@ -0,0 +1,210 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Globalization;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using Jellyfin.MediaEncoding.Hls.Extractors;
|
||||
using Jellyfin.MediaEncoding.Keyframes;
|
||||
using MediaBrowser.Common.Configuration;
|
||||
using MediaBrowser.Controller.Configuration;
|
||||
using MediaBrowser.Controller.MediaEncoding;
|
||||
|
||||
namespace Jellyfin.MediaEncoding.Hls.Playlist;
|
||||
|
||||
/// <inheritdoc />
|
||||
public class DynamicHlsPlaylistGenerator : IDynamicHlsPlaylistGenerator
|
||||
{
|
||||
private readonly IServerConfigurationManager _serverConfigurationManager;
|
||||
private readonly IKeyframeExtractor[] _extractors;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="DynamicHlsPlaylistGenerator"/> class.
|
||||
/// </summary>
|
||||
/// <param name="serverConfigurationManager">An instance of the see <see cref="IServerConfigurationManager"/> interface.</param>
|
||||
/// <param name="extractors">An instance of <see cref="IEnumerable{IKeyframeExtractor}"/>.</param>
|
||||
public DynamicHlsPlaylistGenerator(IServerConfigurationManager serverConfigurationManager, IEnumerable<IKeyframeExtractor> extractors)
|
||||
{
|
||||
_serverConfigurationManager = serverConfigurationManager;
|
||||
_extractors = extractors.Where(e => e.IsMetadataBased).ToArray();
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public string CreateMainPlaylist(CreateMainPlaylistRequest request)
|
||||
{
|
||||
IReadOnlyList<double> segments;
|
||||
// For video transcodes it is sufficient with equal length segments as ffmpeg will create new keyframes
|
||||
if (request.IsRemuxingVideo
|
||||
&& request.MediaSourceId is not null
|
||||
&& TryExtractKeyframes(request.MediaSourceId.Value, request.FilePath, out var keyframeData))
|
||||
{
|
||||
segments = ComputeSegments(keyframeData, request.DesiredSegmentLengthMs);
|
||||
}
|
||||
else
|
||||
{
|
||||
segments = ComputeEqualLengthSegments(request.DesiredSegmentLengthMs, request.TotalRuntimeTicks);
|
||||
}
|
||||
|
||||
var segmentExtension = EncodingHelper.GetSegmentFileExtension(request.SegmentContainer);
|
||||
|
||||
// http://ffmpeg.org/ffmpeg-all.html#toc-hls-2
|
||||
var isHlsInFmp4 = string.Equals(segmentExtension, ".mp4", StringComparison.OrdinalIgnoreCase);
|
||||
var hlsVersion = isHlsInFmp4 ? "7" : "3";
|
||||
|
||||
var builder = new StringBuilder(128);
|
||||
|
||||
builder.AppendLine("#EXTM3U")
|
||||
.AppendLine("#EXT-X-PLAYLIST-TYPE:VOD")
|
||||
.Append("#EXT-X-VERSION:")
|
||||
.Append(hlsVersion)
|
||||
.AppendLine()
|
||||
.Append("#EXT-X-TARGETDURATION:")
|
||||
.Append(Math.Ceiling(segments.Count > 0 ? segments.Max() : request.DesiredSegmentLengthMs))
|
||||
.AppendLine()
|
||||
.AppendLine("#EXT-X-MEDIA-SEQUENCE:0");
|
||||
|
||||
var index = 0;
|
||||
|
||||
if (isHlsInFmp4)
|
||||
{
|
||||
// Init file that only includes fMP4 headers
|
||||
builder.Append("#EXT-X-MAP:URI=\"")
|
||||
.Append(request.EndpointPrefix)
|
||||
.Append("-1")
|
||||
.Append(segmentExtension)
|
||||
.Append(request.QueryString)
|
||||
.Append("&runtimeTicks=0")
|
||||
.Append("&actualSegmentLengthTicks=0")
|
||||
.Append('"')
|
||||
.AppendLine();
|
||||
}
|
||||
|
||||
long currentRuntimeInSeconds = 0;
|
||||
foreach (var length in segments)
|
||||
{
|
||||
// Manually convert to ticks to avoid precision loss when converting double
|
||||
var lengthTicks = Convert.ToInt64(length * TimeSpan.TicksPerSecond);
|
||||
builder.Append("#EXTINF:")
|
||||
.Append(length.ToString("0.000000", CultureInfo.InvariantCulture))
|
||||
.AppendLine(", nodesc")
|
||||
.Append(request.EndpointPrefix)
|
||||
.Append(index++)
|
||||
.Append(segmentExtension)
|
||||
.Append(request.QueryString)
|
||||
.Append("&runtimeTicks=")
|
||||
.Append(currentRuntimeInSeconds)
|
||||
.Append("&actualSegmentLengthTicks=")
|
||||
.Append(lengthTicks)
|
||||
.AppendLine();
|
||||
|
||||
currentRuntimeInSeconds += lengthTicks;
|
||||
}
|
||||
|
||||
builder.AppendLine("#EXT-X-ENDLIST");
|
||||
|
||||
return builder.ToString();
|
||||
}
|
||||
|
||||
private bool TryExtractKeyframes(Guid itemId, string filePath, [NotNullWhen(true)] out KeyframeData? keyframeData)
|
||||
{
|
||||
keyframeData = null;
|
||||
if (!IsExtractionAllowedForFile(filePath, _serverConfigurationManager.GetEncodingOptions().AllowOnDemandMetadataBasedKeyframeExtractionForExtensions))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var len = _extractors.Length;
|
||||
for (var i = 0; i < len; i++)
|
||||
{
|
||||
var extractor = _extractors[i];
|
||||
if (!extractor.TryExtractKeyframes(itemId, filePath, out var result))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
keyframeData = result;
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
internal static bool IsExtractionAllowedForFile(ReadOnlySpan<char> filePath, IReadOnlyList<string> allowedExtensions)
|
||||
{
|
||||
var extension = Path.GetExtension(filePath);
|
||||
if (extension.IsEmpty)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
// Remove the leading dot
|
||||
var extensionWithoutDot = extension[1..];
|
||||
for (var i = 0; i < allowedExtensions.Count; i++)
|
||||
{
|
||||
var allowedExtension = allowedExtensions[i].AsSpan().TrimStart('.');
|
||||
if (extensionWithoutDot.Equals(allowedExtension, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
internal static IReadOnlyList<double> ComputeSegments(KeyframeData keyframeData, int desiredSegmentLengthMs)
|
||||
{
|
||||
if (keyframeData.KeyframeTicks.Count > 0 && keyframeData.TotalDuration < keyframeData.KeyframeTicks[^1])
|
||||
{
|
||||
throw new ArgumentException("Invalid duration in keyframe data", nameof(keyframeData));
|
||||
}
|
||||
|
||||
long lastKeyframe = 0;
|
||||
var result = new List<double>();
|
||||
// Scale the segment length to ticks to match the keyframes
|
||||
var desiredSegmentLengthTicks = TimeSpan.FromMilliseconds(desiredSegmentLengthMs).Ticks;
|
||||
var desiredCutTime = desiredSegmentLengthTicks;
|
||||
for (var j = 0; j < keyframeData.KeyframeTicks.Count; j++)
|
||||
{
|
||||
var keyframe = keyframeData.KeyframeTicks[j];
|
||||
if (keyframe >= desiredCutTime)
|
||||
{
|
||||
var currentSegmentLength = keyframe - lastKeyframe;
|
||||
result.Add(TimeSpan.FromTicks(currentSegmentLength).TotalSeconds);
|
||||
lastKeyframe = keyframe;
|
||||
desiredCutTime += desiredSegmentLengthTicks;
|
||||
}
|
||||
}
|
||||
|
||||
result.Add(TimeSpan.FromTicks(keyframeData.TotalDuration - lastKeyframe).TotalSeconds);
|
||||
return result;
|
||||
}
|
||||
|
||||
internal static double[] ComputeEqualLengthSegments(int desiredSegmentLengthMs, long totalRuntimeTicks)
|
||||
{
|
||||
if (desiredSegmentLengthMs == 0 || totalRuntimeTicks == 0)
|
||||
{
|
||||
throw new InvalidOperationException($"Invalid segment length ({desiredSegmentLengthMs}) or runtime ticks ({totalRuntimeTicks})");
|
||||
}
|
||||
|
||||
var desiredSegmentLength = TimeSpan.FromMilliseconds(desiredSegmentLengthMs);
|
||||
|
||||
var segmentLengthTicks = desiredSegmentLength.Ticks;
|
||||
var wholeSegments = totalRuntimeTicks / segmentLengthTicks;
|
||||
var remainingTicks = totalRuntimeTicks % segmentLengthTicks;
|
||||
|
||||
var segmentsLen = wholeSegments + (remainingTicks == 0 ? 0 : 1);
|
||||
var segments = new double[segmentsLen];
|
||||
for (int i = 0; i < wholeSegments; i++)
|
||||
{
|
||||
segments[i] = desiredSegmentLength.TotalSeconds;
|
||||
}
|
||||
|
||||
if (remainingTicks != 0)
|
||||
{
|
||||
segments[^1] = TimeSpan.FromTicks(remainingTicks).TotalSeconds;
|
||||
}
|
||||
|
||||
return segments;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
namespace Jellyfin.MediaEncoding.Hls.Playlist;
|
||||
|
||||
/// <summary>
|
||||
/// Generator for dynamic HLS playlists where the segment lengths aren't known in advance.
|
||||
/// </summary>
|
||||
public interface IDynamicHlsPlaylistGenerator
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates the main playlist containing the main video or audio stream.
|
||||
/// </summary>
|
||||
/// <param name="request">An instance of the <see cref="CreateMainPlaylistRequest"/> class.</param>
|
||||
/// <returns>The playlist as a formatted string.</returns>
|
||||
string CreateMainPlaylist(CreateMainPlaylistRequest request);
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Jellyfin.Data.Enums;
|
||||
using Jellyfin.MediaEncoding.Hls.Extractors;
|
||||
using MediaBrowser.Controller.Dto;
|
||||
using MediaBrowser.Controller.Entities;
|
||||
using MediaBrowser.Controller.Library;
|
||||
using MediaBrowser.Model.Globalization;
|
||||
using MediaBrowser.Model.Tasks;
|
||||
|
||||
namespace Jellyfin.MediaEncoding.Hls.ScheduledTasks;
|
||||
|
||||
/// <inheritdoc />
|
||||
public class KeyframeExtractionScheduledTask : IScheduledTask
|
||||
{
|
||||
private const int Pagesize = 1000;
|
||||
|
||||
private readonly ILocalizationManager _localizationManager;
|
||||
private readonly ILibraryManager _libraryManager;
|
||||
private readonly IKeyframeExtractor[] _keyframeExtractors;
|
||||
private static readonly BaseItemKind[] _itemTypes = [BaseItemKind.Episode, BaseItemKind.Movie];
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="KeyframeExtractionScheduledTask"/> class.
|
||||
/// </summary>
|
||||
/// <param name="localizationManager">An instance of the <see cref="ILocalizationManager"/> interface.</param>
|
||||
/// <param name="libraryManager">An instance of the <see cref="ILibraryManager"/> interface.</param>
|
||||
/// <param name="keyframeExtractors">The keyframe extractors.</param>
|
||||
public KeyframeExtractionScheduledTask(ILocalizationManager localizationManager, ILibraryManager libraryManager, IEnumerable<IKeyframeExtractor> keyframeExtractors)
|
||||
{
|
||||
_localizationManager = localizationManager;
|
||||
_libraryManager = libraryManager;
|
||||
_keyframeExtractors = keyframeExtractors.OrderByDescending(e => e.IsMetadataBased).ToArray();
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public string Name => _localizationManager.GetLocalizedString("TaskKeyframeExtractor");
|
||||
|
||||
/// <inheritdoc />
|
||||
public string Key => "KeyframeExtraction";
|
||||
|
||||
/// <inheritdoc />
|
||||
public string Description => _localizationManager.GetLocalizedString("TaskKeyframeExtractorDescription");
|
||||
|
||||
/// <inheritdoc />
|
||||
public string Category => _localizationManager.GetLocalizedString("TasksLibraryCategory");
|
||||
|
||||
/// <inheritdoc />
|
||||
public Task ExecuteAsync(IProgress<double> progress, CancellationToken cancellationToken)
|
||||
{
|
||||
var query = new InternalItemsQuery
|
||||
{
|
||||
MediaTypes = [MediaType.Video],
|
||||
IsVirtualItem = false,
|
||||
IncludeItemTypes = _itemTypes,
|
||||
DtoOptions = new DtoOptions(true),
|
||||
SourceTypes = [SourceType.Library],
|
||||
Recursive = true,
|
||||
Limit = Pagesize
|
||||
};
|
||||
|
||||
var numberOfVideos = _libraryManager.GetCount(query);
|
||||
|
||||
var startIndex = 0;
|
||||
var numComplete = 0;
|
||||
|
||||
while (startIndex < numberOfVideos)
|
||||
{
|
||||
query.StartIndex = startIndex;
|
||||
|
||||
var videos = _libraryManager.GetItemList(query);
|
||||
foreach (var video in videos)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
|
||||
// Only local files supported
|
||||
var path = video.Path;
|
||||
if (File.Exists(path))
|
||||
{
|
||||
foreach (var extractor in _keyframeExtractors)
|
||||
{
|
||||
// The cache decorator will make sure to save the keyframes
|
||||
if (extractor.TryExtractKeyframes(video.Id, path, out _))
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Update progress
|
||||
numComplete++;
|
||||
double percent = (double)numComplete / numberOfVideos;
|
||||
progress.Report(100 * percent);
|
||||
}
|
||||
|
||||
startIndex += Pagesize;
|
||||
}
|
||||
|
||||
progress.Report(100);
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public IEnumerable<TaskTriggerInfo> GetDefaultTriggers() => [];
|
||||
}
|
||||
+4
@@ -0,0 +1,4 @@
|
||||
// <autogenerated />
|
||||
using System;
|
||||
using System.Reflection;
|
||||
[assembly: global::System.Runtime.Versioning.TargetFrameworkAttribute(".NETCoreApp,Version=v10.0", FrameworkDisplayName = ".NET 10.0")]
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
//------------------------------------------------------------------------------
|
||||
// <auto-generated>
|
||||
// This code was generated by a tool.
|
||||
//
|
||||
// Changes to this file may cause incorrect behavior and will be lost if
|
||||
// the code is regenerated.
|
||||
// </auto-generated>
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
using System;
|
||||
using System.Reflection;
|
||||
|
||||
[assembly: System.Runtime.CompilerServices.InternalsVisibleTo("Jellyfin.MediaEncoding.Hls.Tests")]
|
||||
[assembly: System.Reflection.AssemblyCompanyAttribute("Jellyfin.MediaEncoding.Hls")]
|
||||
[assembly: System.Reflection.AssemblyConfigurationAttribute("Debug")]
|
||||
[assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.0.0")]
|
||||
[assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0")]
|
||||
[assembly: System.Reflection.AssemblyProductAttribute("Jellyfin.MediaEncoding.Hls")]
|
||||
[assembly: System.Reflection.AssemblyTitleAttribute("Jellyfin.MediaEncoding.Hls")]
|
||||
[assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")]
|
||||
|
||||
// Generated by the MSBuild WriteCodeFragment class.
|
||||
|
||||
+1
@@ -0,0 +1 @@
|
||||
edf4babb1b81b04b3b6384e6551f8507281aea7811516788c3cf3ddcb1eacfa1
|
||||
+27
@@ -0,0 +1,27 @@
|
||||
is_global = true
|
||||
build_property.TargetFramework = net10.0
|
||||
build_property.TargetFramework = net10.0
|
||||
build_property.TargetFrameworkIdentifier = .NETCoreApp
|
||||
build_property.TargetFrameworkIdentifier = .NETCoreApp
|
||||
build_property.TargetFrameworkVersion = v10.0
|
||||
build_property.TargetFrameworkVersion = v10.0
|
||||
build_property.TargetPlatformMinVersion =
|
||||
build_property.TargetPlatformMinVersion =
|
||||
build_property.UsingMicrosoftNETSdkWeb =
|
||||
build_property.UsingMicrosoftNETSdkWeb =
|
||||
build_property.ProjectTypeGuids =
|
||||
build_property.ProjectTypeGuids =
|
||||
build_property.InvariantGlobalization =
|
||||
build_property.InvariantGlobalization =
|
||||
build_property.PlatformNeutralAssembly =
|
||||
build_property.PlatformNeutralAssembly =
|
||||
build_property.EnforceExtendedAnalyzerRules =
|
||||
build_property.EnforceExtendedAnalyzerRules =
|
||||
build_property._SupportedPlatformList = Linux,macOS,Windows
|
||||
build_property._SupportedPlatformList = Linux,macOS,Windows
|
||||
build_property.RootNamespace = Jellyfin.MediaEncoding.Hls
|
||||
build_property.ProjectDir = /srv/common_drive/Projects/pgsql-jellyfin/src/Jellyfin.MediaEncoding.Hls/
|
||||
build_property.EnableComHosting =
|
||||
build_property.EnableGeneratedComInterfaceComImportInterop =
|
||||
build_property.EffectiveAnalysisLevelStyle = 10.0
|
||||
build_property.EnableCodeStyleSeverity =
|
||||
BIN
Binary file not shown.
BIN
Binary file not shown.
+4755
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,26 @@
|
||||
<?xml version="1.0" encoding="utf-8" standalone="no"?>
|
||||
<Project ToolsVersion="14.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
|
||||
<PropertyGroup Condition=" '$(ExcludeRestorePackageImports)' != 'true' ">
|
||||
<RestoreSuccess Condition=" '$(RestoreSuccess)' == '' ">True</RestoreSuccess>
|
||||
<RestoreTool Condition=" '$(RestoreTool)' == '' ">NuGet</RestoreTool>
|
||||
<ProjectAssetsFile Condition=" '$(ProjectAssetsFile)' == '' ">$(MSBuildThisFileDirectory)project.assets.json</ProjectAssetsFile>
|
||||
<NuGetPackageRoot Condition=" '$(NuGetPackageRoot)' == '' ">/home/wjones/.nuget/packages/</NuGetPackageRoot>
|
||||
<NuGetPackageFolders Condition=" '$(NuGetPackageFolders)' == '' ">/home/wjones/.nuget/packages/</NuGetPackageFolders>
|
||||
<NuGetProjectStyle Condition=" '$(NuGetProjectStyle)' == '' ">PackageReference</NuGetProjectStyle>
|
||||
<NuGetToolVersion Condition=" '$(NuGetToolVersion)' == '' ">7.0.0</NuGetToolVersion>
|
||||
</PropertyGroup>
|
||||
<ItemGroup Condition=" '$(ExcludeRestorePackageImports)' != 'true' ">
|
||||
<SourceRoot Include="/home/wjones/.nuget/packages/" />
|
||||
</ItemGroup>
|
||||
<ImportGroup Condition=" '$(ExcludeRestorePackageImports)' != 'true' ">
|
||||
<Import Project="$(NuGetPackageRoot)microsoft.entityframeworkcore/10.0.3/buildTransitive/net10.0/Microsoft.EntityFrameworkCore.props" Condition="Exists('$(NuGetPackageRoot)microsoft.entityframeworkcore/10.0.3/buildTransitive/net10.0/Microsoft.EntityFrameworkCore.props')" />
|
||||
<Import Project="$(NuGetPackageRoot)microsoft.codeanalysis.bannedapianalyzers/4.14.0/buildTransitive/Microsoft.CodeAnalysis.BannedApiAnalyzers.props" Condition="Exists('$(NuGetPackageRoot)microsoft.codeanalysis.bannedapianalyzers/4.14.0/buildTransitive/Microsoft.CodeAnalysis.BannedApiAnalyzers.props')" />
|
||||
</ImportGroup>
|
||||
<PropertyGroup Condition=" '$(ExcludeRestorePackageImports)' != 'true' ">
|
||||
<PkgStyleCop_Analyzers_Unstable Condition=" '$(PkgStyleCop_Analyzers_Unstable)' == '' ">/home/wjones/.nuget/packages/stylecop.analyzers.unstable/1.2.0.556</PkgStyleCop_Analyzers_Unstable>
|
||||
<PkgSmartAnalyzers_MultithreadingAnalyzer Condition=" '$(PkgSmartAnalyzers_MultithreadingAnalyzer)' == '' ">/home/wjones/.nuget/packages/smartanalyzers.multithreadinganalyzer/1.1.31</PkgSmartAnalyzers_MultithreadingAnalyzer>
|
||||
<PkgSerilogAnalyzer Condition=" '$(PkgSerilogAnalyzer)' == '' ">/home/wjones/.nuget/packages/seriloganalyzer/0.15.0</PkgSerilogAnalyzer>
|
||||
<PkgMicrosoft_CodeAnalysis_BannedApiAnalyzers Condition=" '$(PkgMicrosoft_CodeAnalysis_BannedApiAnalyzers)' == '' ">/home/wjones/.nuget/packages/microsoft.codeanalysis.bannedapianalyzers/4.14.0</PkgMicrosoft_CodeAnalysis_BannedApiAnalyzers>
|
||||
<PkgIDisposableAnalyzers Condition=" '$(PkgIDisposableAnalyzers)' == '' ">/home/wjones/.nuget/packages/idisposableanalyzers/4.0.8</PkgIDisposableAnalyzers>
|
||||
</PropertyGroup>
|
||||
</Project>
|
||||
@@ -0,0 +1,9 @@
|
||||
<?xml version="1.0" encoding="utf-8" standalone="no"?>
|
||||
<Project ToolsVersion="14.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
|
||||
<ImportGroup Condition=" '$(ExcludeRestorePackageImports)' != 'true' ">
|
||||
<Import Project="$(NuGetPackageRoot)microsoft.extensions.options/10.0.3/buildTransitive/net8.0/Microsoft.Extensions.Options.targets" Condition="Exists('$(NuGetPackageRoot)microsoft.extensions.options/10.0.3/buildTransitive/net8.0/Microsoft.Extensions.Options.targets')" />
|
||||
<Import Project="$(NuGetPackageRoot)microsoft.extensions.logging.abstractions/10.0.3/buildTransitive/net8.0/Microsoft.Extensions.Logging.Abstractions.targets" Condition="Exists('$(NuGetPackageRoot)microsoft.extensions.logging.abstractions/10.0.3/buildTransitive/net8.0/Microsoft.Extensions.Logging.Abstractions.targets')" />
|
||||
<Import Project="$(NuGetPackageRoot)microsoft.extensions.configuration.binder/10.0.3/buildTransitive/netstandard2.0/Microsoft.Extensions.Configuration.Binder.targets" Condition="Exists('$(NuGetPackageRoot)microsoft.extensions.configuration.binder/10.0.3/buildTransitive/netstandard2.0/Microsoft.Extensions.Configuration.Binder.targets')" />
|
||||
<Import Project="$(NuGetPackageRoot)microsoft.codeanalysis.bannedapianalyzers/4.14.0/buildTransitive/Microsoft.CodeAnalysis.BannedApiAnalyzers.targets" Condition="Exists('$(NuGetPackageRoot)microsoft.codeanalysis.bannedapianalyzers/4.14.0/buildTransitive/Microsoft.CodeAnalysis.BannedApiAnalyzers.targets')" />
|
||||
</ImportGroup>
|
||||
</Project>
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,38 @@
|
||||
{
|
||||
"version": 2,
|
||||
"dgSpecHash": "Kr52o9OudyQ=",
|
||||
"success": true,
|
||||
"projectFilePath": "/srv/common_drive/Projects/pgsql-jellyfin/src/Jellyfin.MediaEncoding.Hls/Jellyfin.MediaEncoding.Hls.csproj",
|
||||
"expectedPackageFiles": [
|
||||
"/home/wjones/.nuget/packages/bitfaster.caching/2.5.4/bitfaster.caching.2.5.4.nupkg.sha512",
|
||||
"/home/wjones/.nuget/packages/diacritics/4.1.4/diacritics.4.1.4.nupkg.sha512",
|
||||
"/home/wjones/.nuget/packages/icu4n/60.1.0-alpha.356/icu4n.60.1.0-alpha.356.nupkg.sha512",
|
||||
"/home/wjones/.nuget/packages/icu4n.transliterator/60.1.0-alpha.356/icu4n.transliterator.60.1.0-alpha.356.nupkg.sha512",
|
||||
"/home/wjones/.nuget/packages/idisposableanalyzers/4.0.8/idisposableanalyzers.4.0.8.nupkg.sha512",
|
||||
"/home/wjones/.nuget/packages/j2n/2.0.0/j2n.2.0.0.nupkg.sha512",
|
||||
"/home/wjones/.nuget/packages/microsoft.codeanalysis.bannedapianalyzers/4.14.0/microsoft.codeanalysis.bannedapianalyzers.4.14.0.nupkg.sha512",
|
||||
"/home/wjones/.nuget/packages/microsoft.entityframeworkcore/10.0.3/microsoft.entityframeworkcore.10.0.3.nupkg.sha512",
|
||||
"/home/wjones/.nuget/packages/microsoft.entityframeworkcore.abstractions/10.0.3/microsoft.entityframeworkcore.abstractions.10.0.3.nupkg.sha512",
|
||||
"/home/wjones/.nuget/packages/microsoft.entityframeworkcore.analyzers/10.0.3/microsoft.entityframeworkcore.analyzers.10.0.3.nupkg.sha512",
|
||||
"/home/wjones/.nuget/packages/microsoft.entityframeworkcore.relational/10.0.3/microsoft.entityframeworkcore.relational.10.0.3.nupkg.sha512",
|
||||
"/home/wjones/.nuget/packages/microsoft.extensions.caching.abstractions/10.0.3/microsoft.extensions.caching.abstractions.10.0.3.nupkg.sha512",
|
||||
"/home/wjones/.nuget/packages/microsoft.extensions.caching.memory/10.0.3/microsoft.extensions.caching.memory.10.0.3.nupkg.sha512",
|
||||
"/home/wjones/.nuget/packages/microsoft.extensions.configuration/10.0.3/microsoft.extensions.configuration.10.0.3.nupkg.sha512",
|
||||
"/home/wjones/.nuget/packages/microsoft.extensions.configuration.abstractions/10.0.3/microsoft.extensions.configuration.abstractions.10.0.3.nupkg.sha512",
|
||||
"/home/wjones/.nuget/packages/microsoft.extensions.configuration.binder/10.0.3/microsoft.extensions.configuration.binder.10.0.3.nupkg.sha512",
|
||||
"/home/wjones/.nuget/packages/microsoft.extensions.dependencyinjection/10.0.3/microsoft.extensions.dependencyinjection.10.0.3.nupkg.sha512",
|
||||
"/home/wjones/.nuget/packages/microsoft.extensions.dependencyinjection.abstractions/10.0.3/microsoft.extensions.dependencyinjection.abstractions.10.0.3.nupkg.sha512",
|
||||
"/home/wjones/.nuget/packages/microsoft.extensions.logging/10.0.3/microsoft.extensions.logging.10.0.3.nupkg.sha512",
|
||||
"/home/wjones/.nuget/packages/microsoft.extensions.logging.abstractions/10.0.3/microsoft.extensions.logging.abstractions.10.0.3.nupkg.sha512",
|
||||
"/home/wjones/.nuget/packages/microsoft.extensions.options/10.0.3/microsoft.extensions.options.10.0.3.nupkg.sha512",
|
||||
"/home/wjones/.nuget/packages/microsoft.extensions.primitives/10.0.3/microsoft.extensions.primitives.10.0.3.nupkg.sha512",
|
||||
"/home/wjones/.nuget/packages/nebml/1.1.0.5/nebml.1.1.0.5.nupkg.sha512",
|
||||
"/home/wjones/.nuget/packages/polly/8.6.5/polly.8.6.5.nupkg.sha512",
|
||||
"/home/wjones/.nuget/packages/polly.core/8.6.5/polly.core.8.6.5.nupkg.sha512",
|
||||
"/home/wjones/.nuget/packages/seriloganalyzer/0.15.0/seriloganalyzer.0.15.0.nupkg.sha512",
|
||||
"/home/wjones/.nuget/packages/smartanalyzers.multithreadinganalyzer/1.1.31/smartanalyzers.multithreadinganalyzer.1.1.31.nupkg.sha512",
|
||||
"/home/wjones/.nuget/packages/stylecop.analyzers/1.2.0-beta.556/stylecop.analyzers.1.2.0-beta.556.nupkg.sha512",
|
||||
"/home/wjones/.nuget/packages/stylecop.analyzers.unstable/1.2.0.556/stylecop.analyzers.unstable.1.2.0.556.nupkg.sha512"
|
||||
],
|
||||
"logs": []
|
||||
}
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1 @@
|
||||
17714532042500000
|
||||
@@ -0,0 +1 @@
|
||||
17715044197100000
|
||||
Reference in New Issue
Block a user