diff options
Diffstat (limited to 'MediaBrowser.MediaEncoding')
3 files changed, 52 insertions, 170 deletions
diff --git a/MediaBrowser.MediaEncoding/Attachments/AttachmentExtractor.cs b/MediaBrowser.MediaEncoding/Attachments/AttachmentExtractor.cs index fbe8afc66e..756b67e063 100644 --- a/MediaBrowser.MediaEncoding/Attachments/AttachmentExtractor.cs +++ b/MediaBrowser.MediaEncoding/Attachments/AttachmentExtractor.cs @@ -100,22 +100,10 @@ namespace MediaBrowser.MediaEncoding.Attachments MediaSourceInfo mediaSource, CancellationToken cancellationToken) { - var shouldExtractOneByOne = mediaSource.MediaAttachments.Any(a => !string.IsNullOrEmpty(a.FileName) - && !string.Equals(PathHelper.GetSafeLeafFileName(a.FileName), a.FileName, StringComparison.Ordinal)); - if (shouldExtractOneByOne && !inputFile.EndsWith(".mks", StringComparison.OrdinalIgnoreCase)) - { - await ExtractAllAttachmentsIndividuallyInternal( - inputFile, - mediaSource, - cancellationToken).ConfigureAwait(false); - } - else - { - await ExtractAllAttachmentsInternal( - inputFile, - mediaSource, - cancellationToken).ConfigureAwait(false); - } + await ExtractAllAttachmentsIndividuallyInternal( + inputFile, + mediaSource, + cancellationToken).ConfigureAwait(false); } private async Task ExtractAllAttachmentsIndividuallyInternal( @@ -252,117 +240,6 @@ namespace MediaBrowser.MediaEncoding.Attachments } } - private async Task ExtractAllAttachmentsInternal( - string inputFile, - MediaSourceInfo mediaSource, - CancellationToken cancellationToken) - { - var inputPath = _mediaEncoder.GetInputArgument(inputFile, mediaSource); - - ArgumentException.ThrowIfNullOrEmpty(inputPath); - - var outputFolder = _pathManager.GetAttachmentFolderPath(mediaSource.Id); - if (outputFolder is null) - { - _logger.LogDebug("Skipping attachment extraction for input {InputFile}: MediaSource Id is not a GUID.", inputFile); - return; - } - - using (await _semaphoreLocks.LockAsync(outputFolder, cancellationToken).ConfigureAwait(false)) - { - var directory = Directory.CreateDirectory(outputFolder); - var fileNames = directory.GetFiles("*", SearchOption.TopDirectoryOnly).Select(f => f.Name).ToHashSet(); - var missingFiles = mediaSource.MediaAttachments.Where(a => a.FileName is not null && !fileNames.Contains(a.FileName) && !string.Equals(a.Codec, "mjpeg", StringComparison.OrdinalIgnoreCase)); - if (!missingFiles.Any()) - { - // Skip extraction if all files already exist - return; - } - - // Files without video/audio streams (e.g. MKS subtitle files) don't need a dummy - // output since there are no streams to process. Omit "-t 0 -f null null" so ffmpeg - // doesn't fail trying to open an output with no streams. It will exit with code 1 - // ("at least one output file must be specified") which is expected and harmless - // since we only need the -dump_attachment side effect. - var hasVideoOrAudioStream = mediaSource.MediaStreams - .Any(s => s.Type == MediaStreamType.Video || s.Type == MediaStreamType.Audio); - var processArgs = string.Format( - CultureInfo.InvariantCulture, - "-dump_attachment:t \"\" -y {0} -i {1} {2}", - inputPath.EndsWith(".concat\"", StringComparison.OrdinalIgnoreCase) ? "-f concat -safe 0" : string.Empty, - inputPath, - hasVideoOrAudioStream ? "-t 0 -f null null" : string.Empty); - - int exitCode; - - using (var process = new Process - { - StartInfo = new ProcessStartInfo - { - Arguments = processArgs, - FileName = _mediaEncoder.EncoderPath, - UseShellExecute = false, - CreateNoWindow = true, - WindowStyle = ProcessWindowStyle.Hidden, - WorkingDirectory = outputFolder, - ErrorDialog = false - }, - EnableRaisingEvents = true - }) - { - _logger.LogInformation("{File} {Arguments}", process.StartInfo.FileName, process.StartInfo.Arguments); - - process.Start(); - - try - { - await process.WaitForExitAsync(cancellationToken).ConfigureAwait(false); - exitCode = process.ExitCode; - } - catch (OperationCanceledException) - { - process.Kill(true); - exitCode = -1; - } - } - - var failed = false; - - if (exitCode != 0) - { - if (hasVideoOrAudioStream || exitCode != 1) - { - failed = true; - - _logger.LogWarning("Deleting extracted attachments {Path} due to failure: {ExitCode}", outputFolder, exitCode); - try - { - Directory.Delete(outputFolder); - } - catch (IOException ex) - { - _logger.LogError(ex, "Error deleting extracted attachments {Path}", outputFolder); - } - } - } - - if (!failed && !Directory.Exists(outputFolder)) - { - failed = true; - } - - if (failed) - { - _logger.LogError("ffmpeg attachment extraction failed for {InputPath} to {OutputPath}", inputPath, outputFolder); - - throw new InvalidOperationException( - string.Format(CultureInfo.InvariantCulture, "ffmpeg attachment extraction failed for {0} to {1}", inputPath, outputFolder)); - } - - _logger.LogInformation("ffmpeg attachment extraction completed for {InputPath} to {OutputPath}", inputPath, outputFolder); - } - } - private async Task<Stream> GetAttachmentStream( MediaSourceInfo mediaSource, MediaAttachment mediaAttachment, diff --git a/MediaBrowser.MediaEncoding/Probing/ProbeResultNormalizer.cs b/MediaBrowser.MediaEncoding/Probing/ProbeResultNormalizer.cs index c9d618c84a..6cf4d22581 100644 --- a/MediaBrowser.MediaEncoding/Probing/ProbeResultNormalizer.cs +++ b/MediaBrowser.MediaEncoding/Probing/ProbeResultNormalizer.cs @@ -170,8 +170,10 @@ namespace MediaBrowser.MediaEncoding.Probing FFProbeHelpers.GetDictionaryDateTime(tags, "retail date") ?? FFProbeHelpers.GetDictionaryDateTime(tags, "retail_date") ?? FFProbeHelpers.GetDictionaryDateTime(tags, "date_released") ?? - FFProbeHelpers.GetDictionaryDateTime(tags, "date") ?? - FFProbeHelpers.GetDictionaryDateTime(tags, "creation_time"); + FFProbeHelpers.GetDictionaryDateTime(tags, "date"); + + // creation_time is when the file was written, not a release date + info.ContainerCreationDate = FFProbeHelpers.GetDictionaryDateTime(tags, "creation_time"); // Set common metadata for music (audio) and music videos (video) info.Album = tags.GetValueOrDefault("album"); diff --git a/MediaBrowser.MediaEncoding/Subtitles/SubtitleEncoder.cs b/MediaBrowser.MediaEncoding/Subtitles/SubtitleEncoder.cs index 27a987fefe..58129da0ca 100644 --- a/MediaBrowser.MediaEncoding/Subtitles/SubtitleEncoder.cs +++ b/MediaBrowser.MediaEncoding/Subtitles/SubtitleEncoder.cs @@ -8,6 +8,7 @@ using System.Globalization; using System.IO; using System.Linq; using System.Net.Http; +using System.Security.Cryptography; using System.Text; using System.Threading; using System.Threading.Tasks; @@ -222,6 +223,12 @@ namespace MediaBrowser.MediaEncoding.Subtitles var outputPath = GetSubtitleCachePath(mediaSource, subtitleStream.Index, "." + outputFileExtension) ?? throw new ResourceNotFoundException($"MediaSource {mediaSource.Id} has no subtitle cache (non-GUID Id, e.g. Live TV stream)."); + // Failed batch extraction can leave stale cache files behind. + if (!IsCachedSubtitleFresh(outputPath, mediaSource, subtitleStream)) + { + throw new ResourceNotFoundException($"Subtitle extraction did not produce a current cache for stream {subtitleStream.Index} of MediaSource {mediaSource.Id}."); + } + return new SubtitleInfo() { Path = outputPath, @@ -342,7 +349,7 @@ namespace MediaBrowser.MediaEncoding.Subtitles { using (await _semaphoreLocks.LockAsync(outputPath, cancellationToken).ConfigureAwait(false)) { - if (!IsCachedSubtitleFresh(outputPath, subtitleStream.Path)) + if (!IsCachedSubtitleFresh(outputPath, mediaSource, subtitleStream)) { await ConvertTextSubtitleToSrtInternal(subtitleStream, mediaSource, outputPath, cancellationToken).ConfigureAwait(false); } @@ -360,13 +367,25 @@ namespace MediaBrowser.MediaEncoding.Subtitles }; } - // Records "this cache was built from this exact source revision" in a sidecar file next to the cache: "<sizeBytes>:<mtimeTicks>" private static string GetCacheMetaPath(string cachePath) => cachePath + ".meta"; - private static string FormatCacheMeta(long length, DateTime lastWriteUtc) - => string.Create(CultureInfo.InvariantCulture, $"{length}:{lastWriteUtc.Ticks}"); + private string FormatCacheMeta(MediaSourceInfo mediaSource, MediaStream subtitleStream) + { + var sourcePath = string.IsNullOrEmpty(subtitleStream.Path) ? mediaSource.Path : subtitleStream.Path; + // Identify the source track independently of its public stream index. + var streamIndex = EncodingHelper.GetSubtitleStreamIndexForFfmpeg(mediaSource, subtitleStream); + var sourceId = Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(sourcePath ?? string.Empty))); + var revision = string.Empty; + if (File.Exists(sourcePath)) + { + var sourceInfo = _fileSystem.GetFileInfo(sourcePath); + revision = string.Create(CultureInfo.InvariantCulture, $"{sourceInfo.Length}:{sourceInfo.LastWriteTimeUtc.Ticks}"); + } - private bool IsCachedSubtitleFresh(string cachePath, string? sourcePath) + return string.Create(CultureInfo.InvariantCulture, $"v2:{streamIndex}:{revision}:{sourceId}"); + } + + internal bool IsCachedSubtitleFresh(string cachePath, MediaSourceInfo mediaSource, MediaStream subtitleStream) { if (!File.Exists(cachePath)) { @@ -379,11 +398,6 @@ namespace MediaBrowser.MediaEncoding.Subtitles return false; } - if (string.IsNullOrEmpty(sourcePath) || !File.Exists(sourcePath)) - { - return true; - } - var metaPath = GetCacheMetaPath(cachePath); if (!File.Exists(metaPath)) { @@ -393,8 +407,7 @@ namespace MediaBrowser.MediaEncoding.Subtitles try { - var sourceInfo = _fileSystem.GetFileInfo(sourcePath); - var expected = FormatCacheMeta(sourceInfo.Length, sourceInfo.LastWriteTimeUtc); + var expected = FormatCacheMeta(mediaSource, subtitleStream); var actual = File.ReadAllText(metaPath); return string.Equals(expected, actual, StringComparison.Ordinal); } @@ -404,22 +417,11 @@ namespace MediaBrowser.MediaEncoding.Subtitles } } - private void WriteCacheMeta(string cachePath, string? sourcePath) + internal void WriteCacheMeta(string cachePath, MediaSourceInfo mediaSource, MediaStream subtitleStream) { - if (string.IsNullOrEmpty(sourcePath)) - { - return; - } - try { - var sourceInfo = _fileSystem.GetFileInfo(sourcePath); - if (!sourceInfo.Exists) - { - return; - } - - File.WriteAllText(GetCacheMetaPath(cachePath), FormatCacheMeta(sourceInfo.Length, sourceInfo.LastWriteTimeUtc)); + File.WriteAllText(GetCacheMetaPath(cachePath), FormatCacheMeta(mediaSource, subtitleStream)); } catch (IOException ex) { @@ -470,7 +472,7 @@ namespace MediaBrowser.MediaEncoding.Subtitles [outputPath], cancellationToken).ConfigureAwait(false); - WriteCacheMeta(outputPath, inputPath); + WriteCacheMeta(outputPath, mediaSource, subtitleStream); } private string GetExtractableSubtitleFormat(MediaStream subtitleStream) @@ -546,8 +548,7 @@ namespace MediaBrowser.MediaEncoding.Subtitles var releaser = await _semaphoreLocks.LockAsync(outputPath, cancellationToken).ConfigureAwait(false); - var sourcePath = string.IsNullOrEmpty(subtitleStream.Path) ? mediaSource.Path : subtitleStream.Path; - if (IsCachedSubtitleFresh(outputPath, sourcePath)) + if (IsCachedSubtitleFresh(outputPath, mediaSource, subtitleStream)) { releaser.Dispose(); continue; @@ -601,7 +602,7 @@ namespace MediaBrowser.MediaEncoding.Subtitles foreach (string mksFile in mksFiles) { var inputPath = _mediaEncoder.GetInputArgument(mksFile, mediaSource); - var outputPaths = new List<string>(); + var outputStreams = new Dictionary<string, MediaStream>(); var args = string.Format( CultureInfo.InvariantCulture, "-y -i {0}", @@ -633,7 +634,7 @@ namespace MediaBrowser.MediaEncoding.Subtitles Directory.CreateDirectory(Path.GetDirectoryName(outputPath) ?? throw new FileNotFoundException($"Calculated path ({outputPath}) is not valid.")); - outputPaths.Add(outputPath); + outputStreams.Add(outputPath, subtitleStream); args += string.Format( CultureInfo.InvariantCulture, " -map 0:{0} -an -vn -c:s {1}{2} -flush_packets 1 \"{3}\"", @@ -643,11 +644,11 @@ namespace MediaBrowser.MediaEncoding.Subtitles outputPath.EscapeProcessArgument()); } - await ExtractSubtitlesForFile(inputPath, args, outputPaths, cancellationToken).ConfigureAwait(false); + await ExtractSubtitlesForFile(inputPath, args, outputStreams.Keys.ToArray(), cancellationToken).ConfigureAwait(false); - foreach (var outputPath in outputPaths) + foreach (var (outputPath, subtitleStream) in outputStreams) { - WriteCacheMeta(outputPath, mksFile); + WriteCacheMeta(outputPath, mediaSource, subtitleStream); } } } @@ -658,7 +659,7 @@ namespace MediaBrowser.MediaEncoding.Subtitles CancellationToken cancellationToken) { var inputPath = _mediaEncoder.GetInputPathArgument(mediaSource.Path, mediaSource); - var outputPaths = new List<string>(); + var outputStreams = new Dictionary<string, MediaStream>(); var args = string.Format( CultureInfo.InvariantCulture, "-y -i {0}", @@ -691,7 +692,7 @@ namespace MediaBrowser.MediaEncoding.Subtitles Directory.CreateDirectory(Path.GetDirectoryName(outputPath) ?? throw new FileNotFoundException($"Calculated path ({outputPath}) is not valid.")); - outputPaths.Add(outputPath); + outputStreams.Add(outputPath, subtitleStream); args += string.Format( CultureInfo.InvariantCulture, " -map 0:{0} -an -vn -c:s {1}{2} -flush_packets 1 \"{3}\"", @@ -701,13 +702,13 @@ namespace MediaBrowser.MediaEncoding.Subtitles outputPath.EscapeProcessArgument()); } - if (outputPaths.Count > 0) + if (outputStreams.Count > 0) { - await ExtractSubtitlesForFile(inputPath, args, outputPaths, cancellationToken).ConfigureAwait(false); + await ExtractSubtitlesForFile(inputPath, args, outputStreams.Keys.ToArray(), cancellationToken).ConfigureAwait(false); - foreach (var outputPath in outputPaths) + foreach (var (outputPath, subtitleStream) in outputStreams) { - WriteCacheMeta(outputPath, mediaSource.Path); + WriteCacheMeta(outputPath, mediaSource, subtitleStream); } } } @@ -722,7 +723,7 @@ namespace MediaBrowser.MediaEncoding.Subtitles var failed = false; - if (exitCode == -1) + if (exitCode != 0) { failed = true; @@ -809,7 +810,7 @@ namespace MediaBrowser.MediaEncoding.Subtitles { using (await _semaphoreLocks.LockAsync(outputPath, cancellationToken).ConfigureAwait(false)) { - if (!File.Exists(outputPath) || _fileSystem.GetFileInfo(outputPath).Length == 0) + if (!IsCachedSubtitleFresh(outputPath, mediaSource, subtitleStream)) { var subtitleStreamIndex = EncodingHelper.FindIndex(mediaSource.MediaStreams, subtitleStream); @@ -826,6 +827,8 @@ namespace MediaBrowser.MediaEncoding.Subtitles outputCodec, outputPath, cancellationToken).ConfigureAwait(false); + + WriteCacheMeta(outputPath, mediaSource, subtitleStream); } } } |
