The Free Software Media System - Server Backend & API
Merge changes
Mark Cilia Vincentif26fc7dfb263
diff --cc Directory.Packages.propsindex 29b9030ac4,8b4813f566..7c0169c6ef--- a/Directory.Packages.props+++ b/Directory.Packages.props@@@ -4,7 -4,6 +4,7 @@@</PropertyGroup><!-- Run "dotnet list package (dash,dash)outdated" to see the latest versions of each package.--><ItemGroup Label="Package Dependencies">- <PackageVersion Include="AsyncKeyedLock" Version="6.3.0" />++ <PackageVersion Include="AsyncKeyedLock" Version="6.3.4" /><PackageVersion Include="AutoFixture.AutoMoq" Version="4.18.1" /><PackageVersion Include="AutoFixture.Xunit2" Version="4.18.1" /><PackageVersion Include="AutoFixture" Version="4.18.1" />@@@ -86,6 -85,6 +86,6 @@@<PackageVersion Include="Xunit.Priority" Version="1.1.6" /><PackageVersion Include="xunit.runner.visualstudio" Version="2.5.6" /><PackageVersion Include="Xunit.SkippableFact" Version="1.4.13" />- <PackageVersion Include="xunit" Version="2.6.6" />+ <PackageVersion Include="xunit" Version="2.6.5" /></ItemGroup>--</Project>++</Project>diff --cc Emby.Server.Implementations/Library/MediaSourceManager.csindex ec6029faf3,c38f1af912..18ada6aeb5--- a/Emby.Server.Implementations/Library/MediaSourceManager.cs+++ b/Emby.Server.Implementations/Library/MediaSourceManager.cs@@@ -11,9 -11,9 +11,10 @@@ using System.Linqusing System.Text.Json;using System.Threading;using System.Threading.Tasks;+using AsyncKeyedLock;using Jellyfin.Data.Entities;using Jellyfin.Data.Enums;+ using Jellyfin.Extensions;using Jellyfin.Extensions.Json;using MediaBrowser.Common.Configuration;using MediaBrowser.Common.Extensions;diff --cc MediaBrowser.MediaEncoding/Encoder/MediaEncoder.csindex 7d5ec615a0,4dbefca4bb..f86d14fc86--- a/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs+++ b/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs@@@ -904,8 -908,8 +904,7 @@@ namespace MediaBrowser.MediaEncoding.En{bool ranToCompletion = false;-- await _thumbnailResourcePool.WaitAsync(cancellationToken).ConfigureAwait(false);-- try++ using (await _thumbnailResourcePool.LockAsync(cancellationToken).ConfigureAwait(false)){StartProcess(processWrapper);@@@ -959,10 -963,10 +958,6 @@@StopProcess(processWrapper, 1000);}}-- finally-- {-- _thumbnailResourcePool.Release();-- }var exitCode = ranToCompletion ? processWrapper.ExitCode ?? 0 : -1;diff --cc MediaBrowser.MediaEncoding/Subtitles/SubtitleEncoder.csindex a546c80b43,8fd1f9fc1e..8f1cc3f645--- a/MediaBrowser.MediaEncoding/Subtitles/SubtitleEncoder.cs+++ b/MediaBrowser.MediaEncoding/Subtitles/SubtitleEncoder.cs@@@ -1,6 -1,8 +1,7 @@@#pragma warning disable CS1591using System;-using System.Collections.Concurrent;+ using System.Collections.Generic;using System.Diagnostics;using System.Diagnostics.CodeAnalysis;using System.Globalization;@@@ -453,6 -443,203 +428,203 @@@ namespace MediaBrowser.MediaEncoding.Su_logger.LogInformation("ffmpeg subtitle conversion succeeded for {Path}", inputPath);}+ private string GetTextSubtitleFormat(MediaStream subtitleStream)+ {+ if (string.Equals(subtitleStream.Codec, "ass", StringComparison.OrdinalIgnoreCase)+ || string.Equals(subtitleStream.Codec, "ssa", StringComparison.OrdinalIgnoreCase))+ {+ return subtitleStream.Codec;+ }+ else+ {+ return "srt";+ }+ }++ private bool IsCodecCopyable(string codec)+ {+ return string.Equals(codec, "ass", StringComparison.OrdinalIgnoreCase)+ || string.Equals(codec, "ssa", StringComparison.OrdinalIgnoreCase)+ || string.Equals(codec, "srt", StringComparison.OrdinalIgnoreCase)+ || string.Equals(codec, "subrip", StringComparison.OrdinalIgnoreCase);+ }++ /// <summary>+ /// Extracts all text subtitles.+ /// </summary>+ /// <param name="mediaSource">The mediaSource.</param>+ /// <param name="cancellationToken">The cancellation token.</param>+ /// <returns>Task.</returns>+ private async Task ExtractAllTextSubtitles(MediaSourceInfo mediaSource, CancellationToken cancellationToken)+ {- var semaphores = new List<SemaphoreSlim>();++ var locks = new List<AsyncKeyedLockReleaser<string>>();+ var extractableStreams = new List<MediaStream>();++ try+ {+ var subtitleStreams = mediaSource.MediaStreams+ .Where(stream => stream.IsTextSubtitleStream && stream.SupportsExternalStream);++ foreach (var subtitleStream in subtitleStreams)+ {+ var outputPath = GetSubtitleCachePath(mediaSource, subtitleStream.Index, "." + GetTextSubtitleFormat(subtitleStream));+- var semaphore = GetLock(outputPath);- await semaphore.WaitAsync(cancellationToken).ConfigureAwait(false);++ var @lock = _semaphoreLocks.GetOrAdd(outputPath);++ await @lock.SemaphoreSlim.WaitAsync(cancellationToken).ConfigureAwait(false);++ if (File.Exists(outputPath))+ {- semaphore.Release();++ @lock.Dispose();+ continue;+ }+- semaphores.Add(semaphore);++ locks.Add(@lock);+ extractableStreams.Add(subtitleStream);+ }++ if (extractableStreams.Count > 0)+ {+ await ExtractAllTextSubtitlesInternal(mediaSource, extractableStreams, cancellationToken).ConfigureAwait(false);+ }+ }+ catch (Exception ex)+ {+ _logger.LogWarning(ex, "Unable to get streams for File:{File}", mediaSource.Path);+ }+ finally+ {- foreach (var semaphore in semaphores)++ foreach (var @lock in locks)+ {- semaphore.Release();++ @lock.Dispose();+ }+ }+ }++ private async Task ExtractAllTextSubtitlesInternal(+ MediaSourceInfo mediaSource,+ List<MediaStream> subtitleStreams,+ CancellationToken cancellationToken)+ {+ var inputPath = mediaSource.Path;+ var outputPaths = new List<string>();+ var args = string.Format(+ CultureInfo.InvariantCulture,+ "-i {0} -copyts",+ inputPath);++ foreach (var subtitleStream in subtitleStreams)+ {+ var outputPath = GetSubtitleCachePath(mediaSource, subtitleStream.Index, "." + GetTextSubtitleFormat(subtitleStream));+ var outputCodec = IsCodecCopyable(subtitleStream.Codec) ? "copy" : "srt";+ var streamIndex = EncodingHelper.FindIndex(mediaSource.MediaStreams, subtitleStream);++ if (streamIndex == -1)+ {+ _logger.LogError("Cannot find subtitle stream index for {InputPath} ({Index}), skipping this stream", inputPath, subtitleStream.Index);+ continue;+ }++ Directory.CreateDirectory(Path.GetDirectoryName(outputPath) ?? throw new FileNotFoundException($"Calculated path ({outputPath}) is not valid."));++ outputPaths.Add(outputPath);+ args += string.Format(+ CultureInfo.InvariantCulture,+ " -map 0:{0} -an -vn -c:s {1} \"{2}\"",+ streamIndex,+ outputCodec,+ outputPath);+ }++ int exitCode;++ using (var process = new Process+ {+ StartInfo = new ProcessStartInfo+ {+ CreateNoWindow = true,+ UseShellExecute = false,+ FileName = _mediaEncoder.EncoderPath,+ Arguments = args,+ WindowStyle = ProcessWindowStyle.Hidden,+ ErrorDialog = false+ },+ EnableRaisingEvents = true+ })+ {+ _logger.LogInformation("{File} {Arguments}", process.StartInfo.FileName, process.StartInfo.Arguments);++ try+ {+ process.Start();+ }+ catch (Exception ex)+ {+ _logger.LogError(ex, "Error starting ffmpeg");++ throw;+ }++ try+ {+ await process.WaitForExitAsync(TimeSpan.FromMinutes(30)).ConfigureAwait(false);+ exitCode = process.ExitCode;+ }+ catch (OperationCanceledException)+ {+ process.Kill(true);+ exitCode = -1;+ }+ }++ var failed = false;++ if (exitCode == -1)+ {+ failed = true;++ foreach (var outputPath in outputPaths)+ {+ try+ {+ _logger.LogWarning("Deleting extracted subtitle due to failure: {Path}", outputPath);+ _fileSystem.DeleteFile(outputPath);+ }+ catch (FileNotFoundException)+ {+ }+ catch (IOException ex)+ {+ _logger.LogError(ex, "Error deleting extracted subtitle {Path}", outputPath);+ }+ }+ }+ else+ {+ foreach (var outputPath in outputPaths)+ {+ if (!File.Exists(outputPath))+ {+ _logger.LogError("ffmpeg subtitle extraction failed for {InputPath} to {OutputPath}", inputPath, outputPath);+ failed = true;+ continue;+ }++ if (outputPath.EndsWith("ass", StringComparison.OrdinalIgnoreCase))+ {+ await SetAssFont(outputPath, cancellationToken).ConfigureAwait(false);+ }++ _logger.LogInformation("ffmpeg subtitle extraction completed for {InputPath} to {OutputPath}", inputPath, outputPath);+ }+ }++ if (failed)+ {+ throw new FfmpegException(+ string.Format(CultureInfo.InvariantCulture, "ffmpeg subtitle extraction failed for {0}", inputPath));+ }+ }+/// <summary>/// Extracts the text subtitle./// </summary>diff --cc MediaBrowser.MediaEncoding/Transcoding/TranscodeManager.csindex bb61d7fa6a,d79e4441aa..ab3eb3298b--- a/MediaBrowser.MediaEncoding/Transcoding/TranscodeManager.cs+++ b/MediaBrowser.MediaEncoding/Transcoding/TranscodeManager.cs@@@ -9,8 -8,8 +9,9 @@@ using System.Textusing System.Text.Json;using System.Threading;using System.Threading.Tasks;+using AsyncKeyedLock;using Jellyfin.Data.Enums;+ using Jellyfin.Extensions;using MediaBrowser.Common;using MediaBrowser.Common.Configuration;using MediaBrowser.Common.Extensions;