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