1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
|
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.Json;
using Jellyfin.Extensions.Json;
using Jellyfin.MediaEncoding.Keyframes;
using MediaBrowser.Common.Configuration;
using MediaBrowser.Common.Extensions;
using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.MediaEncoding;
using Microsoft.Extensions.Logging;
namespace Jellyfin.MediaEncoding.Hls.Playlist
{
/// <inheritdoc />
public class DynamicHlsPlaylistGenerator : IDynamicHlsPlaylistGenerator
{
private const string DefaultContainerExtension = ".ts";
private readonly JsonSerializerOptions _jsonOptions = JsonDefaults.Options;
private readonly IServerConfigurationManager _serverConfigurationManager;
private readonly IMediaEncoder _mediaEncoder;
private readonly IApplicationPaths _applicationPaths;
private readonly KeyframeExtractor _keyframeExtractor;
/// <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="mediaEncoder">An instance of the see <see cref="IMediaEncoder"/> interface.</param>
/// <param name="applicationPaths">An instance of the <see cref="IApplicationPaths"/> interface.</param>
/// <param name="loggerFactory">An instance of the see <see cref="ILoggerFactory"/> interface.</param>
public DynamicHlsPlaylistGenerator(IServerConfigurationManager serverConfigurationManager, IMediaEncoder mediaEncoder, IApplicationPaths applicationPaths, ILoggerFactory loggerFactory)
{
_serverConfigurationManager = serverConfigurationManager;
_mediaEncoder = mediaEncoder;
_applicationPaths = applicationPaths;
_keyframeExtractor = new KeyframeExtractor(loggerFactory.CreateLogger<KeyframeExtractor>());
}
private string KeyframeCachePath => Path.Combine(_applicationPaths.DataPath, "keyframes");
/// <inheritdoc />
public string CreateMainPlaylist(CreateMainPlaylistRequest request)
{
IReadOnlyList<double> segments;
if (IsExtractionAllowed(request.FilePath))
{
segments = ComputeSegments(request.FilePath, request.DesiredSegmentLengthMs);
}
else
{
segments = ComputeEqualLengthSegments(request.DesiredSegmentLengthMs, request.TotalRuntimeTicks);
}
var segmentExtension = 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)
{
builder.Append("#EXT-X-MAP:URI=\"")
.Append(request.EndpointPrefix)
.Append("-1")
.Append(segmentExtension)
.Append(request.QueryString)
.Append('"')
.AppendLine();
}
double currentRuntimeInSeconds = 0;
foreach (var length in segments)
{
builder.Append("#EXTINF:")
.Append(length.ToString("0.0000", CultureInfo.InvariantCulture))
.AppendLine(", nodesc")
.Append(request.EndpointPrefix)
.Append(index++)
.Append(segmentExtension)
.Append(request.QueryString)
.Append("&runtimeTicks=")
.Append(TimeSpan.FromSeconds(currentRuntimeInSeconds).Ticks)
.Append("&actualSegmentLengthTicks=")
.Append(TimeSpan.FromSeconds(length).Ticks)
.AppendLine();
currentRuntimeInSeconds += length;
}
builder.AppendLine("#EXT-X-ENDLIST");
return builder.ToString();
}
private IReadOnlyList<double> ComputeSegments(string filePath, int desiredSegmentLengthMs)
{
KeyframeData keyframeData;
var cachePath = GetCachePath(filePath);
if (TryReadFromCache(cachePath, out var cachedResult))
{
keyframeData = cachedResult;
}
else
{
keyframeData = _keyframeExtractor.GetKeyframeData(filePath, _mediaEncoder.ProbePath, string.Empty);
CacheResult(cachePath, 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;
}
private void CacheResult(string cachePath, KeyframeData keyframeData)
{
var json = JsonSerializer.Serialize(keyframeData, _jsonOptions);
Directory.CreateDirectory(Path.GetDirectoryName(cachePath) ?? throw new ArgumentException($"Provided path ({cachePath}) is not valid.", nameof(cachePath)));
File.WriteAllText(cachePath, json);
}
private string GetCachePath(string filePath)
{
var lastWriteTimeUtc = File.GetLastWriteTimeUtc(filePath);
ReadOnlySpan<char> filename = (filePath + "_" + lastWriteTimeUtc.Ticks.ToString(CultureInfo.InvariantCulture)).GetMD5() + ".json";
var prefix = filename.Slice(0, 1);
return Path.Join(KeyframeCachePath, prefix, filename);
}
private bool TryReadFromCache(string cachePath, [NotNullWhen(true)] out KeyframeData? cachedResult)
{
if (File.Exists(cachePath))
{
var bytes = File.ReadAllBytes(cachePath);
cachedResult = JsonSerializer.Deserialize<KeyframeData>(bytes, _jsonOptions);
return cachedResult != null;
}
cachedResult = null;
return false;
}
private bool IsExtractionAllowed(ReadOnlySpan<char> filePath)
{
// Remove the leading dot
var extension = Path.GetExtension(filePath)[1..];
var allowedExtensions = _serverConfigurationManager.GetEncodingOptions().AllowAutomaticKeyframeExtractionForExtensions;
for (var i = 0; i < allowedExtensions.Length; i++)
{
var allowedExtension = allowedExtensions[i];
if (extension.Equals(allowedExtension, StringComparison.OrdinalIgnoreCase))
{
return true;
}
}
return false;
}
private static double[] ComputeEqualLengthSegments(long desiredSegmentLengthMs, long totalRuntimeTicks)
{
var segmentLengthTicks = TimeSpan.FromMilliseconds(desiredSegmentLengthMs).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] = desiredSegmentLengthMs;
}
if (remainingTicks != 0)
{
segments[^1] = TimeSpan.FromTicks(remainingTicks).TotalSeconds;
}
return segments;
}
// TODO copied from DynamicHlsController
private static string GetSegmentFileExtension(string segmentContainer)
{
if (!string.IsNullOrWhiteSpace(segmentContainer))
{
return "." + segmentContainer;
}
return DefaultContainerExtension;
}
}
}
|