| | | 1 | | #pragma warning disable CS1591 |
| | | 2 | | |
| | | 3 | | using System; |
| | | 4 | | using System.Collections.Generic; |
| | | 5 | | using System.Diagnostics; |
| | | 6 | | using System.Diagnostics.CodeAnalysis; |
| | | 7 | | using System.Globalization; |
| | | 8 | | using System.IO; |
| | | 9 | | using System.Linq; |
| | | 10 | | using System.Net.Http; |
| | | 11 | | using System.Text; |
| | | 12 | | using System.Threading; |
| | | 13 | | using System.Threading.Tasks; |
| | | 14 | | using AsyncKeyedLock; |
| | | 15 | | using MediaBrowser.Common; |
| | | 16 | | using MediaBrowser.Common.Configuration; |
| | | 17 | | using MediaBrowser.Common.Extensions; |
| | | 18 | | using MediaBrowser.Common.Net; |
| | | 19 | | using MediaBrowser.Controller.Configuration; |
| | | 20 | | using MediaBrowser.Controller.Entities; |
| | | 21 | | using MediaBrowser.Controller.IO; |
| | | 22 | | using MediaBrowser.Controller.Library; |
| | | 23 | | using MediaBrowser.Controller.MediaEncoding; |
| | | 24 | | using MediaBrowser.Model.Dto; |
| | | 25 | | using MediaBrowser.Model.Entities; |
| | | 26 | | using MediaBrowser.Model.IO; |
| | | 27 | | using MediaBrowser.Model.MediaInfo; |
| | | 28 | | using Microsoft.Extensions.Logging; |
| | | 29 | | using Nikse.SubtitleEdit.Core.Common; |
| | | 30 | | using Nikse.SubtitleEdit.Core.SubtitleFormats; |
| | | 31 | | using UtfUnknown; |
| | | 32 | | using SubtitleFormat = MediaBrowser.Model.MediaInfo.SubtitleFormat; |
| | | 33 | | |
| | | 34 | | namespace MediaBrowser.MediaEncoding.Subtitles |
| | | 35 | | { |
| | | 36 | | public sealed class SubtitleEncoder : ISubtitleEncoder, IDisposable |
| | | 37 | | { |
| | | 38 | | private readonly ILogger<SubtitleEncoder> _logger; |
| | | 39 | | private readonly IFileSystem _fileSystem; |
| | | 40 | | private readonly IMediaEncoder _mediaEncoder; |
| | | 41 | | private readonly IHttpClientFactory _httpClientFactory; |
| | | 42 | | private readonly IMediaSourceManager _mediaSourceManager; |
| | | 43 | | private readonly ISubtitleParser _subtitleParser; |
| | | 44 | | private readonly IPathManager _pathManager; |
| | | 45 | | private readonly IServerConfigurationManager _serverConfigurationManager; |
| | | 46 | | |
| | | 47 | | /// <summary> |
| | | 48 | | /// The _semaphoreLocks. |
| | | 49 | | /// </summary> |
| | 32 | 50 | | private readonly AsyncKeyedLocker<string> _semaphoreLocks = new(o => |
| | 32 | 51 | | { |
| | 32 | 52 | | o.PoolSize = 20; |
| | 32 | 53 | | o.PoolInitialFill = 1; |
| | 32 | 54 | | }); |
| | | 55 | | |
| | | 56 | | public SubtitleEncoder( |
| | | 57 | | ILogger<SubtitleEncoder> logger, |
| | | 58 | | IFileSystem fileSystem, |
| | | 59 | | IMediaEncoder mediaEncoder, |
| | | 60 | | IHttpClientFactory httpClientFactory, |
| | | 61 | | IMediaSourceManager mediaSourceManager, |
| | | 62 | | ISubtitleParser subtitleParser, |
| | | 63 | | IPathManager pathManager, |
| | | 64 | | IServerConfigurationManager serverConfigurationManager) |
| | | 65 | | { |
| | 32 | 66 | | _logger = logger; |
| | 32 | 67 | | _fileSystem = fileSystem; |
| | 32 | 68 | | _mediaEncoder = mediaEncoder; |
| | 32 | 69 | | _httpClientFactory = httpClientFactory; |
| | 32 | 70 | | _mediaSourceManager = mediaSourceManager; |
| | 32 | 71 | | _subtitleParser = subtitleParser; |
| | 32 | 72 | | _pathManager = pathManager; |
| | 32 | 73 | | _serverConfigurationManager = serverConfigurationManager; |
| | 32 | 74 | | } |
| | | 75 | | |
| | | 76 | | internal MemoryStream ConvertSubtitles( |
| | | 77 | | Stream stream, |
| | | 78 | | SubtitleInfo inputInfo, |
| | | 79 | | string outputFormat, |
| | | 80 | | long startTimeTicks, |
| | | 81 | | long endTimeTicks, |
| | | 82 | | bool preserveOriginalTimestamps) |
| | | 83 | | { |
| | 104 | 84 | | var subtitle = _subtitleParser.Parse(stream, inputInfo.Format); |
| | | 85 | | |
| | 104 | 86 | | FilterEvents(subtitle, startTimeTicks, endTimeTicks, preserveOriginalTimestamps); |
| | | 87 | | |
| | 104 | 88 | | var formatter = GetWriter(outputFormat); |
| | | 89 | | |
| | 104 | 90 | | var text = formatter.ToText(subtitle, "untitled"); |
| | 104 | 91 | | var bytes = Encoding.UTF8.GetBytes(text); |
| | | 92 | | |
| | 104 | 93 | | return new MemoryStream(bytes, 0, bytes.Length, false, true); |
| | | 94 | | } |
| | | 95 | | |
| | | 96 | | internal void FilterEvents(Subtitle track, long startPositionTicks, long endTimeTicks, bool preserveTimestamps) |
| | | 97 | | { |
| | | 98 | | // Drop subs that have fully elapsed before the requested start position |
| | 104 | 99 | | track.Paragraphs |
| | 104 | 100 | | .RemoveAll(i => (i.StartTime.TimeSpan.Ticks - startPositionTicks) < 0 && (i.EndTime.TimeSpan.Ticks - sta |
| | | 101 | | |
| | 104 | 102 | | if (endTimeTicks > 0) |
| | | 103 | | { |
| | 0 | 104 | | track.Paragraphs |
| | 0 | 105 | | .RemoveAll(i => i.StartTime.TimeSpan.Ticks > endTimeTicks); |
| | | 106 | | } |
| | | 107 | | |
| | 104 | 108 | | if (!preserveTimestamps) |
| | | 109 | | { |
| | 104208 | 110 | | foreach (var trackEvent in track.Paragraphs) |
| | | 111 | | { |
| | 52000 | 112 | | trackEvent.StartTime = new TimeCode(TimeSpan.FromTicks(Math.Max(0, trackEvent.StartTime.TimeSpan.Tic |
| | 52000 | 113 | | trackEvent.EndTime = new TimeCode(TimeSpan.FromTicks(Math.Max(0, trackEvent.EndTime.TimeSpan.Ticks - |
| | | 114 | | } |
| | | 115 | | } |
| | 104 | 116 | | } |
| | | 117 | | |
| | | 118 | | async Task<Stream> ISubtitleEncoder.GetSubtitles(BaseItem item, string mediaSourceId, int subtitleStreamIndex, s |
| | | 119 | | { |
| | 0 | 120 | | ArgumentNullException.ThrowIfNull(item); |
| | | 121 | | |
| | 0 | 122 | | if (string.IsNullOrWhiteSpace(mediaSourceId)) |
| | | 123 | | { |
| | 0 | 124 | | throw new ArgumentNullException(nameof(mediaSourceId)); |
| | | 125 | | } |
| | | 126 | | |
| | 0 | 127 | | var mediaSources = await _mediaSourceManager.GetPlaybackMediaSources(item, null, true, false, cancellationTo |
| | | 128 | | |
| | 0 | 129 | | var mediaSource = mediaSources |
| | 0 | 130 | | .First(i => string.Equals(i.Id, mediaSourceId, StringComparison.OrdinalIgnoreCase)); |
| | | 131 | | |
| | 0 | 132 | | var subtitleStream = mediaSource.MediaStreams |
| | 0 | 133 | | .First(i => i.Type == MediaStreamType.Subtitle && i.Index == subtitleStreamIndex); |
| | | 134 | | |
| | 0 | 135 | | var (stream, info) = await GetSubtitleStream(mediaSource, subtitleStream, cancellationToken) |
| | 0 | 136 | | .ConfigureAwait(false); |
| | | 137 | | |
| | | 138 | | // Return the original if the same format is being requested |
| | | 139 | | // Character encoding was already handled in GetSubtitleStream |
| | | 140 | | // ASS is a superset of SSA, skipping the conversion and preserving the styles |
| | 0 | 141 | | if (string.Equals(info.Format, outputFormat, StringComparison.OrdinalIgnoreCase) |
| | 0 | 142 | | || (string.Equals(info.Format, SubtitleFormat.SSA, StringComparison.OrdinalIgnoreCase) |
| | 0 | 143 | | && string.Equals(outputFormat, SubtitleFormat.ASS, StringComparison.OrdinalIgnoreCase))) |
| | | 144 | | { |
| | 0 | 145 | | return stream; |
| | | 146 | | } |
| | | 147 | | |
| | 0 | 148 | | using (stream) |
| | | 149 | | { |
| | 0 | 150 | | return ConvertSubtitles(stream, info, outputFormat, startTimeTicks, endTimeTicks, preserveOriginalTimest |
| | | 151 | | } |
| | 0 | 152 | | } |
| | | 153 | | |
| | | 154 | | private async Task<(Stream Stream, SubtitleInfo Info)> GetSubtitleStream( |
| | | 155 | | MediaSourceInfo mediaSource, |
| | | 156 | | MediaStream subtitleStream, |
| | | 157 | | CancellationToken cancellationToken) |
| | | 158 | | { |
| | 0 | 159 | | var fileInfo = await GetReadableFile(mediaSource, subtitleStream, cancellationToken).ConfigureAwait(false); |
| | | 160 | | |
| | 0 | 161 | | var stream = await GetSubtitleStream(fileInfo, cancellationToken).ConfigureAwait(false); |
| | | 162 | | |
| | 0 | 163 | | return (stream, fileInfo); |
| | 0 | 164 | | } |
| | | 165 | | |
| | | 166 | | internal async Task<Stream> GetSubtitleStream(SubtitleInfo fileInfo, CancellationToken cancellationToken) |
| | | 167 | | { |
| | 4 | 168 | | if (fileInfo.IsExternal && MediaStream.IsTextFormat(fileInfo.Format)) |
| | | 169 | | { |
| | 4 | 170 | | var result = await DetectCharset(fileInfo.Path, cancellationToken).ConfigureAwait(false); |
| | 4 | 171 | | var detected = result.Detected; |
| | | 172 | | |
| | 4 | 173 | | var stream = fileInfo.Protocol == MediaProtocol.Http |
| | 4 | 174 | | ? await _httpClientFactory.CreateClient(NamedClient.Default) |
| | 4 | 175 | | .GetStreamAsync(new Uri(fileInfo.Path), cancellationToken) |
| | 4 | 176 | | .ConfigureAwait(false) |
| | 4 | 177 | | : AsyncFile.OpenRead(fileInfo.Path); |
| | | 178 | | |
| | | 179 | | // Short-circuit when the file is already UTF-8/ASCII. |
| | 4 | 180 | | if (detected is null |
| | 4 | 181 | | || string.Equals(detected.EncodingName, "utf-8", StringComparison.OrdinalIgnoreCase) |
| | 4 | 182 | | || string.Equals(detected.EncodingName, "ascii", StringComparison.OrdinalIgnoreCase) |
| | 4 | 183 | | || string.Equals(detected.EncodingName, "us-ascii", StringComparison.OrdinalIgnoreCase)) |
| | | 184 | | { |
| | 1 | 185 | | return stream; |
| | | 186 | | } |
| | | 187 | | |
| | 3 | 188 | | _logger.LogDebug("charset {CharSet} detected for {Path}", detected.EncodingName, fileInfo.Path); |
| | | 189 | | |
| | 3 | 190 | | await using (stream.ConfigureAwait(false)) |
| | | 191 | | { |
| | 3 | 192 | | using var reader = new StreamReader(stream, detected.Encoding); |
| | 3 | 193 | | var text = await reader.ReadToEndAsync(cancellationToken).ConfigureAwait(false); |
| | | 194 | | |
| | 3 | 195 | | return new MemoryStream(Encoding.UTF8.GetBytes(text)); |
| | | 196 | | } |
| | 0 | 197 | | } |
| | | 198 | | |
| | 0 | 199 | | return AsyncFile.OpenRead(fileInfo.Path); |
| | 4 | 200 | | } |
| | | 201 | | |
| | | 202 | | internal async Task<SubtitleInfo> GetReadableFile( |
| | | 203 | | MediaSourceInfo mediaSource, |
| | | 204 | | MediaStream subtitleStream, |
| | | 205 | | CancellationToken cancellationToken) |
| | | 206 | | { |
| | 4 | 207 | | if (!subtitleStream.IsExternal || subtitleStream.Path.EndsWith(".mks", StringComparison.OrdinalIgnoreCase)) |
| | | 208 | | { |
| | 0 | 209 | | await ExtractAllExtractableSubtitles(mediaSource, cancellationToken).ConfigureAwait(false); |
| | | 210 | | |
| | 0 | 211 | | var outputFileExtension = GetExtractableSubtitleFileExtension(subtitleStream); |
| | 0 | 212 | | var outputFormat = GetExtractableSubtitleFormat(subtitleStream); |
| | 0 | 213 | | var outputPath = GetSubtitleCachePath(mediaSource, subtitleStream.Index, "." + outputFileExtension) |
| | 0 | 214 | | ?? throw new ResourceNotFoundException($"MediaSource {mediaSource.Id} has no subtitle cache (non-GUI |
| | | 215 | | |
| | 0 | 216 | | return new SubtitleInfo() |
| | 0 | 217 | | { |
| | 0 | 218 | | Path = outputPath, |
| | 0 | 219 | | Protocol = MediaProtocol.File, |
| | 0 | 220 | | Format = outputFormat, |
| | 0 | 221 | | IsExternal = MediaStream.IsVobSubFormat(outputFormat) |
| | 0 | 222 | | }; |
| | | 223 | | } |
| | | 224 | | |
| | | 225 | | // Normalize ffmpeg codec names to the file extensions the parser is keyed on |
| | 4 | 226 | | var currentFormat = NormalizeCodecToParserExtension((Path.GetExtension(subtitleStream.Path) ?? subtitleStrea |
| | | 227 | | |
| | | 228 | | // Handle PGS subtitles as raw streams for the client to render |
| | 4 | 229 | | if (MediaStream.IsPgsFormat(currentFormat)) |
| | | 230 | | { |
| | 0 | 231 | | return new SubtitleInfo() |
| | 0 | 232 | | { |
| | 0 | 233 | | Path = subtitleStream.Path, |
| | 0 | 234 | | Protocol = _mediaSourceManager.GetPathProtocol(subtitleStream.Path), |
| | 0 | 235 | | Format = "pgssub", |
| | 0 | 236 | | IsExternal = true |
| | 0 | 237 | | }; |
| | | 238 | | } |
| | | 239 | | |
| | | 240 | | // Fallback to ffmpeg conversion |
| | 4 | 241 | | if (!_subtitleParser.SupportsFileExtension(currentFormat)) |
| | | 242 | | { |
| | | 243 | | // Convert |
| | 0 | 244 | | var outputPath = GetSubtitleCachePath(mediaSource, subtitleStream.Index, ".srt") |
| | 0 | 245 | | ?? throw new ResourceNotFoundException($"MediaSource {mediaSource.Id} has no subtitle cache (non-GUI |
| | | 246 | | |
| | 0 | 247 | | await ConvertTextSubtitleToSrt(subtitleStream, mediaSource, outputPath, cancellationToken).ConfigureAwai |
| | | 248 | | |
| | 0 | 249 | | return new SubtitleInfo() |
| | 0 | 250 | | { |
| | 0 | 251 | | Path = outputPath, |
| | 0 | 252 | | Protocol = MediaProtocol.File, |
| | 0 | 253 | | Format = "srt", |
| | 0 | 254 | | IsExternal = true |
| | 0 | 255 | | }; |
| | | 256 | | } |
| | | 257 | | |
| | | 258 | | // It's possible that the subtitleStream and mediaSource don't share the same protocol (e.g. .STRM file with |
| | 4 | 259 | | return new SubtitleInfo() |
| | 4 | 260 | | { |
| | 4 | 261 | | Path = subtitleStream.Path, |
| | 4 | 262 | | Protocol = _mediaSourceManager.GetPathProtocol(subtitleStream.Path), |
| | 4 | 263 | | Format = currentFormat, |
| | 4 | 264 | | IsExternal = true |
| | 4 | 265 | | }; |
| | 4 | 266 | | } |
| | | 267 | | |
| | | 268 | | private bool TryGetWriter(string format, [NotNullWhen(true)] out Nikse.SubtitleEdit.Core.SubtitleFormats.Subtitl |
| | | 269 | | { |
| | 104 | 270 | | ArgumentException.ThrowIfNullOrEmpty(format); |
| | | 271 | | |
| | 104 | 272 | | if (string.Equals(format, SubtitleFormat.ASS, StringComparison.OrdinalIgnoreCase)) |
| | | 273 | | { |
| | 0 | 274 | | value = new AdvancedSubStationAlpha(); |
| | 0 | 275 | | return true; |
| | | 276 | | } |
| | | 277 | | |
| | 104 | 278 | | if (string.Equals(format, "json", StringComparison.OrdinalIgnoreCase)) |
| | | 279 | | { |
| | 0 | 280 | | value = new JsonWriter(); |
| | 0 | 281 | | return true; |
| | | 282 | | } |
| | | 283 | | |
| | 104 | 284 | | if (string.Equals(format, SubtitleFormat.SRT, StringComparison.OrdinalIgnoreCase) |
| | 104 | 285 | | || string.Equals(format, SubtitleFormat.SUBRIP, StringComparison.OrdinalIgnoreCase)) |
| | | 286 | | { |
| | 0 | 287 | | value = new SubRip(); |
| | 0 | 288 | | return true; |
| | | 289 | | } |
| | | 290 | | |
| | 104 | 291 | | if (string.Equals(format, SubtitleFormat.SSA, StringComparison.OrdinalIgnoreCase)) |
| | | 292 | | { |
| | 0 | 293 | | value = new SubStationAlpha(); |
| | 0 | 294 | | return true; |
| | | 295 | | } |
| | | 296 | | |
| | 104 | 297 | | if (string.Equals(format, SubtitleFormat.VTT, StringComparison.OrdinalIgnoreCase) |
| | 104 | 298 | | || string.Equals(format, SubtitleFormat.WEBVTT, StringComparison.OrdinalIgnoreCase)) |
| | | 299 | | { |
| | 104 | 300 | | value = new WebVTT(); |
| | 104 | 301 | | return true; |
| | | 302 | | } |
| | | 303 | | |
| | 0 | 304 | | if (string.Equals(format, SubtitleFormat.TTML, StringComparison.OrdinalIgnoreCase)) |
| | | 305 | | { |
| | 0 | 306 | | value = new TimedText10(); |
| | 0 | 307 | | return true; |
| | | 308 | | } |
| | | 309 | | |
| | 0 | 310 | | value = null; |
| | 0 | 311 | | return false; |
| | | 312 | | } |
| | | 313 | | |
| | | 314 | | private Nikse.SubtitleEdit.Core.SubtitleFormats.SubtitleFormat GetWriter(string format) |
| | | 315 | | { |
| | 104 | 316 | | if (TryGetWriter(format, out var writer)) |
| | | 317 | | { |
| | 104 | 318 | | return writer; |
| | | 319 | | } |
| | | 320 | | |
| | 0 | 321 | | throw new ArgumentException("Unsupported format: " + format); |
| | | 322 | | } |
| | | 323 | | |
| | | 324 | | /// <summary> |
| | | 325 | | /// Converts the text subtitle to SRT. |
| | | 326 | | /// </summary> |
| | | 327 | | /// <param name="subtitleStream">The subtitle stream.</param> |
| | | 328 | | /// <param name="mediaSource">The input mediaSource.</param> |
| | | 329 | | /// <param name="outputPath">The output path.</param> |
| | | 330 | | /// <param name="cancellationToken">The cancellation token.</param> |
| | | 331 | | /// <returns>Task.</returns> |
| | | 332 | | private async Task ConvertTextSubtitleToSrt(MediaStream subtitleStream, MediaSourceInfo mediaSource, string outp |
| | | 333 | | { |
| | 0 | 334 | | using (await _semaphoreLocks.LockAsync(outputPath, cancellationToken).ConfigureAwait(false)) |
| | | 335 | | { |
| | 0 | 336 | | if (!IsCachedSubtitleFresh(outputPath, subtitleStream.Path)) |
| | | 337 | | { |
| | 0 | 338 | | await ConvertTextSubtitleToSrtInternal(subtitleStream, mediaSource, outputPath, cancellationToken).C |
| | | 339 | | } |
| | 0 | 340 | | } |
| | 0 | 341 | | } |
| | | 342 | | |
| | | 343 | | // ffmpeg codec names don't always match the file extensions the subtitle parser is keyed on. |
| | | 344 | | private static string NormalizeCodecToParserExtension(string codecOrExtension) |
| | | 345 | | { |
| | 4 | 346 | | return codecOrExtension switch |
| | 4 | 347 | | { |
| | 0 | 348 | | "subrip" => "srt", |
| | 0 | 349 | | "webvtt" => "vtt", |
| | 4 | 350 | | _ => codecOrExtension |
| | 4 | 351 | | }; |
| | | 352 | | } |
| | | 353 | | |
| | | 354 | | // Records "this cache was built from this exact source revision" in a sidecar file next to the cache: "<sizeByt |
| | 0 | 355 | | private static string GetCacheMetaPath(string cachePath) => cachePath + ".meta"; |
| | | 356 | | |
| | | 357 | | private static string FormatCacheMeta(long length, DateTime lastWriteUtc) |
| | 0 | 358 | | => string.Create(CultureInfo.InvariantCulture, $"{length}:{lastWriteUtc.Ticks}"); |
| | | 359 | | |
| | | 360 | | private bool IsCachedSubtitleFresh(string cachePath, string? sourcePath) |
| | | 361 | | { |
| | 0 | 362 | | if (!File.Exists(cachePath)) |
| | | 363 | | { |
| | 0 | 364 | | return false; |
| | | 365 | | } |
| | | 366 | | |
| | 0 | 367 | | var cacheInfo = _fileSystem.GetFileInfo(cachePath); |
| | 0 | 368 | | if (cacheInfo.Length == 0) |
| | | 369 | | { |
| | 0 | 370 | | return false; |
| | | 371 | | } |
| | | 372 | | |
| | 0 | 373 | | if (string.IsNullOrEmpty(sourcePath) || !File.Exists(sourcePath)) |
| | | 374 | | { |
| | 0 | 375 | | return true; |
| | | 376 | | } |
| | | 377 | | |
| | 0 | 378 | | var metaPath = GetCacheMetaPath(cachePath); |
| | 0 | 379 | | if (!File.Exists(metaPath)) |
| | | 380 | | { |
| | | 381 | | // Pre-existing cache from before metadata tracking - regenerate so we can record the source state. |
| | 0 | 382 | | return false; |
| | | 383 | | } |
| | | 384 | | |
| | | 385 | | try |
| | | 386 | | { |
| | 0 | 387 | | var sourceInfo = _fileSystem.GetFileInfo(sourcePath); |
| | 0 | 388 | | var expected = FormatCacheMeta(sourceInfo.Length, sourceInfo.LastWriteTimeUtc); |
| | 0 | 389 | | var actual = File.ReadAllText(metaPath); |
| | 0 | 390 | | return string.Equals(expected, actual, StringComparison.Ordinal); |
| | | 391 | | } |
| | 0 | 392 | | catch (IOException) |
| | | 393 | | { |
| | 0 | 394 | | return false; |
| | | 395 | | } |
| | 0 | 396 | | } |
| | | 397 | | |
| | | 398 | | private void WriteCacheMeta(string cachePath, string? sourcePath) |
| | | 399 | | { |
| | 0 | 400 | | if (string.IsNullOrEmpty(sourcePath)) |
| | | 401 | | { |
| | 0 | 402 | | return; |
| | | 403 | | } |
| | | 404 | | |
| | | 405 | | try |
| | | 406 | | { |
| | 0 | 407 | | var sourceInfo = _fileSystem.GetFileInfo(sourcePath); |
| | 0 | 408 | | if (!sourceInfo.Exists) |
| | | 409 | | { |
| | 0 | 410 | | return; |
| | | 411 | | } |
| | | 412 | | |
| | 0 | 413 | | File.WriteAllText(GetCacheMetaPath(cachePath), FormatCacheMeta(sourceInfo.Length, sourceInfo.LastWriteTi |
| | 0 | 414 | | } |
| | 0 | 415 | | catch (IOException ex) |
| | | 416 | | { |
| | 0 | 417 | | _logger.LogWarning(ex, "Failed to record subtitle cache metadata for {CachePath}", cachePath); |
| | 0 | 418 | | } |
| | 0 | 419 | | } |
| | | 420 | | |
| | | 421 | | /// <summary> |
| | | 422 | | /// Converts the text subtitle to SRT internal. |
| | | 423 | | /// </summary> |
| | | 424 | | /// <param name="subtitleStream">The subtitle stream.</param> |
| | | 425 | | /// <param name="mediaSource">The input mediaSource.</param> |
| | | 426 | | /// <param name="outputPath">The output path.</param> |
| | | 427 | | /// <param name="cancellationToken">The cancellation token.</param> |
| | | 428 | | /// <returns>Task.</returns> |
| | | 429 | | /// <exception cref="ArgumentNullException"> |
| | | 430 | | /// The <c>inputPath</c> or <c>outputPath</c> is <c>null</c>. |
| | | 431 | | /// </exception> |
| | | 432 | | private async Task ConvertTextSubtitleToSrtInternal(MediaStream subtitleStream, MediaSourceInfo mediaSource, str |
| | | 433 | | { |
| | 0 | 434 | | var inputPath = subtitleStream.Path; |
| | 0 | 435 | | ArgumentException.ThrowIfNullOrEmpty(inputPath); |
| | | 436 | | |
| | 0 | 437 | | ArgumentException.ThrowIfNullOrEmpty(outputPath); |
| | | 438 | | |
| | 0 | 439 | | Directory.CreateDirectory(Path.GetDirectoryName(outputPath) ?? throw new ArgumentException($"Provided path ( |
| | | 440 | | |
| | 0 | 441 | | var encodingParam = await GetSubtitleFileCharacterSet(subtitleStream, subtitleStream.Language, mediaSource, |
| | | 442 | | |
| | | 443 | | // FFmpeg automatically convert character encoding when it is UTF-16 |
| | | 444 | | // If we specify character encoding, it rejects with "do not specify a character encoding" and "Unable to re |
| | 0 | 445 | | if ((inputPath.EndsWith(".smi", StringComparison.Ordinal) || inputPath.EndsWith(".sami", StringComparison.Or |
| | 0 | 446 | | (encodingParam.Equals("UTF-16BE", StringComparison.OrdinalIgnoreCase) || |
| | 0 | 447 | | encodingParam.Equals("UTF-16LE", StringComparison.OrdinalIgnoreCase))) |
| | | 448 | | { |
| | 0 | 449 | | encodingParam = string.Empty; |
| | | 450 | | } |
| | 0 | 451 | | else if (!string.IsNullOrEmpty(encodingParam)) |
| | | 452 | | { |
| | 0 | 453 | | encodingParam = " -sub_charenc " + encodingParam; |
| | | 454 | | } |
| | | 455 | | |
| | 0 | 456 | | var args = string.Format(CultureInfo.InvariantCulture, "-y {0} -i \"{1}\" -c:s srt \"{2}\"", encodingParam, |
| | | 457 | | |
| | 0 | 458 | | await ExtractSubtitlesForFile( |
| | 0 | 459 | | inputPath, |
| | 0 | 460 | | args, |
| | 0 | 461 | | [outputPath], |
| | 0 | 462 | | cancellationToken).ConfigureAwait(false); |
| | | 463 | | |
| | 0 | 464 | | WriteCacheMeta(outputPath, inputPath); |
| | 0 | 465 | | } |
| | | 466 | | |
| | | 467 | | private string GetExtractableSubtitleFormat(MediaStream subtitleStream) |
| | | 468 | | { |
| | 0 | 469 | | if (string.Equals(subtitleStream.Codec, "ass", StringComparison.OrdinalIgnoreCase) |
| | 0 | 470 | | || string.Equals(subtitleStream.Codec, "ssa", StringComparison.OrdinalIgnoreCase) |
| | 0 | 471 | | || string.Equals(subtitleStream.Codec, "pgssub", StringComparison.OrdinalIgnoreCase)) |
| | | 472 | | { |
| | 0 | 473 | | return subtitleStream.Codec; |
| | | 474 | | } |
| | 0 | 475 | | else if (MediaStream.IsVobSubFormat(subtitleStream.Codec)) |
| | | 476 | | { |
| | 0 | 477 | | return "mks"; |
| | | 478 | | } |
| | | 479 | | else |
| | | 480 | | { |
| | 0 | 481 | | return "srt"; |
| | | 482 | | } |
| | | 483 | | } |
| | | 484 | | |
| | | 485 | | private string GetExtractableSubtitleFileExtension(MediaStream subtitleStream) |
| | | 486 | | { |
| | | 487 | | // Using .pgssub as file extension is not allowed by ffmpeg. The file extension for pgs subtitles is .sup. |
| | 0 | 488 | | if (string.Equals(subtitleStream.Codec, "pgssub", StringComparison.OrdinalIgnoreCase)) |
| | | 489 | | { |
| | 0 | 490 | | return "sup"; |
| | | 491 | | } |
| | 0 | 492 | | else if (MediaStream.IsVobSubFormat(subtitleStream.Codec)) |
| | | 493 | | { |
| | | 494 | | // FFmpeg cannot mux VobSub subtitle streams back into the .idx/.sub pair, so we use .mks container inst |
| | 0 | 495 | | return "mks"; |
| | | 496 | | } |
| | | 497 | | else |
| | | 498 | | { |
| | 0 | 499 | | return GetExtractableSubtitleFormat(subtitleStream); |
| | | 500 | | } |
| | | 501 | | } |
| | | 502 | | |
| | | 503 | | private bool IsCodecCopyable(string codec) |
| | | 504 | | { |
| | 0 | 505 | | return string.Equals(codec, "ass", StringComparison.OrdinalIgnoreCase) |
| | 0 | 506 | | || string.Equals(codec, "ssa", StringComparison.OrdinalIgnoreCase) |
| | 0 | 507 | | || string.Equals(codec, "srt", StringComparison.OrdinalIgnoreCase) |
| | 0 | 508 | | || string.Equals(codec, "subrip", StringComparison.OrdinalIgnoreCase) |
| | 0 | 509 | | || string.Equals(codec, "pgssub", StringComparison.OrdinalIgnoreCase) |
| | 0 | 510 | | || MediaStream.IsVobSubFormat(codec); |
| | | 511 | | } |
| | | 512 | | |
| | | 513 | | /// <inheritdoc /> |
| | | 514 | | public async Task ExtractAllExtractableSubtitles(MediaSourceInfo mediaSource, CancellationToken cancellationToke |
| | | 515 | | { |
| | 0 | 516 | | var locks = new List<IDisposable>(); |
| | 0 | 517 | | var extractableStreams = new List<MediaStream>(); |
| | | 518 | | |
| | | 519 | | try |
| | | 520 | | { |
| | 0 | 521 | | var subtitleStreams = mediaSource.MediaStreams |
| | 0 | 522 | | .Where(stream => stream is { IsExtractableSubtitleStream: true, SupportsExternalStream: true }); |
| | | 523 | | |
| | 0 | 524 | | foreach (var subtitleStream in subtitleStreams) |
| | | 525 | | { |
| | 0 | 526 | | if (subtitleStream.IsExternal |
| | 0 | 527 | | && !subtitleStream.Path.EndsWith(".mks", StringComparison.OrdinalIgnoreCase)) |
| | | 528 | | { |
| | | 529 | | continue; |
| | | 530 | | } |
| | | 531 | | |
| | 0 | 532 | | var outputPath = GetSubtitleCachePath(mediaSource, subtitleStream.Index, "." + GetExtractableSubtitl |
| | 0 | 533 | | if (outputPath is null) |
| | | 534 | | { |
| | | 535 | | continue; |
| | | 536 | | } |
| | | 537 | | |
| | 0 | 538 | | var releaser = await _semaphoreLocks.LockAsync(outputPath, cancellationToken).ConfigureAwait(false); |
| | | 539 | | |
| | 0 | 540 | | var sourcePath = string.IsNullOrEmpty(subtitleStream.Path) ? mediaSource.Path : subtitleStream.Path; |
| | 0 | 541 | | if (IsCachedSubtitleFresh(outputPath, sourcePath)) |
| | | 542 | | { |
| | 0 | 543 | | releaser.Dispose(); |
| | 0 | 544 | | continue; |
| | | 545 | | } |
| | | 546 | | |
| | 0 | 547 | | locks.Add(releaser); |
| | 0 | 548 | | extractableStreams.Add(subtitleStream); |
| | 0 | 549 | | } |
| | | 550 | | |
| | 0 | 551 | | if (extractableStreams.Count > 0) |
| | | 552 | | { |
| | 0 | 553 | | await ExtractAllExtractableSubtitlesInternal(mediaSource, extractableStreams, cancellationToken).Con |
| | 0 | 554 | | await ExtractAllExtractableSubtitlesMKS(mediaSource, extractableStreams, cancellationToken).Configur |
| | | 555 | | } |
| | 0 | 556 | | } |
| | 0 | 557 | | catch (Exception ex) |
| | | 558 | | { |
| | 0 | 559 | | _logger.LogWarning(ex, "Unable to get streams for File:{File}", mediaSource.Path); |
| | 0 | 560 | | } |
| | | 561 | | finally |
| | | 562 | | { |
| | 0 | 563 | | locks.ForEach(x => x.Dispose()); |
| | | 564 | | } |
| | 0 | 565 | | } |
| | | 566 | | |
| | | 567 | | private async Task ExtractAllExtractableSubtitlesMKS( |
| | | 568 | | MediaSourceInfo mediaSource, |
| | | 569 | | List<MediaStream> subtitleStreams, |
| | | 570 | | CancellationToken cancellationToken) |
| | | 571 | | { |
| | 0 | 572 | | var mksFiles = new List<string>(); |
| | | 573 | | |
| | 0 | 574 | | foreach (var subtitleStream in subtitleStreams) |
| | | 575 | | { |
| | 0 | 576 | | if (string.IsNullOrEmpty(subtitleStream.Path) || !subtitleStream.Path.EndsWith(".mks", StringComparison. |
| | | 577 | | { |
| | | 578 | | continue; |
| | | 579 | | } |
| | | 580 | | |
| | 0 | 581 | | if (!mksFiles.Contains(subtitleStream.Path)) |
| | | 582 | | { |
| | 0 | 583 | | mksFiles.Add(subtitleStream.Path); |
| | | 584 | | } |
| | | 585 | | } |
| | | 586 | | |
| | 0 | 587 | | if (mksFiles.Count == 0) |
| | | 588 | | { |
| | 0 | 589 | | return; |
| | | 590 | | } |
| | | 591 | | |
| | 0 | 592 | | foreach (string mksFile in mksFiles) |
| | | 593 | | { |
| | 0 | 594 | | var inputPath = _mediaEncoder.GetInputArgument(mksFile, mediaSource); |
| | 0 | 595 | | var outputPaths = new List<string>(); |
| | 0 | 596 | | var args = string.Format( |
| | 0 | 597 | | CultureInfo.InvariantCulture, |
| | 0 | 598 | | "-y -i {0}", |
| | 0 | 599 | | inputPath); |
| | | 600 | | |
| | 0 | 601 | | foreach (var subtitleStream in subtitleStreams) |
| | | 602 | | { |
| | 0 | 603 | | if (!subtitleStream.Path.Equals(mksFile, StringComparison.OrdinalIgnoreCase)) |
| | | 604 | | { |
| | | 605 | | continue; |
| | | 606 | | } |
| | | 607 | | |
| | 0 | 608 | | var outputPath = GetSubtitleCachePath(mediaSource, subtitleStream.Index, "." + GetExtractableSubtitl |
| | 0 | 609 | | if (outputPath is null) |
| | | 610 | | { |
| | | 611 | | continue; |
| | | 612 | | } |
| | | 613 | | |
| | 0 | 614 | | var outputCodec = IsCodecCopyable(subtitleStream.Codec) ? "copy" : "srt"; |
| | | 615 | | // FFmpeg does not provide an .idx/.sub muxer, so VobSub streams must be written as MKS files. |
| | 0 | 616 | | var outputFormatOption = MediaStream.IsVobSubFormat(subtitleStream.Codec) ? " -f matroska" : string. |
| | 0 | 617 | | var streamIndex = EncodingHelper.FindIndex(mediaSource.MediaStreams, subtitleStream); |
| | | 618 | | |
| | 0 | 619 | | if (streamIndex == -1) |
| | | 620 | | { |
| | 0 | 621 | | _logger.LogError("Cannot find subtitle stream index for {InputPath} ({Index}), skipping this str |
| | 0 | 622 | | continue; |
| | | 623 | | } |
| | | 624 | | |
| | 0 | 625 | | Directory.CreateDirectory(Path.GetDirectoryName(outputPath) ?? throw new FileNotFoundException($"Cal |
| | | 626 | | |
| | 0 | 627 | | outputPaths.Add(outputPath); |
| | 0 | 628 | | args += string.Format( |
| | 0 | 629 | | CultureInfo.InvariantCulture, |
| | 0 | 630 | | " -map 0:{0} -an -vn -c:s {1}{2} -flush_packets 1 \"{3}\"", |
| | 0 | 631 | | streamIndex, |
| | 0 | 632 | | outputCodec, |
| | 0 | 633 | | outputFormatOption, |
| | 0 | 634 | | outputPath); |
| | | 635 | | } |
| | | 636 | | |
| | 0 | 637 | | await ExtractSubtitlesForFile(inputPath, args, outputPaths, cancellationToken).ConfigureAwait(false); |
| | | 638 | | |
| | 0 | 639 | | foreach (var outputPath in outputPaths) |
| | | 640 | | { |
| | 0 | 641 | | WriteCacheMeta(outputPath, mksFile); |
| | | 642 | | } |
| | 0 | 643 | | } |
| | 0 | 644 | | } |
| | | 645 | | |
| | | 646 | | private async Task ExtractAllExtractableSubtitlesInternal( |
| | | 647 | | MediaSourceInfo mediaSource, |
| | | 648 | | List<MediaStream> subtitleStreams, |
| | | 649 | | CancellationToken cancellationToken) |
| | | 650 | | { |
| | 0 | 651 | | var inputPath = _mediaEncoder.GetInputArgument(mediaSource.Path, mediaSource); |
| | 0 | 652 | | var outputPaths = new List<string>(); |
| | 0 | 653 | | var args = string.Format( |
| | 0 | 654 | | CultureInfo.InvariantCulture, |
| | 0 | 655 | | "-y -i {0}", |
| | 0 | 656 | | inputPath); |
| | | 657 | | |
| | 0 | 658 | | foreach (var subtitleStream in subtitleStreams) |
| | | 659 | | { |
| | 0 | 660 | | if (!string.IsNullOrEmpty(subtitleStream.Path) && subtitleStream.Path.EndsWith(".mks", StringComparison. |
| | | 661 | | { |
| | 0 | 662 | | _logger.LogDebug("Subtitle {Index} for file {InputPath} is part in an MKS file. Skipping", inputPath |
| | 0 | 663 | | continue; |
| | | 664 | | } |
| | | 665 | | |
| | 0 | 666 | | var outputPath = GetSubtitleCachePath(mediaSource, subtitleStream.Index, "." + GetExtractableSubtitleFil |
| | 0 | 667 | | if (outputPath is null) |
| | | 668 | | { |
| | | 669 | | continue; |
| | | 670 | | } |
| | | 671 | | |
| | 0 | 672 | | var outputCodec = IsCodecCopyable(subtitleStream.Codec) ? "copy" : "srt"; |
| | | 673 | | // FFmpeg does not provide an .idx/.sub muxer, so VobSub streams must be written as MKS files. |
| | 0 | 674 | | var outputFormatOption = MediaStream.IsVobSubFormat(subtitleStream.Codec) ? " -f matroska" : string.Empt |
| | 0 | 675 | | var streamIndex = EncodingHelper.FindIndex(mediaSource.MediaStreams, subtitleStream); |
| | | 676 | | |
| | 0 | 677 | | if (streamIndex == -1) |
| | | 678 | | { |
| | 0 | 679 | | _logger.LogError("Cannot find subtitle stream index for {InputPath} ({Index}), skipping this stream" |
| | 0 | 680 | | continue; |
| | | 681 | | } |
| | | 682 | | |
| | 0 | 683 | | Directory.CreateDirectory(Path.GetDirectoryName(outputPath) ?? throw new FileNotFoundException($"Calcula |
| | | 684 | | |
| | 0 | 685 | | outputPaths.Add(outputPath); |
| | 0 | 686 | | args += string.Format( |
| | 0 | 687 | | CultureInfo.InvariantCulture, |
| | 0 | 688 | | " -map 0:{0} -an -vn -c:s {1}{2} -flush_packets 1 \"{3}\"", |
| | 0 | 689 | | streamIndex, |
| | 0 | 690 | | outputCodec, |
| | 0 | 691 | | outputFormatOption, |
| | 0 | 692 | | outputPath); |
| | | 693 | | } |
| | | 694 | | |
| | 0 | 695 | | if (outputPaths.Count > 0) |
| | | 696 | | { |
| | 0 | 697 | | await ExtractSubtitlesForFile(inputPath, args, outputPaths, cancellationToken).ConfigureAwait(false); |
| | | 698 | | |
| | 0 | 699 | | foreach (var outputPath in outputPaths) |
| | | 700 | | { |
| | 0 | 701 | | WriteCacheMeta(outputPath, mediaSource.Path); |
| | | 702 | | } |
| | | 703 | | } |
| | 0 | 704 | | } |
| | | 705 | | |
| | | 706 | | private async Task ExtractSubtitlesForFile( |
| | | 707 | | string inputPath, |
| | | 708 | | string args, |
| | | 709 | | IReadOnlyList<string> outputPaths, |
| | | 710 | | CancellationToken cancellationToken) |
| | | 711 | | { |
| | 0 | 712 | | var (exitCode, ffmpegError) = await RunSubtitleExtractionProcess(args, cancellationToken).ConfigureAwait(fal |
| | | 713 | | |
| | 0 | 714 | | var failed = false; |
| | | 715 | | |
| | 0 | 716 | | if (exitCode == -1) |
| | | 717 | | { |
| | 0 | 718 | | failed = true; |
| | | 719 | | |
| | 0 | 720 | | foreach (var outputPath in outputPaths) |
| | | 721 | | { |
| | | 722 | | try |
| | | 723 | | { |
| | 0 | 724 | | _logger.LogWarning("Deleting extracted subtitle due to failure: {Path}", outputPath); |
| | 0 | 725 | | _fileSystem.DeleteFile(outputPath); |
| | 0 | 726 | | } |
| | 0 | 727 | | catch (FileNotFoundException) |
| | | 728 | | { |
| | 0 | 729 | | } |
| | 0 | 730 | | catch (IOException ex) |
| | | 731 | | { |
| | 0 | 732 | | _logger.LogError(ex, "Error deleting extracted subtitle {Path}", outputPath); |
| | 0 | 733 | | } |
| | | 734 | | } |
| | | 735 | | } |
| | | 736 | | else |
| | | 737 | | { |
| | 0 | 738 | | foreach (var outputPath in outputPaths) |
| | | 739 | | { |
| | 0 | 740 | | if (!File.Exists(outputPath) || _fileSystem.GetFileInfo(outputPath).Length == 0) |
| | | 741 | | { |
| | 0 | 742 | | _logger.LogError("ffmpeg subtitle extraction failed for {InputPath} to {OutputPath}", inputPath, |
| | 0 | 743 | | failed = true; |
| | | 744 | | |
| | | 745 | | try |
| | | 746 | | { |
| | 0 | 747 | | _logger.LogWarning("Deleting extracted subtitle due to failure: {Path}", outputPath); |
| | 0 | 748 | | _fileSystem.DeleteFile(outputPath); |
| | 0 | 749 | | } |
| | 0 | 750 | | catch (FileNotFoundException) |
| | | 751 | | { |
| | 0 | 752 | | } |
| | 0 | 753 | | catch (IOException ex) |
| | | 754 | | { |
| | 0 | 755 | | _logger.LogError(ex, "Error deleting extracted subtitle {Path}", outputPath); |
| | 0 | 756 | | } |
| | | 757 | | |
| | | 758 | | continue; |
| | | 759 | | } |
| | | 760 | | |
| | 0 | 761 | | if (outputPath.EndsWith("ass", StringComparison.OrdinalIgnoreCase)) |
| | | 762 | | { |
| | 0 | 763 | | await SetAssFont(outputPath, cancellationToken).ConfigureAwait(false); |
| | | 764 | | } |
| | | 765 | | |
| | 0 | 766 | | _logger.LogInformation("ffmpeg subtitle extraction completed for {InputPath} to {OutputPath}", input |
| | 0 | 767 | | } |
| | | 768 | | } |
| | | 769 | | |
| | 0 | 770 | | if (failed) |
| | | 771 | | { |
| | 0 | 772 | | cancellationToken.ThrowIfCancellationRequested(); |
| | | 773 | | |
| | 0 | 774 | | if (!string.IsNullOrWhiteSpace(ffmpegError)) |
| | | 775 | | { |
| | 0 | 776 | | _logger.LogError("ffmpeg subtitle extraction failed for {InputPath}: {FfmpegOutput}", inputPath, ffm |
| | | 777 | | } |
| | | 778 | | |
| | 0 | 779 | | throw new FfmpegException( |
| | 0 | 780 | | string.Format(CultureInfo.InvariantCulture, "ffmpeg subtitle extraction failed for {0}", inputPath)) |
| | | 781 | | } |
| | 0 | 782 | | } |
| | | 783 | | |
| | | 784 | | /// <summary> |
| | | 785 | | /// Extracts the text subtitle. |
| | | 786 | | /// </summary> |
| | | 787 | | /// <param name="mediaSource">The mediaSource.</param> |
| | | 788 | | /// <param name="subtitleStream">The subtitle stream.</param> |
| | | 789 | | /// <param name="outputCodec">The output codec.</param> |
| | | 790 | | /// <param name="outputPath">The output path.</param> |
| | | 791 | | /// <param name="cancellationToken">The cancellation token.</param> |
| | | 792 | | /// <returns>Task.</returns> |
| | | 793 | | /// <exception cref="ArgumentException">Must use inputPath list overload.</exception> |
| | | 794 | | private async Task ExtractTextSubtitle( |
| | | 795 | | MediaSourceInfo mediaSource, |
| | | 796 | | MediaStream subtitleStream, |
| | | 797 | | string outputCodec, |
| | | 798 | | string outputPath, |
| | | 799 | | CancellationToken cancellationToken) |
| | | 800 | | { |
| | 0 | 801 | | using (await _semaphoreLocks.LockAsync(outputPath, cancellationToken).ConfigureAwait(false)) |
| | | 802 | | { |
| | 0 | 803 | | if (!File.Exists(outputPath) || _fileSystem.GetFileInfo(outputPath).Length == 0) |
| | | 804 | | { |
| | 0 | 805 | | var subtitleStreamIndex = EncodingHelper.FindIndex(mediaSource.MediaStreams, subtitleStream); |
| | | 806 | | |
| | 0 | 807 | | var args = _mediaEncoder.GetInputArgument(mediaSource.Path, mediaSource); |
| | | 808 | | |
| | 0 | 809 | | if (subtitleStream.IsExternal) |
| | | 810 | | { |
| | 0 | 811 | | args = _mediaEncoder.GetExternalSubtitleInputArgument(subtitleStream.Path); |
| | | 812 | | } |
| | | 813 | | |
| | 0 | 814 | | await ExtractTextSubtitleInternal( |
| | 0 | 815 | | args, |
| | 0 | 816 | | subtitleStreamIndex, |
| | 0 | 817 | | outputCodec, |
| | 0 | 818 | | outputPath, |
| | 0 | 819 | | cancellationToken).ConfigureAwait(false); |
| | | 820 | | } |
| | 0 | 821 | | } |
| | 0 | 822 | | } |
| | | 823 | | |
| | | 824 | | private async Task ExtractTextSubtitleInternal( |
| | | 825 | | string inputPath, |
| | | 826 | | int subtitleStreamIndex, |
| | | 827 | | string outputCodec, |
| | | 828 | | string outputPath, |
| | | 829 | | CancellationToken cancellationToken) |
| | | 830 | | { |
| | 0 | 831 | | ArgumentException.ThrowIfNullOrEmpty(inputPath); |
| | | 832 | | |
| | 0 | 833 | | ArgumentException.ThrowIfNullOrEmpty(outputPath); |
| | | 834 | | |
| | 0 | 835 | | Directory.CreateDirectory(Path.GetDirectoryName(outputPath) ?? throw new ArgumentException($"Provided path ( |
| | 0 | 836 | | var processArgs = string.Format( |
| | 0 | 837 | | CultureInfo.InvariantCulture, |
| | 0 | 838 | | "-y -i {0} -copyts -map 0:{1} -an -vn -c:s {2} \"{3}\"", |
| | 0 | 839 | | inputPath, |
| | 0 | 840 | | subtitleStreamIndex, |
| | 0 | 841 | | outputCodec, |
| | 0 | 842 | | outputPath); |
| | | 843 | | |
| | 0 | 844 | | await ExtractSubtitlesForFile( |
| | 0 | 845 | | inputPath, |
| | 0 | 846 | | processArgs, |
| | 0 | 847 | | [outputPath], |
| | 0 | 848 | | cancellationToken).ConfigureAwait(false); |
| | 0 | 849 | | } |
| | | 850 | | |
| | | 851 | | /// <summary> |
| | | 852 | | /// Runs ffmpeg to extract or convert subtitles, capturing its exit code and stderr output. |
| | | 853 | | /// </summary> |
| | | 854 | | /// <remarks> |
| | | 855 | | /// stdin is redirected and closed, and <c>-nostdin</c> is prepended to the arguments, so ffmpeg can never |
| | | 856 | | /// block reading an inherited stdin handle (which happens when Jellyfin runs as a service, e.g. under NSSM, |
| | | 857 | | /// and stalls subtitle extraction until the timeout). stderr is redirected and drained so a full pipe buffer |
| | | 858 | | /// cannot deadlock ffmpeg and so its output can be surfaced on failure; stdout is left un-redirected as it is |
| | | 859 | | /// unused for subtitle extraction. |
| | | 860 | | /// </remarks> |
| | | 861 | | /// <param name="arguments">The ffmpeg command line arguments.</param> |
| | | 862 | | /// <param name="cancellationToken">The cancellation token.</param> |
| | | 863 | | /// <returns>The ffmpeg exit code (-1 on timeout) and its captured stderr output.</returns> |
| | | 864 | | private async Task<(int ExitCode, string StandardError)> RunSubtitleExtractionProcess(string arguments, Cancella |
| | | 865 | | { |
| | | 866 | | int exitCode; |
| | 0 | 867 | | var standardError = string.Empty; |
| | | 868 | | |
| | 0 | 869 | | using (var process = new Process |
| | 0 | 870 | | { |
| | 0 | 871 | | StartInfo = new ProcessStartInfo |
| | 0 | 872 | | { |
| | 0 | 873 | | CreateNoWindow = true, |
| | 0 | 874 | | UseShellExecute = false, |
| | 0 | 875 | | RedirectStandardInput = true, |
| | 0 | 876 | | RedirectStandardError = true, |
| | 0 | 877 | | FileName = _mediaEncoder.EncoderPath, |
| | 0 | 878 | | Arguments = "-nostdin " + arguments, |
| | 0 | 879 | | WindowStyle = ProcessWindowStyle.Hidden, |
| | 0 | 880 | | ErrorDialog = false |
| | 0 | 881 | | }, |
| | 0 | 882 | | EnableRaisingEvents = true |
| | 0 | 883 | | }) |
| | | 884 | | { |
| | 0 | 885 | | _logger.LogInformation("{File} {Arguments}", process.StartInfo.FileName, process.StartInfo.Arguments); |
| | | 886 | | |
| | | 887 | | try |
| | | 888 | | { |
| | 0 | 889 | | process.Start(); |
| | 0 | 890 | | } |
| | 0 | 891 | | catch (Exception ex) |
| | | 892 | | { |
| | 0 | 893 | | _logger.LogError(ex, "Error starting ffmpeg"); |
| | 0 | 894 | | throw; |
| | | 895 | | } |
| | | 896 | | |
| | | 897 | | // Close stdin so ffmpeg observes EOF instead of blocking on an inherited handle. |
| | 0 | 898 | | process.StandardInput.Close(); |
| | | 899 | | |
| | | 900 | | // Begin draining stderr before waiting for exit; a full stderr pipe buffer would otherwise deadlock ffm |
| | 0 | 901 | | var standardErrorTask = process.StandardError.ReadToEndAsync(CancellationToken.None); |
| | 0 | 902 | | var timeoutMinutes = _serverConfigurationManager.GetEncodingOptions().SubtitleExtractionTimeoutMinutes; |
| | 0 | 903 | | using var waitSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); |
| | 0 | 904 | | waitSource.CancelAfter(TimeSpan.FromMinutes(timeoutMinutes)); |
| | | 905 | | |
| | | 906 | | try |
| | | 907 | | { |
| | 0 | 908 | | await process.WaitForExitAsync(waitSource.Token).ConfigureAwait(false); |
| | 0 | 909 | | exitCode = process.ExitCode; |
| | 0 | 910 | | } |
| | 0 | 911 | | catch (OperationCanceledException) |
| | | 912 | | { |
| | 0 | 913 | | process.Kill(true); |
| | 0 | 914 | | exitCode = -1; |
| | 0 | 915 | | } |
| | | 916 | | |
| | | 917 | | try |
| | | 918 | | { |
| | 0 | 919 | | standardError = await standardErrorTask.ConfigureAwait(false); |
| | 0 | 920 | | } |
| | 0 | 921 | | catch (OperationCanceledException) |
| | | 922 | | { |
| | | 923 | | // Reading ffmpeg output was cancelled; nothing more to capture. |
| | 0 | 924 | | } |
| | 0 | 925 | | } |
| | | 926 | | |
| | 0 | 927 | | return (exitCode, standardError); |
| | 0 | 928 | | } |
| | | 929 | | |
| | | 930 | | /// <summary> |
| | | 931 | | /// Sets the ass font. |
| | | 932 | | /// </summary> |
| | | 933 | | /// <param name="file">The file.</param> |
| | | 934 | | /// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <c>Syst |
| | | 935 | | /// <returns>Task.</returns> |
| | | 936 | | private async Task SetAssFont(string file, CancellationToken cancellationToken = default) |
| | | 937 | | { |
| | 0 | 938 | | _logger.LogInformation("Setting ass font within {File}", file); |
| | | 939 | | |
| | | 940 | | string text; |
| | | 941 | | Encoding encoding; |
| | | 942 | | |
| | 0 | 943 | | using (var fileStream = AsyncFile.OpenRead(file)) |
| | 0 | 944 | | using (var reader = new StreamReader(fileStream, true)) |
| | | 945 | | { |
| | 0 | 946 | | encoding = reader.CurrentEncoding; |
| | | 947 | | |
| | 0 | 948 | | text = await reader.ReadToEndAsync(cancellationToken).ConfigureAwait(false); |
| | 0 | 949 | | } |
| | | 950 | | |
| | 0 | 951 | | var newText = text.Replace(",Arial,", ",Arial Unicode MS,", StringComparison.Ordinal); |
| | | 952 | | |
| | 0 | 953 | | if (!string.Equals(text, newText, StringComparison.Ordinal)) |
| | | 954 | | { |
| | 0 | 955 | | var fileStream = new FileStream(file, FileMode.Create, FileAccess.Write, FileShare.None, IODefaults.File |
| | 0 | 956 | | await using (fileStream.ConfigureAwait(false)) |
| | | 957 | | { |
| | 0 | 958 | | var writer = new StreamWriter(fileStream, encoding); |
| | 0 | 959 | | await using (writer.ConfigureAwait(false)) |
| | | 960 | | { |
| | 0 | 961 | | await writer.WriteAsync(newText.AsMemory(), cancellationToken).ConfigureAwait(false); |
| | | 962 | | } |
| | | 963 | | } |
| | | 964 | | } |
| | 0 | 965 | | } |
| | | 966 | | |
| | | 967 | | private string? GetSubtitleCachePath(MediaSourceInfo mediaSource, int subtitleStreamIndex, string outputSubtitle |
| | | 968 | | { |
| | 0 | 969 | | return _pathManager.GetSubtitlePath(mediaSource.Id, subtitleStreamIndex, outputSubtitleExtension); |
| | | 970 | | } |
| | | 971 | | |
| | | 972 | | /// <inheritdoc /> |
| | | 973 | | public async Task<string> GetSubtitleFileCharacterSet(MediaStream subtitleStream, string language, MediaSourceIn |
| | | 974 | | { |
| | 0 | 975 | | var subtitleCodec = subtitleStream.Codec; |
| | 0 | 976 | | var path = subtitleStream.Path; |
| | | 977 | | |
| | 0 | 978 | | if (path.EndsWith(".mks", StringComparison.OrdinalIgnoreCase)) |
| | | 979 | | { |
| | 0 | 980 | | var cachePath = GetSubtitleCachePath(mediaSource, subtitleStream.Index, "." + subtitleCodec); |
| | 0 | 981 | | if (cachePath is not null) |
| | | 982 | | { |
| | 0 | 983 | | path = cachePath; |
| | 0 | 984 | | await ExtractTextSubtitle(mediaSource, subtitleStream, subtitleCodec, path, cancellationToken) |
| | 0 | 985 | | .ConfigureAwait(false); |
| | | 986 | | } |
| | | 987 | | } |
| | | 988 | | |
| | 0 | 989 | | var result = await DetectCharset(path, cancellationToken).ConfigureAwait(false); |
| | 0 | 990 | | var charset = result.Detected?.EncodingName ?? string.Empty; |
| | | 991 | | |
| | | 992 | | // UTF16 is automatically converted to UTF8 by FFmpeg, do not specify a character encoding |
| | 0 | 993 | | if ((path.EndsWith(".ass", StringComparison.Ordinal) || path.EndsWith(".ssa", StringComparison.Ordinal) || p |
| | 0 | 994 | | && (string.Equals(charset, "utf-16le", StringComparison.OrdinalIgnoreCase) |
| | 0 | 995 | | || string.Equals(charset, "utf-16be", StringComparison.OrdinalIgnoreCase))) |
| | | 996 | | { |
| | 0 | 997 | | charset = string.Empty; |
| | | 998 | | } |
| | | 999 | | |
| | 0 | 1000 | | _logger.LogDebug("charset {0} detected for {Path}", charset, path); |
| | | 1001 | | |
| | 0 | 1002 | | return charset; |
| | 0 | 1003 | | } |
| | | 1004 | | |
| | | 1005 | | private async Task<DetectionResult> DetectCharset(string path, CancellationToken cancellationToken) |
| | | 1006 | | { |
| | 4 | 1007 | | var protocol = _mediaSourceManager.GetPathProtocol(path); |
| | | 1008 | | switch (protocol) |
| | | 1009 | | { |
| | | 1010 | | case MediaProtocol.Http: |
| | | 1011 | | { |
| | 0 | 1012 | | using var stream = await _httpClientFactory |
| | 0 | 1013 | | .CreateClient(NamedClient.Default) |
| | 0 | 1014 | | .GetStreamAsync(new Uri(path), cancellationToken) |
| | 0 | 1015 | | .ConfigureAwait(false); |
| | | 1016 | | |
| | 0 | 1017 | | return await CharsetDetector.DetectFromStreamAsync(stream, cancellationToken).ConfigureAwait(fal |
| | | 1018 | | } |
| | | 1019 | | |
| | | 1020 | | case MediaProtocol.File: |
| | | 1021 | | { |
| | 4 | 1022 | | return await CharsetDetector.DetectFromFileAsync(path, cancellationToken) |
| | 4 | 1023 | | .ConfigureAwait(false); |
| | | 1024 | | } |
| | | 1025 | | |
| | | 1026 | | default: |
| | 0 | 1027 | | throw new NotSupportedException($"Unsupported protocol: {protocol}"); |
| | | 1028 | | } |
| | 4 | 1029 | | } |
| | | 1030 | | |
| | | 1031 | | public async Task<string> GetSubtitleFilePath(MediaStream subtitleStream, MediaSourceInfo mediaSource, Cancellat |
| | | 1032 | | { |
| | 0 | 1033 | | var info = await GetReadableFile(mediaSource, subtitleStream, cancellationToken) |
| | 0 | 1034 | | .ConfigureAwait(false); |
| | 0 | 1035 | | return info.Path; |
| | 0 | 1036 | | } |
| | | 1037 | | |
| | | 1038 | | /// <inheritdoc /> |
| | | 1039 | | public void Dispose() |
| | | 1040 | | { |
| | 24 | 1041 | | _semaphoreLocks.Dispose(); |
| | 24 | 1042 | | } |
| | | 1043 | | |
| | | 1044 | | #pragma warning disable CA1034 // Nested types should not be visible |
| | | 1045 | | // Only public for the unit tests |
| | | 1046 | | public readonly record struct SubtitleInfo |
| | | 1047 | | { |
| | | 1048 | | public string Path { get; init; } |
| | | 1049 | | |
| | | 1050 | | public MediaProtocol Protocol { get; init; } |
| | | 1051 | | |
| | | 1052 | | public string Format { get; init; } |
| | | 1053 | | |
| | | 1054 | | public bool IsExternal { get; init; } |
| | | 1055 | | } |
| | | 1056 | | } |
| | | 1057 | | } |