From 891b9f7a997ce5e5892c1b0f166a921ff07abf68 Mon Sep 17 00:00:00 2001
From: AmbulantRex <21176662+AmbulantRex@users.noreply.github.com>
Date: Thu, 30 Mar 2023 08:59:21 -0600
Subject: [PATCH 01/21] Add DLL whitelist support for plugins
---
.../Library/PathExtensions.cs | 99 ++++++++++---
.../Plugins/PluginManager.cs | 83 ++++++++++-
MediaBrowser.Common/Plugins/PluginManifest.cs | 9 ++
MediaBrowser.Model/Updates/VersionInfo.cs | 8 ++
.../Library/PathExtensionsTests.cs | 43 ++++++
.../Plugins/PluginManagerTests.cs | 135 ++++++++++++++++++
.../Test Data/Updates/manifest-stable.json | 10 +-
.../Updates/InstallationManagerTests.cs | 14 ++
8 files changed, 375 insertions(+), 26 deletions(-)
diff --git a/Emby.Server.Implementations/Library/PathExtensions.cs b/Emby.Server.Implementations/Library/PathExtensions.cs
index 64e7d54466..7e0d0b78d5 100644
--- a/Emby.Server.Implementations/Library/PathExtensions.cs
+++ b/Emby.Server.Implementations/Library/PathExtensions.cs
@@ -1,6 +1,9 @@
using System;
using System.Diagnostics.CodeAnalysis;
+using System.IO;
+using System.Linq;
using MediaBrowser.Common.Providers;
+using Nikse.SubtitleEdit.Core.Common;
namespace Emby.Server.Implementations.Library
{
@@ -86,24 +89,8 @@ namespace Emby.Server.Implementations.Library
return false;
}
- char oldDirectorySeparatorChar;
- char newDirectorySeparatorChar;
- // True normalization is still not possible https://github.com/dotnet/runtime/issues/2162
- // The reasoning behind this is that a forward slash likely means it's a Linux path and
- // so the whole path should be normalized to use / and vice versa for Windows (although Windows doesn't care much).
- if (newSubPath.Contains('/', StringComparison.Ordinal))
- {
- oldDirectorySeparatorChar = '\\';
- newDirectorySeparatorChar = '/';
- }
- else
- {
- oldDirectorySeparatorChar = '/';
- newDirectorySeparatorChar = '\\';
- }
-
- path = path.Replace(oldDirectorySeparatorChar, newDirectorySeparatorChar);
- subPath = subPath.Replace(oldDirectorySeparatorChar, newDirectorySeparatorChar);
+ subPath = subPath.NormalizePath(out var newDirectorySeparatorChar)!;
+ path = path.NormalizePath(newDirectorySeparatorChar)!;
// We have to ensure that the sub path ends with a directory separator otherwise we'll get weird results
// when the sub path matches a similar but in-complete subpath
@@ -120,12 +107,86 @@ namespace Emby.Server.Implementations.Library
return false;
}
- var newSubPathTrimmed = newSubPath.AsSpan().TrimEnd(newDirectorySeparatorChar);
+ var newSubPathTrimmed = newSubPath.AsSpan().TrimEnd((char)newDirectorySeparatorChar!);
// Ensure that the path with the old subpath removed starts with a leading dir separator
int idx = oldSubPathEndsWithSeparator ? subPath.Length - 1 : subPath.Length;
newPath = string.Concat(newSubPathTrimmed, path.AsSpan(idx));
return true;
}
+
+ ///
+ /// Retrieves the full resolved path and normalizes path separators to the .
+ ///
+ /// The path to canonicalize.
+ /// The fully expanded, normalized path.
+ public static string Canonicalize(this string path)
+ {
+ return Path.GetFullPath(path).NormalizePath()!;
+ }
+
+ ///
+ /// Normalizes the path's directory separator character to the currently defined .
+ ///
+ /// The path to normalize.
+ /// The normalized path string or if the input path is null or empty.
+ public static string? NormalizePath(this string? path)
+ {
+ return path.NormalizePath(Path.DirectorySeparatorChar);
+ }
+
+ ///
+ /// Normalizes the path's directory separator character.
+ ///
+ /// The path to normalize.
+ /// The separator character the path now uses or .
+ /// The normalized path string or if the input path is null or empty.
+ public static string? NormalizePath(this string? path, out char separator)
+ {
+ if (string.IsNullOrEmpty(path))
+ {
+ separator = default;
+ return path;
+ }
+
+ var newSeparator = '\\';
+
+ // True normalization is still not possible https://github.com/dotnet/runtime/issues/2162
+ // The reasoning behind this is that a forward slash likely means it's a Linux path and
+ // so the whole path should be normalized to use / and vice versa for Windows (although Windows doesn't care much).
+ if (path.Contains('/', StringComparison.Ordinal))
+ {
+ newSeparator = '/';
+ }
+
+ separator = newSeparator;
+
+ return path?.NormalizePath(newSeparator);
+ }
+
+ ///
+ /// Normalizes the path's directory separator character to the specified character.
+ ///
+ /// The path to normalize.
+ /// The replacement directory separator character. Must be a valid directory separator.
+ /// The normalized path.
+ /// Thrown if the new separator character is not a directory separator.
+ public static string? NormalizePath(this string? path, char newSeparator)
+ {
+ const char Bs = '\\';
+ const char Fs = '/';
+
+ if (!(newSeparator == Bs || newSeparator == Fs))
+ {
+ throw new ArgumentException("The character must be a directory separator.");
+ }
+
+ if (string.IsNullOrEmpty(path))
+ {
+ return path;
+ }
+
+ return newSeparator == Bs ? path?.Replace(Fs, newSeparator) : path?.Replace(Bs, newSeparator);
+ }
}
}
diff --git a/Emby.Server.Implementations/Plugins/PluginManager.cs b/Emby.Server.Implementations/Plugins/PluginManager.cs
index 7c23254a12..a5c55c8a09 100644
--- a/Emby.Server.Implementations/Plugins/PluginManager.cs
+++ b/Emby.Server.Implementations/Plugins/PluginManager.cs
@@ -1,5 +1,6 @@
using System;
using System.Collections.Generic;
+using System.Data;
using System.Globalization;
using System.IO;
using System.Linq;
@@ -9,6 +10,8 @@ using System.Runtime.Loader;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
+using Emby.Server.Implementations.Library;
+using Jellyfin.Extensions;
using Jellyfin.Extensions.Json;
using Jellyfin.Extensions.Json.Converters;
using MediaBrowser.Common;
@@ -19,8 +22,11 @@ using MediaBrowser.Model.Configuration;
using MediaBrowser.Model.IO;
using MediaBrowser.Model.Plugins;
using MediaBrowser.Model.Updates;
+using Microsoft.AspNetCore.Mvc.ApplicationParts;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
+using Nikse.SubtitleEdit.Core.Common;
+using SQLitePCL.pretty;
namespace Emby.Server.Implementations.Plugins
{
@@ -44,7 +50,7 @@ namespace Emby.Server.Implementations.Plugins
///
/// Initializes a new instance of the class.
///
- /// The .
+ /// The .
/// The .
/// The .
/// The plugin path.
@@ -424,7 +430,8 @@ namespace Emby.Server.Implementations.Plugins
Version = versionInfo.Version,
Status = status == PluginStatus.Disabled ? PluginStatus.Disabled : PluginStatus.Active, // Keep disabled state.
AutoUpdate = true,
- ImagePath = imagePath
+ ImagePath = imagePath,
+ Assemblies = versionInfo.Assemblies
};
return SaveManifest(manifest, path);
@@ -688,7 +695,15 @@ namespace Emby.Server.Implementations.Plugins
var entry = versions[x];
if (!string.Equals(lastName, entry.Name, StringComparison.OrdinalIgnoreCase))
{
- entry.DllFiles = Directory.GetFiles(entry.Path, "*.dll", SearchOption.AllDirectories);
+ if (!TryGetPluginDlls(entry, out var allowedDlls))
+ {
+ _logger.LogError("One or more assembly paths was invalid. Marking plugin {Plugin} as \"Malfunctioned\".", entry.Name);
+ ChangePluginState(entry, PluginStatus.Malfunctioned);
+ continue;
+ }
+
+ entry.DllFiles = allowedDlls;
+
if (entry.IsEnabledAndSupported)
{
lastName = entry.Name;
@@ -734,6 +749,68 @@ namespace Emby.Server.Implementations.Plugins
return versions.Where(p => p.DllFiles.Count != 0);
}
+ ///
+ /// Attempts to retrieve valid DLLs from the plugin path. This method will consider the assembly whitelist
+ /// from the manifest.
+ ///
+ ///
+ /// Loading DLLs from externally supplied paths introduces a path traversal risk. This method
+ /// uses a safelisting tactic of considering DLLs from the plugin directory and only using
+ /// the plugin's canonicalized assembly whitelist for comparison. See
+ /// for more details.
+ ///
+ /// The plugin.
+ /// The whitelisted DLLs. If the method returns , this will be empty.
+ ///
+ /// if all assemblies listed in the manifest were available in the plugin directory.
+ /// if any assemblies were invalid or missing from the plugin directory.
+ ///
+ /// If the is null.
+ private bool TryGetPluginDlls(LocalPlugin plugin, out IReadOnlyList whitelistedDlls)
+ {
+ _ = plugin ?? throw new ArgumentNullException(nameof(plugin));
+
+ IReadOnlyList pluginDlls = Directory.GetFiles(plugin.Path, "*.dll", SearchOption.AllDirectories);
+
+ whitelistedDlls = Array.Empty();
+ if (pluginDlls.Count > 0 && plugin.Manifest.Assemblies.Count > 0)
+ {
+ _logger.LogInformation("Registering whitelisted assemblies for plugin \"{Plugin}\"...", plugin.Name);
+
+ var canonicalizedPaths = new List();
+ foreach (var path in plugin.Manifest.Assemblies)
+ {
+ var canonicalized = Path.Combine(plugin.Path, path).Canonicalize();
+
+ // Ensure we stay in the plugin directory.
+ if (!canonicalized.StartsWith(plugin.Path.NormalizePath()!, StringComparison.Ordinal))
+ {
+ _logger.LogError("Assembly path {Path} is not inside the plugin directory.", path);
+ return false;
+ }
+
+ canonicalizedPaths.Add(canonicalized);
+ }
+
+ var intersected = pluginDlls.Intersect(canonicalizedPaths).ToList();
+
+ if (intersected.Count != canonicalizedPaths.Count)
+ {
+ _logger.LogError("Plugin {Plugin} contained assembly paths that were not found in the directory.", plugin.Name);
+ return false;
+ }
+
+ whitelistedDlls = intersected;
+ }
+ else
+ {
+ // No whitelist, default to loading all DLLs in plugin directory.
+ whitelistedDlls = pluginDlls;
+ }
+
+ return true;
+ }
+
///
/// Changes the status of the other versions of the plugin to "Superceded".
///
diff --git a/MediaBrowser.Common/Plugins/PluginManifest.cs b/MediaBrowser.Common/Plugins/PluginManifest.cs
index 2910dbe144..2bad3454d1 100644
--- a/MediaBrowser.Common/Plugins/PluginManifest.cs
+++ b/MediaBrowser.Common/Plugins/PluginManifest.cs
@@ -1,4 +1,5 @@
using System;
+using System.Collections.Generic;
using System.Text.Json.Serialization;
using MediaBrowser.Model.Plugins;
@@ -23,6 +24,7 @@ namespace MediaBrowser.Common.Plugins
Overview = string.Empty;
TargetAbi = string.Empty;
Version = string.Empty;
+ Assemblies = new List();
}
///
@@ -104,5 +106,12 @@ namespace MediaBrowser.Common.Plugins
///
[JsonPropertyName("imagePath")]
public string? ImagePath { get; set; }
+
+ ///
+ /// Gets or sets the collection of assemblies that should be loaded.
+ /// Paths are considered relative to the plugin folder.
+ ///
+ [JsonPropertyName("assemblies")]
+ public IList Assemblies { get; set; }
}
}
diff --git a/MediaBrowser.Model/Updates/VersionInfo.cs b/MediaBrowser.Model/Updates/VersionInfo.cs
index 320199f984..1e24bde84e 100644
--- a/MediaBrowser.Model/Updates/VersionInfo.cs
+++ b/MediaBrowser.Model/Updates/VersionInfo.cs
@@ -1,3 +1,5 @@
+using System;
+using System.Collections.Generic;
using System.Text.Json.Serialization;
using SysVersion = System.Version;
@@ -73,5 +75,11 @@ namespace MediaBrowser.Model.Updates
///
[JsonPropertyName("repositoryUrl")]
public string RepositoryUrl { get; set; } = string.Empty;
+
+ ///
+ /// Gets or sets the assemblies whitelist for this version.
+ ///
+ [JsonPropertyName("assemblies")]
+ public IList Assemblies { get; set; } = Array.Empty();
}
}
diff --git a/tests/Jellyfin.Server.Implementations.Tests/Library/PathExtensionsTests.cs b/tests/Jellyfin.Server.Implementations.Tests/Library/PathExtensionsTests.cs
index be2dfe0a86..c33a957e69 100644
--- a/tests/Jellyfin.Server.Implementations.Tests/Library/PathExtensionsTests.cs
+++ b/tests/Jellyfin.Server.Implementations.Tests/Library/PathExtensionsTests.cs
@@ -1,4 +1,5 @@
using System;
+using System.IO;
using Emby.Server.Implementations.Library;
using Xunit;
@@ -73,5 +74,47 @@ namespace Jellyfin.Server.Implementations.Tests.Library
Assert.False(PathExtensions.TryReplaceSubPath(path, subPath, newSubPath, out var result));
Assert.Null(result);
}
+
+ [Theory]
+ [InlineData(null, '/', null)]
+ [InlineData(null, '\\', null)]
+ [InlineData("/home/jeff/myfile.mkv", '\\', "\\home\\jeff\\myfile.mkv")]
+ [InlineData("C:\\Users\\Jeff\\myfile.mkv", '/', "C:/Users/Jeff/myfile.mkv")]
+ [InlineData("\\home/jeff\\myfile.mkv", '\\', "\\home\\jeff\\myfile.mkv")]
+ [InlineData("\\home/jeff\\myfile.mkv", '/', "/home/jeff/myfile.mkv")]
+ [InlineData("", '/', "")]
+ public void NormalizePath_SpecifyingSeparator_Normalizes(string path, char separator, string expectedPath)
+ {
+ Assert.Equal(expectedPath, path.NormalizePath(separator));
+ }
+
+ [Theory]
+ [InlineData("/home/jeff/myfile.mkv")]
+ [InlineData("C:\\Users\\Jeff\\myfile.mkv")]
+ [InlineData("\\home/jeff\\myfile.mkv")]
+ public void NormalizePath_NoArgs_UsesDirectorySeparatorChar(string path)
+ {
+ var separator = Path.DirectorySeparatorChar;
+
+ Assert.Equal(path.Replace('\\', separator).Replace('/', separator), path.NormalizePath());
+ }
+
+ [Theory]
+ [InlineData("/home/jeff/myfile.mkv", '/')]
+ [InlineData("C:\\Users\\Jeff\\myfile.mkv", '\\')]
+ [InlineData("\\home/jeff\\myfile.mkv", '/')]
+ public void NormalizePath_OutVar_Correct(string path, char expectedSeparator)
+ {
+ var result = path.NormalizePath(out var separator);
+
+ Assert.Equal(expectedSeparator, separator);
+ Assert.Equal(path.Replace('\\', separator).Replace('/', separator), result);
+ }
+
+ [Fact]
+ public void NormalizePath_SpecifyInvalidSeparator_ThrowsException()
+ {
+ Assert.Throws(() => string.Empty.NormalizePath('a'));
+ }
}
}
diff --git a/tests/Jellyfin.Server.Implementations.Tests/Plugins/PluginManagerTests.cs b/tests/Jellyfin.Server.Implementations.Tests/Plugins/PluginManagerTests.cs
index bc6a447410..d9fdc96f55 100644
--- a/tests/Jellyfin.Server.Implementations.Tests/Plugins/PluginManagerTests.cs
+++ b/tests/Jellyfin.Server.Implementations.Tests/Plugins/PluginManagerTests.cs
@@ -1,7 +1,12 @@
using System;
using System.IO;
+using System.Text.Json;
+using Emby.Server.Implementations.Library;
using Emby.Server.Implementations.Plugins;
+using Jellyfin.Extensions.Json;
+using Jellyfin.Extensions.Json.Converters;
using MediaBrowser.Common.Plugins;
+using MediaBrowser.Model.Plugins;
using Microsoft.Extensions.Logging.Abstractions;
using Xunit;
@@ -40,6 +45,136 @@ namespace Jellyfin.Server.Implementations.Tests.Plugins
Assert.Equal(manifest.Status, res.Manifest.Status);
Assert.Equal(manifest.AutoUpdate, res.Manifest.AutoUpdate);
Assert.Equal(manifest.ImagePath, res.Manifest.ImagePath);
+ Assert.Equal(manifest.Assemblies, res.Manifest.Assemblies);
+ }
+
+ ///
+ /// Tests safe traversal within the plugin directory.
+ ///
+ /// The safe path to evaluate.
+ [Theory]
+ [InlineData("./some.dll")]
+ [InlineData("some.dll")]
+ [InlineData("sub/path/some.dll")]
+ public void Constructor_DiscoversSafePluginAssembly_Status_Active(string dllFile)
+ {
+ var manifest = new PluginManifest
+ {
+ Id = Guid.NewGuid(),
+ Name = "Safe Assembly",
+ Assemblies = new string[] { dllFile }
+ };
+
+ var filename = Path.GetFileName(dllFile)!;
+ var (tempPath, pluginPath) = GetTestPaths("safe");
+
+ Directory.CreateDirectory(Path.Combine(pluginPath, dllFile.Replace(filename, string.Empty, StringComparison.OrdinalIgnoreCase)));
+ File.Create(Path.Combine(pluginPath, dllFile));
+
+ var options = GetTestSerializerOptions();
+ var data = JsonSerializer.Serialize(manifest, options);
+ var metafilePath = Path.Combine(tempPath, "safe", "meta.json");
+
+ File.WriteAllText(metafilePath, data);
+
+ var pluginManager = new PluginManager(new NullLogger(), null!, null!, tempPath, new Version(1, 0));
+
+ var res = JsonSerializer.Deserialize(File.ReadAllText(metafilePath), options);
+
+ var expectedFullPath = Path.Combine(pluginPath, dllFile).Canonicalize();
+
+ Assert.NotNull(res);
+ Assert.NotEmpty(pluginManager.Plugins);
+ Assert.Equal(PluginStatus.Active, res!.Status);
+ Assert.Equal(expectedFullPath, pluginManager.Plugins[0].DllFiles[0]);
+ Assert.StartsWith(Path.Combine(tempPath, "safe"), expectedFullPath, StringComparison.InvariantCulture);
+ }
+
+ ///
+ /// Tests unsafe attempts to traverse to higher directories.
+ ///
+ ///
+ /// Attempts to load directories outside of the plugin should be
+ /// constrained. Path traversal, shell expansion, and double encoding
+ /// can be used to load unintended files.
+ /// See for more.
+ ///
+ /// The unsafe path to evaluate.
+ [Theory]
+ [InlineData("/some.dll")] // Root path.
+ [InlineData("../some.dll")] // Simple traversal.
+ [InlineData("C:\\some.dll")] // Windows root path.
+ [InlineData("test.txt")] // Not a DLL
+ [InlineData(".././.././../some.dll")] // Traversal with current and parent
+ [InlineData("..\\.\\..\\.\\..\\some.dll")] // Windows traversal with current and parent
+ [InlineData("\\\\network\\resource.dll")] // UNC Path
+ [InlineData("https://jellyfin.org/some.dll")] // URL
+ [InlineData("....//....//some.dll")] // Path replacement risk if a single "../" replacement occurs.
+ [InlineData("~/some.dll")] // Tilde poses a shell expansion risk, but is a valid path character.
+ public void Constructor_DiscoversUnsafePluginAssembly_Status_Malfunctioned(string unsafePath)
+ {
+ var manifest = new PluginManifest
+ {
+ Id = Guid.NewGuid(),
+ Name = "Unsafe Assembly",
+ Assemblies = new string[] { unsafePath }
+ };
+
+ var (tempPath, pluginPath) = GetTestPaths("unsafe");
+
+ Directory.CreateDirectory(pluginPath);
+
+ var files = new string[]
+ {
+ "../other.dll",
+ "some.dll"
+ };
+
+ foreach (var file in files)
+ {
+ File.Create(Path.Combine(pluginPath, file));
+ }
+
+ var options = GetTestSerializerOptions();
+ var data = JsonSerializer.Serialize(manifest, options);
+ var metafilePath = Path.Combine(tempPath, "unsafe", "meta.json");
+
+ File.WriteAllText(metafilePath, data);
+
+ var pluginManager = new PluginManager(new NullLogger(), null!, null!, tempPath, new Version(1, 0));
+
+ var res = JsonSerializer.Deserialize(File.ReadAllText(metafilePath), options);
+
+ Assert.NotNull(res);
+ Assert.Empty(pluginManager.Plugins);
+ Assert.Equal(PluginStatus.Malfunctioned, res!.Status);
+ }
+
+ private JsonSerializerOptions GetTestSerializerOptions()
+ {
+ var options = new JsonSerializerOptions(JsonDefaults.Options)
+ {
+ WriteIndented = true
+ };
+
+ for (var i = 0; i < options.Converters.Count; i++)
+ {
+ // Remove the Guid converter for parity with plugin manager.
+ if (options.Converters[i] is JsonGuidConverter converter)
+ {
+ options.Converters.Remove(converter);
+ }
+ }
+
+ return options;
+ }
+
+ private (string TempPath, string PluginPath) GetTestPaths(string pluginFolderName)
+ {
+ var tempPath = Path.Combine(_testPathRoot, "plugins-" + Path.GetRandomFileName());
+ var pluginPath = Path.Combine(tempPath, pluginFolderName);
+
+ return (tempPath, pluginPath);
}
}
}
diff --git a/tests/Jellyfin.Server.Implementations.Tests/Test Data/Updates/manifest-stable.json b/tests/Jellyfin.Server.Implementations.Tests/Test Data/Updates/manifest-stable.json
index fa8fbd8d2c..d69a52d6d0 100644
--- a/tests/Jellyfin.Server.Implementations.Tests/Test Data/Updates/manifest-stable.json
+++ b/tests/Jellyfin.Server.Implementations.Tests/Test Data/Updates/manifest-stable.json
@@ -13,7 +13,8 @@
"targetAbi": "10.6.0.0",
"sourceUrl": "https://repo.jellyfin.org/releases/plugin/anime/anime_10.0.0.0.zip",
"checksum": "93e969adeba1050423fc8817ed3c36f8",
- "timestamp": "2020-08-17T01:41:13Z"
+ "timestamp": "2020-08-17T01:41:13Z",
+ "assemblies": [ "Jellyfin.Plugin.Anime.dll" ]
},
{
"version": "9.0.0.0",
@@ -21,9 +22,10 @@
"targetAbi": "10.6.0.0",
"sourceUrl": "https://repo.jellyfin.org/releases/plugin/anime/anime_9.0.0.0.zip",
"checksum": "9b1cebff835813e15f414f44b40c41c8",
- "timestamp": "2020-07-20T01:30:16Z"
+ "timestamp": "2020-07-20T01:30:16Z",
+ "assemblies": [ "Jellyfin.Plugin.Anime.dll" ]
}
- ]
+ ]
},
{
"guid": "70b7b43b-471b-4159-b4be-56750c795499",
@@ -681,4 +683,4 @@
}
]
}
-]
\ No newline at end of file
+]
diff --git a/tests/Jellyfin.Server.Implementations.Tests/Updates/InstallationManagerTests.cs b/tests/Jellyfin.Server.Implementations.Tests/Updates/InstallationManagerTests.cs
index 7abd2e685f..70d03f8c4a 100644
--- a/tests/Jellyfin.Server.Implementations.Tests/Updates/InstallationManagerTests.cs
+++ b/tests/Jellyfin.Server.Implementations.Tests/Updates/InstallationManagerTests.cs
@@ -106,5 +106,19 @@ namespace Jellyfin.Server.Implementations.Tests.Updates
var ex = await Record.ExceptionAsync(() => _installationManager.InstallPackage(packageInfo, CancellationToken.None)).ConfigureAwait(false);
Assert.Null(ex);
}
+
+ [Fact]
+ public async Task InstallPackage_WithAssemblies_Success()
+ {
+ PackageInfo[] packages = await _installationManager.GetPackages(
+ "Jellyfin Stable",
+ "https://repo.jellyfin.org/releases/plugin/manifest-stable.json",
+ false);
+
+ packages = _installationManager.FilterPackages(packages, "Anime").ToArray();
+ Assert.Single(packages);
+ Assert.NotEmpty(packages[0].Versions[0].Assemblies);
+ Assert.Equal("Jellyfin.Plugin.Anime.dll", packages[0].Versions[0].Assemblies[0]);
+ }
}
}
From 677b1f8e34799d26ffa9ef792aabcc79ad9073ca Mon Sep 17 00:00:00 2001
From: AmbulantRex <21176662+AmbulantRex@users.noreply.github.com>
Date: Thu, 30 Mar 2023 12:56:57 -0600
Subject: [PATCH 02/21] Remove unnecessary using statements in PluginManager
---
Emby.Server.Implementations/Library/PathExtensions.cs | 2 --
Emby.Server.Implementations/Plugins/PluginManager.cs | 3 ---
2 files changed, 5 deletions(-)
diff --git a/Emby.Server.Implementations/Library/PathExtensions.cs b/Emby.Server.Implementations/Library/PathExtensions.cs
index 7e0d0b78d5..a3d748a138 100644
--- a/Emby.Server.Implementations/Library/PathExtensions.cs
+++ b/Emby.Server.Implementations/Library/PathExtensions.cs
@@ -1,9 +1,7 @@
using System;
using System.Diagnostics.CodeAnalysis;
using System.IO;
-using System.Linq;
using MediaBrowser.Common.Providers;
-using Nikse.SubtitleEdit.Core.Common;
namespace Emby.Server.Implementations.Library
{
diff --git a/Emby.Server.Implementations/Plugins/PluginManager.cs b/Emby.Server.Implementations/Plugins/PluginManager.cs
index a5c55c8a09..d253a0ab99 100644
--- a/Emby.Server.Implementations/Plugins/PluginManager.cs
+++ b/Emby.Server.Implementations/Plugins/PluginManager.cs
@@ -22,11 +22,8 @@ using MediaBrowser.Model.Configuration;
using MediaBrowser.Model.IO;
using MediaBrowser.Model.Plugins;
using MediaBrowser.Model.Updates;
-using Microsoft.AspNetCore.Mvc.ApplicationParts;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
-using Nikse.SubtitleEdit.Core.Common;
-using SQLitePCL.pretty;
namespace Emby.Server.Implementations.Plugins
{
From a944352aa8b961ab723fed2d66947c19129a11cc Mon Sep 17 00:00:00 2001
From: AmbulantRex <21176662+AmbulantRex@users.noreply.github.com>
Date: Sat, 1 Apr 2023 04:59:07 -0600
Subject: [PATCH 03/21] Correct style inconsistencies
---
Emby.Server.Implementations/Library/PathExtensions.cs | 9 ++++++---
Emby.Server.Implementations/Plugins/PluginManager.cs | 2 +-
MediaBrowser.Common/Plugins/PluginManifest.cs | 4 ++--
MediaBrowser.Model/Updates/VersionInfo.cs | 2 +-
.../Test Data/Updates/manifest-stable.json | 2 +-
5 files changed, 11 insertions(+), 8 deletions(-)
diff --git a/Emby.Server.Implementations/Library/PathExtensions.cs b/Emby.Server.Implementations/Library/PathExtensions.cs
index a3d748a138..62a9e6419e 100644
--- a/Emby.Server.Implementations/Library/PathExtensions.cs
+++ b/Emby.Server.Implementations/Library/PathExtensions.cs
@@ -87,8 +87,8 @@ namespace Emby.Server.Implementations.Library
return false;
}
- subPath = subPath.NormalizePath(out var newDirectorySeparatorChar)!;
- path = path.NormalizePath(newDirectorySeparatorChar)!;
+ subPath = subPath.NormalizePath(out var newDirectorySeparatorChar);
+ path = path.NormalizePath(newDirectorySeparatorChar);
// We have to ensure that the sub path ends with a directory separator otherwise we'll get weird results
// when the sub path matches a similar but in-complete subpath
@@ -128,6 +128,7 @@ namespace Emby.Server.Implementations.Library
///
/// The path to normalize.
/// The normalized path string or if the input path is null or empty.
+ [return: NotNullIfNotNull(nameof(path))]
public static string? NormalizePath(this string? path)
{
return path.NormalizePath(Path.DirectorySeparatorChar);
@@ -139,6 +140,7 @@ namespace Emby.Server.Implementations.Library
/// The path to normalize.
/// The separator character the path now uses or .
/// The normalized path string or if the input path is null or empty.
+ [return: NotNullIfNotNull(nameof(path))]
public static string? NormalizePath(this string? path, out char separator)
{
if (string.IsNullOrEmpty(path))
@@ -169,6 +171,7 @@ namespace Emby.Server.Implementations.Library
/// The replacement directory separator character. Must be a valid directory separator.
/// The normalized path.
/// Thrown if the new separator character is not a directory separator.
+ [return: NotNullIfNotNull(nameof(path))]
public static string? NormalizePath(this string? path, char newSeparator)
{
const char Bs = '\\';
@@ -184,7 +187,7 @@ namespace Emby.Server.Implementations.Library
return path;
}
- return newSeparator == Bs ? path?.Replace(Fs, newSeparator) : path?.Replace(Bs, newSeparator);
+ return newSeparator == Bs ? path.Replace(Fs, newSeparator) : path.Replace(Bs, newSeparator);
}
}
}
diff --git a/Emby.Server.Implementations/Plugins/PluginManager.cs b/Emby.Server.Implementations/Plugins/PluginManager.cs
index d253a0ab99..0a7c144ed7 100644
--- a/Emby.Server.Implementations/Plugins/PluginManager.cs
+++ b/Emby.Server.Implementations/Plugins/PluginManager.cs
@@ -765,7 +765,7 @@ namespace Emby.Server.Implementations.Plugins
/// If the is null.
private bool TryGetPluginDlls(LocalPlugin plugin, out IReadOnlyList whitelistedDlls)
{
- _ = plugin ?? throw new ArgumentNullException(nameof(plugin));
+ ArgumentNullException.ThrowIfNull(nameof(plugin));
IReadOnlyList pluginDlls = Directory.GetFiles(plugin.Path, "*.dll", SearchOption.AllDirectories);
diff --git a/MediaBrowser.Common/Plugins/PluginManifest.cs b/MediaBrowser.Common/Plugins/PluginManifest.cs
index 2bad3454d1..e0847ccea4 100644
--- a/MediaBrowser.Common/Plugins/PluginManifest.cs
+++ b/MediaBrowser.Common/Plugins/PluginManifest.cs
@@ -24,7 +24,7 @@ namespace MediaBrowser.Common.Plugins
Overview = string.Empty;
TargetAbi = string.Empty;
Version = string.Empty;
- Assemblies = new List();
+ Assemblies = Array.Empty();
}
///
@@ -112,6 +112,6 @@ namespace MediaBrowser.Common.Plugins
/// Paths are considered relative to the plugin folder.
///
[JsonPropertyName("assemblies")]
- public IList Assemblies { get; set; }
+ public IReadOnlyList Assemblies { get; set; }
}
}
diff --git a/MediaBrowser.Model/Updates/VersionInfo.cs b/MediaBrowser.Model/Updates/VersionInfo.cs
index 1e24bde84e..8f76806450 100644
--- a/MediaBrowser.Model/Updates/VersionInfo.cs
+++ b/MediaBrowser.Model/Updates/VersionInfo.cs
@@ -80,6 +80,6 @@ namespace MediaBrowser.Model.Updates
/// Gets or sets the assemblies whitelist for this version.
///
[JsonPropertyName("assemblies")]
- public IList Assemblies { get; set; } = Array.Empty();
+ public IReadOnlyList Assemblies { get; set; } = Array.Empty();
}
}
diff --git a/tests/Jellyfin.Server.Implementations.Tests/Test Data/Updates/manifest-stable.json b/tests/Jellyfin.Server.Implementations.Tests/Test Data/Updates/manifest-stable.json
index d69a52d6d0..3aec299587 100644
--- a/tests/Jellyfin.Server.Implementations.Tests/Test Data/Updates/manifest-stable.json
+++ b/tests/Jellyfin.Server.Implementations.Tests/Test Data/Updates/manifest-stable.json
@@ -25,7 +25,7 @@
"timestamp": "2020-07-20T01:30:16Z",
"assemblies": [ "Jellyfin.Plugin.Anime.dll" ]
}
- ]
+ ]
},
{
"guid": "70b7b43b-471b-4159-b4be-56750c795499",
From 3a731051adf6d636517e5a9babbbe9f9da7d520b Mon Sep 17 00:00:00 2001
From: AmbulantRex <21176662+AmbulantRex@users.noreply.github.com>
Date: Sat, 1 Apr 2023 05:03:55 -0600
Subject: [PATCH 04/21] Correct styling inconsistencies
---
Emby.Server.Implementations/Library/PathExtensions.cs | 6 +++---
1 file changed, 3 insertions(+), 3 deletions(-)
diff --git a/Emby.Server.Implementations/Library/PathExtensions.cs b/Emby.Server.Implementations/Library/PathExtensions.cs
index 62a9e6419e..c4b6b37561 100644
--- a/Emby.Server.Implementations/Library/PathExtensions.cs
+++ b/Emby.Server.Implementations/Library/PathExtensions.cs
@@ -105,7 +105,7 @@ namespace Emby.Server.Implementations.Library
return false;
}
- var newSubPathTrimmed = newSubPath.AsSpan().TrimEnd((char)newDirectorySeparatorChar!);
+ var newSubPathTrimmed = newSubPath.AsSpan().TrimEnd(newDirectorySeparatorChar);
// Ensure that the path with the old subpath removed starts with a leading dir separator
int idx = oldSubPathEndsWithSeparator ? subPath.Length - 1 : subPath.Length;
newPath = string.Concat(newSubPathTrimmed, path.AsSpan(idx));
@@ -120,7 +120,7 @@ namespace Emby.Server.Implementations.Library
/// The fully expanded, normalized path.
public static string Canonicalize(this string path)
{
- return Path.GetFullPath(path).NormalizePath()!;
+ return Path.GetFullPath(path).NormalizePath();
}
///
@@ -161,7 +161,7 @@ namespace Emby.Server.Implementations.Library
separator = newSeparator;
- return path?.NormalizePath(newSeparator);
+ return path.NormalizePath(newSeparator);
}
///
From 7dd4201971f1bb19ea380f2ca83aed11206cfe97 Mon Sep 17 00:00:00 2001
From: AmbulantRex <21176662+AmbulantRex@users.noreply.github.com>
Date: Sun, 9 Apr 2023 10:53:09 -0600
Subject: [PATCH 05/21] Reconcile pre-packaged meta.json against manifest on
install
---
.../Plugins/PluginManager.cs | 74 ++++++-
.../Updates/InstallationManager.cs | 7 +-
MediaBrowser.Common/Plugins/IPluginManager.cs | 2 +-
MediaBrowser.Model/Updates/VersionInfo.cs | 6 -
src/Jellyfin.Extensions/TypeExtensions.cs | 45 +++++
.../TypeExtensionsTests.cs | 68 +++++++
.../Plugins/PluginManagerTests.cs | 181 +++++++++++++++---
.../Test Data/Updates/manifest-stable.json | 6 +-
.../Updates/InstallationManagerTests.cs | 14 --
9 files changed, 341 insertions(+), 62 deletions(-)
create mode 100644 src/Jellyfin.Extensions/TypeExtensions.cs
create mode 100644 tests/Jellyfin.Extensions.Tests/TypeExtensionsTests.cs
diff --git a/Emby.Server.Implementations/Plugins/PluginManager.cs b/Emby.Server.Implementations/Plugins/PluginManager.cs
index 0a7c144ed7..c6a7f45464 100644
--- a/Emby.Server.Implementations/Plugins/PluginManager.cs
+++ b/Emby.Server.Implementations/Plugins/PluginManager.cs
@@ -32,6 +32,8 @@ namespace Emby.Server.Implementations.Plugins
///
public class PluginManager : IPluginManager
{
+ private const string MetafileName = "meta.json";
+
private readonly string _pluginsPath;
private readonly Version _appVersion;
private readonly List _assemblyLoadContexts;
@@ -374,7 +376,7 @@ namespace Emby.Server.Implementations.Plugins
try
{
var data = JsonSerializer.Serialize(manifest, _jsonOptions);
- File.WriteAllText(Path.Combine(path, "meta.json"), data);
+ File.WriteAllText(Path.Combine(path, MetafileName), data);
return true;
}
catch (ArgumentException e)
@@ -385,7 +387,7 @@ namespace Emby.Server.Implementations.Plugins
}
///
- public async Task GenerateManifest(PackageInfo packageInfo, Version version, string path, PluginStatus status)
+ public async Task PopulateManifest(PackageInfo packageInfo, Version version, string path, PluginStatus status)
{
var versionInfo = packageInfo.Versions.First(v => v.Version == version.ToString());
var imagePath = string.Empty;
@@ -427,13 +429,75 @@ namespace Emby.Server.Implementations.Plugins
Version = versionInfo.Version,
Status = status == PluginStatus.Disabled ? PluginStatus.Disabled : PluginStatus.Active, // Keep disabled state.
AutoUpdate = true,
- ImagePath = imagePath,
- Assemblies = versionInfo.Assemblies
+ ImagePath = imagePath
};
+ var metafile = Path.Combine(Path.Combine(path, MetafileName));
+ if (File.Exists(metafile))
+ {
+ var data = File.ReadAllBytes(metafile);
+ var localManifest = JsonSerializer.Deserialize(data, _jsonOptions) ?? new PluginManifest();
+
+ // Plugin installation is the typical cause for populating a manifest. Activate.
+ localManifest.Status = status == PluginStatus.Disabled ? PluginStatus.Disabled : PluginStatus.Active;
+
+ if (!Equals(localManifest.Id, manifest.Id))
+ {
+ _logger.LogError("The manifest ID {LocalUUID} did not match the package info ID {PackageUUID}.", localManifest.Id, manifest.Id);
+ localManifest.Status = PluginStatus.Malfunctioned;
+ }
+
+ if (localManifest.Version != manifest.Version)
+ {
+ _logger.LogWarning("The version of the local manifest was {LocalVersion}, but {PackageVersion} was expected. The value will be replaced.", localManifest.Version, manifest.Version);
+
+ // Correct the local version.
+ localManifest.Version = manifest.Version;
+ }
+
+ // Reconcile missing data against repository manifest.
+ ReconcileManifest(localManifest, manifest);
+
+ manifest = localManifest;
+ }
+ else
+ {
+ _logger.LogInformation("No local manifest exists for plugin {Plugin}. Populating from repository manifest.", manifest.Name);
+ }
+
return SaveManifest(manifest, path);
}
+ ///
+ /// Resolve the target plugin manifest against the source. Values are mapped onto the
+ /// target only if they are default values or empty strings. ID and status fields are ignored.
+ ///
+ /// The base to be reconciled.
+ /// The to reconcile against.
+ private void ReconcileManifest(PluginManifest baseManifest, PluginManifest projector)
+ {
+ var ignoredFields = new string[]
+ {
+ nameof(baseManifest.Id),
+ nameof(baseManifest.Status)
+ };
+
+ foreach (var property in baseManifest.GetType().GetProperties())
+ {
+ var localValue = property.GetValue(baseManifest);
+
+ if (property.PropertyType == typeof(bool) || ignoredFields.Any(s => Equals(s, property.Name)))
+ {
+ continue;
+ }
+
+ if (property.PropertyType.IsNullOrDefault(localValue) || (property.PropertyType == typeof(string) && (string)localValue! == string.Empty))
+ {
+ property.SetValue(baseManifest, property.GetValue(projector));
+ }
+ }
+ }
+
///
/// Changes a plugin's load status.
///
@@ -598,7 +662,7 @@ namespace Emby.Server.Implementations.Plugins
{
Version? version;
PluginManifest? manifest = null;
- var metafile = Path.Combine(dir, "meta.json");
+ var metafile = Path.Combine(dir, MetafileName);
if (File.Exists(metafile))
{
// Only path where this stays null is when File.ReadAllBytes throws an IOException
diff --git a/Emby.Server.Implementations/Updates/InstallationManager.cs b/Emby.Server.Implementations/Updates/InstallationManager.cs
index 5e897833e0..6c198b6f99 100644
--- a/Emby.Server.Implementations/Updates/InstallationManager.cs
+++ b/Emby.Server.Implementations/Updates/InstallationManager.cs
@@ -183,7 +183,7 @@ namespace Emby.Server.Implementations.Updates
var plugin = _pluginManager.GetPlugin(package.Id, version.VersionNumber);
if (plugin is not null)
{
- await _pluginManager.GenerateManifest(package, version.VersionNumber, plugin.Path, plugin.Manifest.Status).ConfigureAwait(false);
+ await _pluginManager.PopulateManifest(package, version.VersionNumber, plugin.Path, plugin.Manifest.Status).ConfigureAwait(false);
}
// Remove versions with a target ABI greater then the current application version.
@@ -555,7 +555,10 @@ namespace Emby.Server.Implementations.Updates
stream.Position = 0;
using var reader = new ZipArchive(stream);
reader.ExtractToDirectory(targetDir, true);
- await _pluginManager.GenerateManifest(package.PackageInfo, package.Version, targetDir, status).ConfigureAwait(false);
+
+ // Ensure we create one or populate existing ones with missing data.
+ await _pluginManager.PopulateManifest(package.PackageInfo, package.Version, targetDir, status);
+
_pluginManager.ImportPluginFrom(targetDir);
}
diff --git a/MediaBrowser.Common/Plugins/IPluginManager.cs b/MediaBrowser.Common/Plugins/IPluginManager.cs
index fa92d383a2..1d73de3c95 100644
--- a/MediaBrowser.Common/Plugins/IPluginManager.cs
+++ b/MediaBrowser.Common/Plugins/IPluginManager.cs
@@ -57,7 +57,7 @@ namespace MediaBrowser.Common.Plugins
/// The path where to save the manifest.
/// Initial status of the plugin.
/// True if successful.
- Task GenerateManifest(PackageInfo packageInfo, Version version, string path, PluginStatus status);
+ Task PopulateManifest(PackageInfo packageInfo, Version version, string path, PluginStatus status);
///
/// Imports plugin details from a folder.
diff --git a/MediaBrowser.Model/Updates/VersionInfo.cs b/MediaBrowser.Model/Updates/VersionInfo.cs
index 8f76806450..53e1d29b01 100644
--- a/MediaBrowser.Model/Updates/VersionInfo.cs
+++ b/MediaBrowser.Model/Updates/VersionInfo.cs
@@ -75,11 +75,5 @@ namespace MediaBrowser.Model.Updates
///
[JsonPropertyName("repositoryUrl")]
public string RepositoryUrl { get; set; } = string.Empty;
-
- ///
- /// Gets or sets the assemblies whitelist for this version.
- ///
- [JsonPropertyName("assemblies")]
- public IReadOnlyList Assemblies { get; set; } = Array.Empty();
}
}
diff --git a/src/Jellyfin.Extensions/TypeExtensions.cs b/src/Jellyfin.Extensions/TypeExtensions.cs
new file mode 100644
index 0000000000..5b1111d594
--- /dev/null
+++ b/src/Jellyfin.Extensions/TypeExtensions.cs
@@ -0,0 +1,45 @@
+using System;
+using System.Globalization;
+
+namespace Jellyfin.Extensions;
+
+///
+/// Provides extensions methods for .
+///
+public static class TypeExtensions
+{
+ ///
+ /// Checks if the supplied value is the default or null value for that type.
+ ///
+ /// The type of the value to compare.
+ /// The type.
+ /// The value to check.
+ /// if the value is the default for the type. Otherwise, .
+ public static bool IsNullOrDefault(this Type type, T value)
+ {
+ if (value is null)
+ {
+ return true;
+ }
+
+ object? tmp = value;
+ object? defaultValue = type.IsValueType ? Activator.CreateInstance(type) : null;
+ if (type.IsAssignableTo(typeof(IConvertible)))
+ {
+ tmp = Convert.ChangeType(value, type, CultureInfo.InvariantCulture);
+ }
+
+ return Equals(tmp, defaultValue);
+ }
+
+ ///
+ /// Checks if the object is currently a default or null value. Boxed types will be unboxed prior to comparison.
+ ///
+ /// The object to check.
+ /// if the value is the default for the type. Otherwise, .
+ public static bool IsNullOrDefault(this object? obj)
+ {
+ // Unbox the type and check.
+ return obj?.GetType().IsNullOrDefault(obj) ?? true;
+ }
+}
diff --git a/tests/Jellyfin.Extensions.Tests/TypeExtensionsTests.cs b/tests/Jellyfin.Extensions.Tests/TypeExtensionsTests.cs
new file mode 100644
index 0000000000..747913fa1a
--- /dev/null
+++ b/tests/Jellyfin.Extensions.Tests/TypeExtensionsTests.cs
@@ -0,0 +1,68 @@
+using System;
+using Xunit;
+
+namespace Jellyfin.Extensions.Tests
+{
+ public class TypeExtensionsTests
+ {
+ [Theory]
+ [InlineData(typeof(byte), byte.MaxValue, false)]
+ [InlineData(typeof(short), short.MinValue, false)]
+ [InlineData(typeof(ushort), ushort.MaxValue, false)]
+ [InlineData(typeof(int), int.MinValue, false)]
+ [InlineData(typeof(uint), uint.MaxValue, false)]
+ [InlineData(typeof(long), long.MinValue, false)]
+ [InlineData(typeof(ulong), ulong.MaxValue, false)]
+ [InlineData(typeof(decimal), -1.0, false)]
+ [InlineData(typeof(bool), true, false)]
+ [InlineData(typeof(char), 'a', false)]
+ [InlineData(typeof(string), "", false)]
+ [InlineData(typeof(object), 1, false)]
+ [InlineData(typeof(byte), 0, true)]
+ [InlineData(typeof(short), 0, true)]
+ [InlineData(typeof(ushort), 0, true)]
+ [InlineData(typeof(int), 0, true)]
+ [InlineData(typeof(uint), 0, true)]
+ [InlineData(typeof(long), 0, true)]
+ [InlineData(typeof(ulong), 0, true)]
+ [InlineData(typeof(decimal), 0, true)]
+ [InlineData(typeof(bool), false, true)]
+ [InlineData(typeof(char), '\x0000', true)]
+ [InlineData(typeof(string), null, true)]
+ [InlineData(typeof(object), null, true)]
+ [InlineData(typeof(PhonyClass), null, true)]
+ [InlineData(typeof(DateTime), null, true)] // Special case handled within the test.
+ [InlineData(typeof(DateTime), null, false)] // Special case handled within the test.
+ [InlineData(typeof(byte?), null, true)]
+ [InlineData(typeof(short?), null, true)]
+ [InlineData(typeof(ushort?), null, true)]
+ [InlineData(typeof(int?), null, true)]
+ [InlineData(typeof(uint?), null, true)]
+ [InlineData(typeof(long?), null, true)]
+ [InlineData(typeof(ulong?), null, true)]
+ [InlineData(typeof(decimal?), null, true)]
+ [InlineData(typeof(bool?), null, true)]
+ [InlineData(typeof(char?), null, true)]
+ public void IsNullOrDefault_Matches_Expected(Type type, object? value, bool expectedResult)
+ {
+ if (type == typeof(DateTime))
+ {
+ if (expectedResult)
+ {
+ value = default(DateTime);
+ }
+ else
+ {
+ value = DateTime.Now;
+ }
+ }
+
+ Assert.Equal(expectedResult, type.IsNullOrDefault(value));
+ Assert.Equal(expectedResult, value.IsNullOrDefault());
+ }
+
+ private class PhonyClass
+ {
+ }
+ }
+}
diff --git a/tests/Jellyfin.Server.Implementations.Tests/Plugins/PluginManagerTests.cs b/tests/Jellyfin.Server.Implementations.Tests/Plugins/PluginManagerTests.cs
index d9fdc96f55..204d144214 100644
--- a/tests/Jellyfin.Server.Implementations.Tests/Plugins/PluginManagerTests.cs
+++ b/tests/Jellyfin.Server.Implementations.Tests/Plugins/PluginManagerTests.cs
@@ -1,12 +1,16 @@
using System;
+using System.Globalization;
using System.IO;
using System.Text.Json;
+using System.Threading.Tasks;
+using AutoFixture;
using Emby.Server.Implementations.Library;
using Emby.Server.Implementations.Plugins;
using Jellyfin.Extensions.Json;
using Jellyfin.Extensions.Json.Converters;
using MediaBrowser.Common.Plugins;
using MediaBrowser.Model.Plugins;
+using MediaBrowser.Model.Updates;
using Microsoft.Extensions.Logging.Abstractions;
using Xunit;
@@ -16,6 +20,21 @@ namespace Jellyfin.Server.Implementations.Tests.Plugins
{
private static readonly string _testPathRoot = Path.Combine(Path.GetTempPath(), "jellyfin-test-data");
+ private string _tempPath = string.Empty;
+
+ private string _pluginPath = string.Empty;
+
+ private JsonSerializerOptions _options;
+
+ public PluginManagerTests()
+ {
+ (_tempPath, _pluginPath) = GetTestPaths("plugin-" + Path.GetRandomFileName());
+
+ Directory.CreateDirectory(_pluginPath);
+
+ _options = GetTestSerializerOptions();
+ }
+
[Fact]
public void SaveManifest_RoundTrip_Success()
{
@@ -25,12 +44,9 @@ namespace Jellyfin.Server.Implementations.Tests.Plugins
Version = "1.0"
};
- var tempPath = Path.Combine(_testPathRoot, "manifest-" + Path.GetRandomFileName());
- Directory.CreateDirectory(tempPath);
-
- Assert.True(pluginManager.SaveManifest(manifest, tempPath));
+ Assert.True(pluginManager.SaveManifest(manifest, _pluginPath));
- var res = pluginManager.LoadManifest(tempPath);
+ var res = pluginManager.LoadManifest(_pluginPath);
Assert.Equal(manifest.Category, res.Manifest.Category);
Assert.Equal(manifest.Changelog, res.Manifest.Changelog);
@@ -66,28 +82,25 @@ namespace Jellyfin.Server.Implementations.Tests.Plugins
};
var filename = Path.GetFileName(dllFile)!;
- var (tempPath, pluginPath) = GetTestPaths("safe");
+ var dllPath = Path.GetDirectoryName(Path.Combine(_pluginPath, dllFile))!;
- Directory.CreateDirectory(Path.Combine(pluginPath, dllFile.Replace(filename, string.Empty, StringComparison.OrdinalIgnoreCase)));
- File.Create(Path.Combine(pluginPath, dllFile));
+ Directory.CreateDirectory(dllPath);
+ File.Create(Path.Combine(dllPath, filename));
+ var metafilePath = Path.Combine(_pluginPath, "meta.json");
- var options = GetTestSerializerOptions();
- var data = JsonSerializer.Serialize(manifest, options);
- var metafilePath = Path.Combine(tempPath, "safe", "meta.json");
+ File.WriteAllText(metafilePath, JsonSerializer.Serialize(manifest, _options));
- File.WriteAllText(metafilePath, data);
+ var pluginManager = new PluginManager(new NullLogger(), null!, null!, _tempPath, new Version(1, 0));
- var pluginManager = new PluginManager(new NullLogger(), null!, null!, tempPath, new Version(1, 0));
+ var res = JsonSerializer.Deserialize(File.ReadAllText(metafilePath), _options);
- var res = JsonSerializer.Deserialize(File.ReadAllText(metafilePath), options);
-
- var expectedFullPath = Path.Combine(pluginPath, dllFile).Canonicalize();
+ var expectedFullPath = Path.Combine(_pluginPath, dllFile).Canonicalize();
Assert.NotNull(res);
Assert.NotEmpty(pluginManager.Plugins);
Assert.Equal(PluginStatus.Active, res!.Status);
Assert.Equal(expectedFullPath, pluginManager.Plugins[0].DllFiles[0]);
- Assert.StartsWith(Path.Combine(tempPath, "safe"), expectedFullPath, StringComparison.InvariantCulture);
+ Assert.StartsWith(_pluginPath, expectedFullPath, StringComparison.InvariantCulture);
}
///
@@ -109,7 +122,6 @@ namespace Jellyfin.Server.Implementations.Tests.Plugins
[InlineData("..\\.\\..\\.\\..\\some.dll")] // Windows traversal with current and parent
[InlineData("\\\\network\\resource.dll")] // UNC Path
[InlineData("https://jellyfin.org/some.dll")] // URL
- [InlineData("....//....//some.dll")] // Path replacement risk if a single "../" replacement occurs.
[InlineData("~/some.dll")] // Tilde poses a shell expansion risk, but is a valid path character.
public void Constructor_DiscoversUnsafePluginAssembly_Status_Malfunctioned(string unsafePath)
{
@@ -120,10 +132,7 @@ namespace Jellyfin.Server.Implementations.Tests.Plugins
Assemblies = new string[] { unsafePath }
};
- var (tempPath, pluginPath) = GetTestPaths("unsafe");
-
- Directory.CreateDirectory(pluginPath);
-
+ // Only create very specific files. Otherwise the test will be exploiting path traversal.
var files = new string[]
{
"../other.dll",
@@ -132,24 +141,136 @@ namespace Jellyfin.Server.Implementations.Tests.Plugins
foreach (var file in files)
{
- File.Create(Path.Combine(pluginPath, file));
+ File.Create(Path.Combine(_pluginPath, file));
}
- var options = GetTestSerializerOptions();
- var data = JsonSerializer.Serialize(manifest, options);
- var metafilePath = Path.Combine(tempPath, "unsafe", "meta.json");
+ var metafilePath = Path.Combine(_pluginPath, "meta.json");
- File.WriteAllText(metafilePath, data);
+ File.WriteAllText(metafilePath, JsonSerializer.Serialize(manifest, _options));
- var pluginManager = new PluginManager(new NullLogger(), null!, null!, tempPath, new Version(1, 0));
+ var pluginManager = new PluginManager(new NullLogger(), null!, null!, _tempPath, new Version(1, 0));
- var res = JsonSerializer.Deserialize(File.ReadAllText(metafilePath), options);
+ var res = JsonSerializer.Deserialize(File.ReadAllText(metafilePath), _options);
Assert.NotNull(res);
Assert.Empty(pluginManager.Plugins);
Assert.Equal(PluginStatus.Malfunctioned, res!.Status);
}
+ [Fact]
+ public async Task PopulateManifest_ExistingMetafilePlugin_PopulatesMissingFields()
+ {
+ var packageInfo = GenerateTestPackage();
+
+ // Partial plugin without a name, but matching version and package ID
+ var partial = new PluginManifest
+ {
+ Id = packageInfo.Id,
+ AutoUpdate = false, // Turn off AutoUpdate
+ Status = PluginStatus.Restart,
+ Version = new Version(1, 0, 0).ToString(),
+ Assemblies = new[] { "Jellyfin.Test.dll" }
+ };
+
+ var metafilePath = Path.Combine(_pluginPath, "meta.json");
+ File.WriteAllText(metafilePath, JsonSerializer.Serialize(partial, _options));
+
+ var pluginManager = new PluginManager(new NullLogger(), null!, null!, _tempPath, new Version(1, 0));
+
+ await pluginManager.PopulateManifest(packageInfo, new Version(1, 0), _pluginPath, PluginStatus.Active);
+
+ var resultBytes = File.ReadAllBytes(metafilePath);
+ var result = JsonSerializer.Deserialize(resultBytes, _options);
+
+ Assert.NotNull(result);
+ Assert.Equal(packageInfo.Name, result.Name);
+ Assert.Equal(packageInfo.Owner, result.Owner);
+ Assert.Equal(PluginStatus.Active, result.Status);
+ Assert.NotEmpty(result.Assemblies);
+ Assert.False(result.AutoUpdate);
+
+ // Preserved
+ Assert.Equal(packageInfo.Category, result.Category);
+ Assert.Equal(packageInfo.Description, result.Description);
+ Assert.Equal(packageInfo.Id, result.Id);
+ Assert.Equal(packageInfo.Overview, result.Overview);
+ Assert.Equal(partial.Assemblies[0], result.Assemblies[0]);
+ Assert.Equal(packageInfo.Versions[0].TargetAbi, result.TargetAbi);
+ Assert.Equal(DateTime.Parse(packageInfo.Versions[0].Timestamp!, CultureInfo.InvariantCulture), result.Timestamp);
+ Assert.Equal(packageInfo.Versions[0].Changelog, result.Changelog);
+ Assert.Equal(packageInfo.Versions[0].Version, result.Version);
+ }
+
+ [Fact]
+ public async Task PopulateManifest_ExistingMetafileMismatchedIds_Status_Malfunctioned()
+ {
+ var packageInfo = GenerateTestPackage();
+
+ // Partial plugin without a name, but matching version and package ID
+ var partial = new PluginManifest
+ {
+ Id = Guid.NewGuid(),
+ Version = new Version(1, 0, 0).ToString()
+ };
+
+ var metafilePath = Path.Combine(_pluginPath, "meta.json");
+ File.WriteAllText(metafilePath, JsonSerializer.Serialize(partial, _options));
+
+ var pluginManager = new PluginManager(new NullLogger(), null!, null!, _tempPath, new Version(1, 0));
+
+ await pluginManager.PopulateManifest(packageInfo, new Version(1, 0), _pluginPath, PluginStatus.Active);
+
+ var resultBytes = File.ReadAllBytes(metafilePath);
+ var result = JsonSerializer.Deserialize(resultBytes, _options);
+
+ Assert.NotNull(result);
+ Assert.Equal(packageInfo.Name, result.Name);
+ Assert.Equal(PluginStatus.Malfunctioned, result.Status);
+ }
+
+ [Fact]
+ public async Task PopulateManifest_ExistingMetafileMismatchedVersions_Updates_Version()
+ {
+ var packageInfo = GenerateTestPackage();
+
+ var partial = new PluginManifest
+ {
+ Id = packageInfo.Id,
+ Version = new Version(2, 0, 0).ToString()
+ };
+
+ var metafilePath = Path.Combine(_pluginPath, "meta.json");
+ File.WriteAllText(metafilePath, JsonSerializer.Serialize(partial, _options));
+
+ var pluginManager = new PluginManager(new NullLogger(), null!, null!, _tempPath, new Version(1, 0));
+
+ await pluginManager.PopulateManifest(packageInfo, new Version(1, 0), _pluginPath, PluginStatus.Active);
+
+ var resultBytes = File.ReadAllBytes(metafilePath);
+ var result = JsonSerializer.Deserialize(resultBytes, _options);
+
+ Assert.NotNull(result);
+ Assert.Equal(packageInfo.Name, result.Name);
+ Assert.Equal(PluginStatus.Active, result.Status);
+ Assert.Equal(packageInfo.Versions[0].Version, result.Version);
+ }
+
+ private PackageInfo GenerateTestPackage()
+ {
+ var fixture = new Fixture();
+ fixture.Customize(c => c.Without(x => x.Versions).Without(x => x.ImageUrl));
+ fixture.Customize(c => c.Without(x => x.Version).Without(x => x.Timestamp));
+
+ var versionInfo = fixture.Create();
+ versionInfo.Version = new Version(1, 0).ToString();
+ versionInfo.Timestamp = DateTime.UtcNow.ToString(CultureInfo.InvariantCulture);
+
+ var packageInfo = fixture.Create();
+ packageInfo.Versions = new[] { versionInfo };
+
+ return packageInfo;
+ }
+
private JsonSerializerOptions GetTestSerializerOptions()
{
var options = new JsonSerializerOptions(JsonDefaults.Options)
@@ -171,7 +292,7 @@ namespace Jellyfin.Server.Implementations.Tests.Plugins
private (string TempPath, string PluginPath) GetTestPaths(string pluginFolderName)
{
- var tempPath = Path.Combine(_testPathRoot, "plugins-" + Path.GetRandomFileName());
+ var tempPath = Path.Combine(_testPathRoot, "plugin-manager" + Path.GetRandomFileName());
var pluginPath = Path.Combine(tempPath, pluginFolderName);
return (tempPath, pluginPath);
diff --git a/tests/Jellyfin.Server.Implementations.Tests/Test Data/Updates/manifest-stable.json b/tests/Jellyfin.Server.Implementations.Tests/Test Data/Updates/manifest-stable.json
index 3aec299587..57367ce88c 100644
--- a/tests/Jellyfin.Server.Implementations.Tests/Test Data/Updates/manifest-stable.json
+++ b/tests/Jellyfin.Server.Implementations.Tests/Test Data/Updates/manifest-stable.json
@@ -13,8 +13,7 @@
"targetAbi": "10.6.0.0",
"sourceUrl": "https://repo.jellyfin.org/releases/plugin/anime/anime_10.0.0.0.zip",
"checksum": "93e969adeba1050423fc8817ed3c36f8",
- "timestamp": "2020-08-17T01:41:13Z",
- "assemblies": [ "Jellyfin.Plugin.Anime.dll" ]
+ "timestamp": "2020-08-17T01:41:13Z"
},
{
"version": "9.0.0.0",
@@ -22,8 +21,7 @@
"targetAbi": "10.6.0.0",
"sourceUrl": "https://repo.jellyfin.org/releases/plugin/anime/anime_9.0.0.0.zip",
"checksum": "9b1cebff835813e15f414f44b40c41c8",
- "timestamp": "2020-07-20T01:30:16Z",
- "assemblies": [ "Jellyfin.Plugin.Anime.dll" ]
+ "timestamp": "2020-07-20T01:30:16Z"
}
]
},
diff --git a/tests/Jellyfin.Server.Implementations.Tests/Updates/InstallationManagerTests.cs b/tests/Jellyfin.Server.Implementations.Tests/Updates/InstallationManagerTests.cs
index 70d03f8c4a..7abd2e685f 100644
--- a/tests/Jellyfin.Server.Implementations.Tests/Updates/InstallationManagerTests.cs
+++ b/tests/Jellyfin.Server.Implementations.Tests/Updates/InstallationManagerTests.cs
@@ -106,19 +106,5 @@ namespace Jellyfin.Server.Implementations.Tests.Updates
var ex = await Record.ExceptionAsync(() => _installationManager.InstallPackage(packageInfo, CancellationToken.None)).ConfigureAwait(false);
Assert.Null(ex);
}
-
- [Fact]
- public async Task InstallPackage_WithAssemblies_Success()
- {
- PackageInfo[] packages = await _installationManager.GetPackages(
- "Jellyfin Stable",
- "https://repo.jellyfin.org/releases/plugin/manifest-stable.json",
- false);
-
- packages = _installationManager.FilterPackages(packages, "Anime").ToArray();
- Assert.Single(packages);
- Assert.NotEmpty(packages[0].Versions[0].Assemblies);
- Assert.Equal("Jellyfin.Plugin.Anime.dll", packages[0].Versions[0].Assemblies[0]);
- }
}
}
From 92f50054b28c85afbee0dfa99016c4b71548de6f Mon Sep 17 00:00:00 2001
From: AmbulantRex <21176662+AmbulantRex@users.noreply.github.com>
Date: Sun, 16 Apr 2023 07:46:12 -0600
Subject: [PATCH 06/21] Add explicit mapping instead of reflection to manifest
reconciliation.
---
.../Plugins/PluginManager.cs | 90 +++++++++----------
MediaBrowser.Model/Updates/VersionInfo.cs | 2 -
.../Plugins/PluginManagerTests.cs | 69 ++++++++++----
3 files changed, 97 insertions(+), 64 deletions(-)
diff --git a/Emby.Server.Implementations/Plugins/PluginManager.cs b/Emby.Server.Implementations/Plugins/PluginManager.cs
index 2d2ad26d29..10d5ea906e 100644
--- a/Emby.Server.Implementations/Plugins/PluginManager.cs
+++ b/Emby.Server.Implementations/Plugins/PluginManager.cs
@@ -432,69 +432,67 @@ namespace Emby.Server.Implementations.Plugins
ImagePath = imagePath
};
- var metafile = Path.Combine(Path.Combine(path, MetafileName));
- if (File.Exists(metafile))
- {
- var data = File.ReadAllBytes(metafile);
- var localManifest = JsonSerializer.Deserialize(data, _jsonOptions) ?? new PluginManifest();
-
- // Plugin installation is the typical cause for populating a manifest. Activate.
- localManifest.Status = status == PluginStatus.Disabled ? PluginStatus.Disabled : PluginStatus.Active;
-
- if (!Equals(localManifest.Id, manifest.Id))
- {
- _logger.LogError("The manifest ID {LocalUUID} did not match the package info ID {PackageUUID}.", localManifest.Id, manifest.Id);
- localManifest.Status = PluginStatus.Malfunctioned;
- }
-
- if (localManifest.Version != manifest.Version)
- {
- _logger.LogWarning("The version of the local manifest was {LocalVersion}, but {PackageVersion} was expected. The value will be replaced.", localManifest.Version, manifest.Version);
-
- // Correct the local version.
- localManifest.Version = manifest.Version;
- }
-
- // Reconcile missing data against repository manifest.
- ReconcileManifest(localManifest, manifest);
-
- manifest = localManifest;
- }
- else
+ if (!ReconcileManifest(manifest, path))
{
- _logger.LogInformation("No local manifest exists for plugin {Plugin}. Populating from repository manifest.", manifest.Name);
+ // An error occurred during reconciliation and saving could be undesirable.
+ return false;
}
return SaveManifest(manifest, path);
}
///
- /// Resolve the target plugin manifest against the source. Values are mapped onto the
- /// target only if they are default values or empty strings. ID and status fields are ignored.
+ /// Reconciles the manifest against any properties that exist locally in a pre-packaged meta.json found at the path.
+ /// If no file is found, no reconciliation occurs.
///
- /// The base to be reconciled.
- /// The to reconcile against.
- private void ReconcileManifest(PluginManifest baseManifest, PluginManifest projector)
+ /// The to reconcile against.
+ /// The plugin path.
+ /// The reconciled .
+ private bool ReconcileManifest(PluginManifest manifest, string path)
{
- var ignoredFields = new string[]
+ try
{
- nameof(baseManifest.Id),
- nameof(baseManifest.Status)
- };
+ var metafile = Path.Combine(path, MetafileName);
+ if (!File.Exists(metafile))
+ {
+ _logger.LogInformation("No local manifest exists for plugin {Plugin}. Skipping manifest reconciliation.", manifest.Name);
+ return true;
+ }
- foreach (var property in baseManifest.GetType().GetProperties())
- {
- var localValue = property.GetValue(baseManifest);
+ var data = File.ReadAllBytes(metafile);
+ var localManifest = JsonSerializer.Deserialize(data, _jsonOptions) ?? new PluginManifest();
- if (property.PropertyType == typeof(bool) || ignoredFields.Any(s => Equals(s, property.Name)))
+ if (!Equals(localManifest.Id, manifest.Id))
{
- continue;
+ _logger.LogError("The manifest ID {LocalUUID} did not match the package info ID {PackageUUID}.", localManifest.Id, manifest.Id);
+ manifest.Status = PluginStatus.Malfunctioned;
}
- if (property.PropertyType.IsNullOrDefault(localValue) || (property.PropertyType == typeof(string) && (string)localValue! == string.Empty))
+ if (localManifest.Version != manifest.Version)
{
- property.SetValue(baseManifest, property.GetValue(projector));
+ // Package information provides the version and is the source of truth. Pre-packages meta.json is assumed to be a mistake in this regard.
+ _logger.LogWarning("The version of the local manifest was {LocalVersion}, but {PackageVersion} was expected. The value will be replaced.", localManifest.Version, manifest.Version);
}
+
+ // Explicitly mapping properties instead of using reflection is preferred here.
+ manifest.Category = string.IsNullOrEmpty(localManifest.Category) ? manifest.Category : localManifest.Category;
+ manifest.AutoUpdate = localManifest.AutoUpdate; // Preserve whatever is local. Package info does not have this property.
+ manifest.Changelog = string.IsNullOrEmpty(localManifest.Changelog) ? manifest.Changelog : localManifest.Changelog;
+ manifest.Description = string.IsNullOrEmpty(localManifest.Description) ? manifest.Description : localManifest.Description;
+ manifest.Name = string.IsNullOrEmpty(localManifest.Name) ? manifest.Name : localManifest.Name;
+ manifest.Overview = string.IsNullOrEmpty(localManifest.Overview) ? manifest.Overview : localManifest.Overview;
+ manifest.Owner = string.IsNullOrEmpty(localManifest.Owner) ? manifest.Owner : localManifest.Owner;
+ manifest.TargetAbi = string.IsNullOrEmpty(localManifest.TargetAbi) ? manifest.TargetAbi : localManifest.TargetAbi;
+ manifest.Timestamp = localManifest.Timestamp.IsNullOrDefault() ? manifest.Timestamp : localManifest.Timestamp;
+ manifest.ImagePath = string.IsNullOrEmpty(localManifest.ImagePath) ? manifest.ImagePath : localManifest.ImagePath;
+ manifest.Assemblies = localManifest.Assemblies;
+
+ return true;
+ }
+ catch (Exception e)
+ {
+ _logger.LogWarning(e, "Unable to reconcile plugin manifest due to an error. {Path}", path);
+ return false;
}
}
diff --git a/MediaBrowser.Model/Updates/VersionInfo.cs b/MediaBrowser.Model/Updates/VersionInfo.cs
index 53e1d29b01..320199f984 100644
--- a/MediaBrowser.Model/Updates/VersionInfo.cs
+++ b/MediaBrowser.Model/Updates/VersionInfo.cs
@@ -1,5 +1,3 @@
-using System;
-using System.Collections.Generic;
using System.Text.Json.Serialization;
using SysVersion = System.Version;
diff --git a/tests/Jellyfin.Server.Implementations.Tests/Plugins/PluginManagerTests.cs b/tests/Jellyfin.Server.Implementations.Tests/Plugins/PluginManagerTests.cs
index 204d144214..d4b90dac02 100644
--- a/tests/Jellyfin.Server.Implementations.Tests/Plugins/PluginManagerTests.cs
+++ b/tests/Jellyfin.Server.Implementations.Tests/Plugins/PluginManagerTests.cs
@@ -172,6 +172,24 @@ namespace Jellyfin.Server.Implementations.Tests.Plugins
Assemblies = new[] { "Jellyfin.Test.dll" }
};
+ var expectedManifest = new PluginManifest
+ {
+ Id = partial.Id,
+ Name = packageInfo.Name,
+ AutoUpdate = partial.AutoUpdate,
+ Status = PluginStatus.Active,
+ Owner = packageInfo.Owner,
+ Assemblies = partial.Assemblies,
+ Category = packageInfo.Category,
+ Description = packageInfo.Description,
+ Overview = packageInfo.Overview,
+ TargetAbi = packageInfo.Versions[0].TargetAbi!,
+ Timestamp = DateTime.Parse(packageInfo.Versions[0].Timestamp!, CultureInfo.InvariantCulture),
+ Changelog = packageInfo.Versions[0].Changelog!,
+ Version = new Version(1, 0).ToString(),
+ ImagePath = string.Empty
+ };
+
var metafilePath = Path.Combine(_pluginPath, "meta.json");
File.WriteAllText(metafilePath, JsonSerializer.Serialize(partial, _options));
@@ -183,22 +201,41 @@ namespace Jellyfin.Server.Implementations.Tests.Plugins
var result = JsonSerializer.Deserialize(resultBytes, _options);
Assert.NotNull(result);
- Assert.Equal(packageInfo.Name, result.Name);
- Assert.Equal(packageInfo.Owner, result.Owner);
- Assert.Equal(PluginStatus.Active, result.Status);
- Assert.NotEmpty(result.Assemblies);
- Assert.False(result.AutoUpdate);
-
- // Preserved
- Assert.Equal(packageInfo.Category, result.Category);
- Assert.Equal(packageInfo.Description, result.Description);
- Assert.Equal(packageInfo.Id, result.Id);
- Assert.Equal(packageInfo.Overview, result.Overview);
- Assert.Equal(partial.Assemblies[0], result.Assemblies[0]);
- Assert.Equal(packageInfo.Versions[0].TargetAbi, result.TargetAbi);
- Assert.Equal(DateTime.Parse(packageInfo.Versions[0].Timestamp!, CultureInfo.InvariantCulture), result.Timestamp);
- Assert.Equal(packageInfo.Versions[0].Changelog, result.Changelog);
- Assert.Equal(packageInfo.Versions[0].Version, result.Version);
+ Assert.Equivalent(expectedManifest, result);
+ }
+
+ [Fact]
+ public async Task PopulateManifest_NoMetafile_PreservesManifest()
+ {
+ var packageInfo = GenerateTestPackage();
+ var expectedManifest = new PluginManifest
+ {
+ Id = packageInfo.Id,
+ Name = packageInfo.Name,
+ AutoUpdate = true,
+ Status = PluginStatus.Active,
+ Owner = packageInfo.Owner,
+ Assemblies = Array.Empty(),
+ Category = packageInfo.Category,
+ Description = packageInfo.Description,
+ Overview = packageInfo.Overview,
+ TargetAbi = packageInfo.Versions[0].TargetAbi!,
+ Timestamp = DateTime.Parse(packageInfo.Versions[0].Timestamp!, CultureInfo.InvariantCulture),
+ Changelog = packageInfo.Versions[0].Changelog!,
+ Version = packageInfo.Versions[0].Version,
+ ImagePath = string.Empty
+ };
+
+ var pluginManager = new PluginManager(new NullLogger(), null!, null!, null!, new Version(1, 0));
+
+ await pluginManager.PopulateManifest(packageInfo, new Version(1, 0), _pluginPath, PluginStatus.Active);
+
+ var metafilePath = Path.Combine(_pluginPath, "meta.json");
+ var resultBytes = File.ReadAllBytes(metafilePath);
+ var result = JsonSerializer.Deserialize(resultBytes, _options);
+
+ Assert.NotNull(result);
+ Assert.Equivalent(expectedManifest, result);
}
[Fact]
From c7174255498e28272fbe6d4d6867a774a3327eff Mon Sep 17 00:00:00 2001
From: AmbulantRex <21176662+AmbulantRex@users.noreply.github.com>
Date: Sun, 16 Apr 2023 18:47:57 -0600
Subject: [PATCH 07/21] Remove unnecessary type extension and handle feedback.
---
.../Plugins/PluginManager.cs | 13 ++--
src/Jellyfin.Extensions/TypeExtensions.cs | 45 ------------
.../TypeExtensionsTests.cs | 68 -------------------
3 files changed, 7 insertions(+), 119 deletions(-)
delete mode 100644 src/Jellyfin.Extensions/TypeExtensions.cs
delete mode 100644 tests/Jellyfin.Extensions.Tests/TypeExtensionsTests.cs
diff --git a/Emby.Server.Implementations/Plugins/PluginManager.cs b/Emby.Server.Implementations/Plugins/PluginManager.cs
index 10d5ea906e..48584ae0cb 100644
--- a/Emby.Server.Implementations/Plugins/PluginManager.cs
+++ b/Emby.Server.Implementations/Plugins/PluginManager.cs
@@ -432,7 +432,7 @@ namespace Emby.Server.Implementations.Plugins
ImagePath = imagePath
};
- if (!ReconcileManifest(manifest, path))
+ if (!await ReconcileManifest(manifest, path))
{
// An error occurred during reconciliation and saving could be undesirable.
return false;
@@ -448,7 +448,7 @@ namespace Emby.Server.Implementations.Plugins
/// The to reconcile against.
/// The plugin path.
/// The reconciled .
- private bool ReconcileManifest(PluginManifest manifest, string path)
+ private async Task ReconcileManifest(PluginManifest manifest, string path)
{
try
{
@@ -459,8 +459,9 @@ namespace Emby.Server.Implementations.Plugins
return true;
}
- var data = File.ReadAllBytes(metafile);
- var localManifest = JsonSerializer.Deserialize(data, _jsonOptions) ?? new PluginManifest();
+ using var metaStream = File.OpenRead(metafile);
+ var localManifest = await JsonSerializer.DeserializeAsync(metaStream, _jsonOptions);
+ localManifest ??= new PluginManifest();
if (!Equals(localManifest.Id, manifest.Id))
{
@@ -483,7 +484,7 @@ namespace Emby.Server.Implementations.Plugins
manifest.Overview = string.IsNullOrEmpty(localManifest.Overview) ? manifest.Overview : localManifest.Overview;
manifest.Owner = string.IsNullOrEmpty(localManifest.Owner) ? manifest.Owner : localManifest.Owner;
manifest.TargetAbi = string.IsNullOrEmpty(localManifest.TargetAbi) ? manifest.TargetAbi : localManifest.TargetAbi;
- manifest.Timestamp = localManifest.Timestamp.IsNullOrDefault() ? manifest.Timestamp : localManifest.Timestamp;
+ manifest.Timestamp = localManifest.Timestamp.Equals(default) ? manifest.Timestamp : localManifest.Timestamp;
manifest.ImagePath = string.IsNullOrEmpty(localManifest.ImagePath) ? manifest.ImagePath : localManifest.ImagePath;
manifest.Assemblies = localManifest.Assemblies;
@@ -842,7 +843,7 @@ namespace Emby.Server.Implementations.Plugins
var canonicalized = Path.Combine(plugin.Path, path).Canonicalize();
// Ensure we stay in the plugin directory.
- if (!canonicalized.StartsWith(plugin.Path.NormalizePath()!, StringComparison.Ordinal))
+ if (!canonicalized.StartsWith(plugin.Path.NormalizePath(), StringComparison.Ordinal))
{
_logger.LogError("Assembly path {Path} is not inside the plugin directory.", path);
return false;
diff --git a/src/Jellyfin.Extensions/TypeExtensions.cs b/src/Jellyfin.Extensions/TypeExtensions.cs
deleted file mode 100644
index 5b1111d594..0000000000
--- a/src/Jellyfin.Extensions/TypeExtensions.cs
+++ /dev/null
@@ -1,45 +0,0 @@
-using System;
-using System.Globalization;
-
-namespace Jellyfin.Extensions;
-
-///
-/// Provides extensions methods for .
-///
-public static class TypeExtensions
-{
- ///
- /// Checks if the supplied value is the default or null value for that type.
- ///
- /// The type of the value to compare.
- /// The type.
- /// The value to check.
- /// if the value is the default for the type. Otherwise, .
- public static bool IsNullOrDefault(this Type type, T value)
- {
- if (value is null)
- {
- return true;
- }
-
- object? tmp = value;
- object? defaultValue = type.IsValueType ? Activator.CreateInstance(type) : null;
- if (type.IsAssignableTo(typeof(IConvertible)))
- {
- tmp = Convert.ChangeType(value, type, CultureInfo.InvariantCulture);
- }
-
- return Equals(tmp, defaultValue);
- }
-
- ///
- /// Checks if the object is currently a default or null value. Boxed types will be unboxed prior to comparison.
- ///
- /// The object to check.
- /// if the value is the default for the type. Otherwise, .
- public static bool IsNullOrDefault(this object? obj)
- {
- // Unbox the type and check.
- return obj?.GetType().IsNullOrDefault(obj) ?? true;
- }
-}
diff --git a/tests/Jellyfin.Extensions.Tests/TypeExtensionsTests.cs b/tests/Jellyfin.Extensions.Tests/TypeExtensionsTests.cs
deleted file mode 100644
index 747913fa1a..0000000000
--- a/tests/Jellyfin.Extensions.Tests/TypeExtensionsTests.cs
+++ /dev/null
@@ -1,68 +0,0 @@
-using System;
-using Xunit;
-
-namespace Jellyfin.Extensions.Tests
-{
- public class TypeExtensionsTests
- {
- [Theory]
- [InlineData(typeof(byte), byte.MaxValue, false)]
- [InlineData(typeof(short), short.MinValue, false)]
- [InlineData(typeof(ushort), ushort.MaxValue, false)]
- [InlineData(typeof(int), int.MinValue, false)]
- [InlineData(typeof(uint), uint.MaxValue, false)]
- [InlineData(typeof(long), long.MinValue, false)]
- [InlineData(typeof(ulong), ulong.MaxValue, false)]
- [InlineData(typeof(decimal), -1.0, false)]
- [InlineData(typeof(bool), true, false)]
- [InlineData(typeof(char), 'a', false)]
- [InlineData(typeof(string), "", false)]
- [InlineData(typeof(object), 1, false)]
- [InlineData(typeof(byte), 0, true)]
- [InlineData(typeof(short), 0, true)]
- [InlineData(typeof(ushort), 0, true)]
- [InlineData(typeof(int), 0, true)]
- [InlineData(typeof(uint), 0, true)]
- [InlineData(typeof(long), 0, true)]
- [InlineData(typeof(ulong), 0, true)]
- [InlineData(typeof(decimal), 0, true)]
- [InlineData(typeof(bool), false, true)]
- [InlineData(typeof(char), '\x0000', true)]
- [InlineData(typeof(string), null, true)]
- [InlineData(typeof(object), null, true)]
- [InlineData(typeof(PhonyClass), null, true)]
- [InlineData(typeof(DateTime), null, true)] // Special case handled within the test.
- [InlineData(typeof(DateTime), null, false)] // Special case handled within the test.
- [InlineData(typeof(byte?), null, true)]
- [InlineData(typeof(short?), null, true)]
- [InlineData(typeof(ushort?), null, true)]
- [InlineData(typeof(int?), null, true)]
- [InlineData(typeof(uint?), null, true)]
- [InlineData(typeof(long?), null, true)]
- [InlineData(typeof(ulong?), null, true)]
- [InlineData(typeof(decimal?), null, true)]
- [InlineData(typeof(bool?), null, true)]
- [InlineData(typeof(char?), null, true)]
- public void IsNullOrDefault_Matches_Expected(Type type, object? value, bool expectedResult)
- {
- if (type == typeof(DateTime))
- {
- if (expectedResult)
- {
- value = default(DateTime);
- }
- else
- {
- value = DateTime.Now;
- }
- }
-
- Assert.Equal(expectedResult, type.IsNullOrDefault(value));
- Assert.Equal(expectedResult, value.IsNullOrDefault());
- }
-
- private class PhonyClass
- {
- }
- }
-}
From 6ddc449a89ac615deb8c6d736e9cac7af4e02b9c Mon Sep 17 00:00:00 2001
From: Shadowghost
Date: Tue, 2 Aug 2022 17:46:38 +0200
Subject: [PATCH 08/21] Implement NFO named season parsing
---
.../Library/Resolvers/TV/SeasonResolver.cs | 26 +++++--
MediaBrowser.Controller/Entities/TV/Series.cs | 4 +
.../Manager/MetadataService.cs | 1 +
.../TV/SeriesMetadataService.cs | 78 ++++++++++++++-----
.../Parsers/SeasonNfoParser.cs | 12 +++
.../Parsers/SeriesNfoParser.cs | 15 ++++
6 files changed, 107 insertions(+), 29 deletions(-)
diff --git a/Emby.Server.Implementations/Library/Resolvers/TV/SeasonResolver.cs b/Emby.Server.Implementations/Library/Resolvers/TV/SeasonResolver.cs
index 62a524d2eb..e9538a5c97 100644
--- a/Emby.Server.Implementations/Library/Resolvers/TV/SeasonResolver.cs
+++ b/Emby.Server.Implementations/Library/Resolvers/TV/SeasonResolver.cs
@@ -81,14 +81,24 @@ namespace Emby.Server.Implementations.Library.Resolvers.TV
if (season.IndexNumber.HasValue)
{
var seasonNumber = season.IndexNumber.Value;
-
- season.Name = seasonNumber == 0 ?
- args.LibraryOptions.SeasonZeroDisplayName :
- string.Format(
- CultureInfo.InvariantCulture,
- _localization.GetLocalizedString("NameSeasonNumber"),
- seasonNumber,
- args.LibraryOptions.PreferredMetadataLanguage);
+ if (string.IsNullOrEmpty(season.Name))
+ {
+ var seasonNames = series.SeasonNames;
+ if (seasonNames.TryGetValue(seasonNumber, out var seasonName))
+ {
+ season.Name = seasonName;
+ }
+ else
+ {
+ season.Name = seasonNumber == 0 ?
+ args.LibraryOptions.SeasonZeroDisplayName :
+ string.Format(
+ CultureInfo.InvariantCulture,
+ _localization.GetLocalizedString("NameSeasonNumber"),
+ seasonNumber,
+ args.LibraryOptions.PreferredMetadataLanguage);
+ }
+ }
}
return season;
diff --git a/MediaBrowser.Controller/Entities/TV/Series.cs b/MediaBrowser.Controller/Entities/TV/Series.cs
index e7a8a773ec..a49c1609d9 100644
--- a/MediaBrowser.Controller/Entities/TV/Series.cs
+++ b/MediaBrowser.Controller/Entities/TV/Series.cs
@@ -28,12 +28,16 @@ namespace MediaBrowser.Controller.Entities.TV
public Series()
{
AirDays = Array.Empty();
+ SeasonNames = new Dictionary();
}
public DayOfWeek[] AirDays { get; set; }
public string AirTime { get; set; }
+ [JsonIgnore]
+ public Dictionary SeasonNames { get; set; }
+
[JsonIgnore]
public override bool SupportsAddingToPlaylist => true;
diff --git a/MediaBrowser.Providers/Manager/MetadataService.cs b/MediaBrowser.Providers/Manager/MetadataService.cs
index 80f77f7c3a..834ef29f51 100644
--- a/MediaBrowser.Providers/Manager/MetadataService.cs
+++ b/MediaBrowser.Providers/Manager/MetadataService.cs
@@ -12,6 +12,7 @@ using Jellyfin.Extensions;
using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Entities.Audio;
+using MediaBrowser.Controller.Entities.TV;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.Configuration;
diff --git a/MediaBrowser.Providers/TV/SeriesMetadataService.cs b/MediaBrowser.Providers/TV/SeriesMetadataService.cs
index 97f9383971..b99f1cbdbf 100644
--- a/MediaBrowser.Providers/TV/SeriesMetadataService.cs
+++ b/MediaBrowser.Providers/TV/SeriesMetadataService.cs
@@ -41,7 +41,7 @@ namespace MediaBrowser.Providers.TV
RemoveObsoleteEpisodes(item);
RemoveObsoleteSeasons(item);
- await FillInMissingSeasonsAsync(item, cancellationToken).ConfigureAwait(false);
+ await UpdateAndCreateSeasonsAsync(item, cancellationToken).ConfigureAwait(false);
}
///
@@ -67,6 +67,24 @@ namespace MediaBrowser.Providers.TV
var sourceItem = source.Item;
var targetItem = target.Item;
+ var sourceSeasonNames = sourceItem.SeasonNames;
+ var targetSeasonNames = targetItem.SeasonNames;
+
+ if (replaceData || targetSeasonNames.Count == 0)
+ {
+ targetItem.SeasonNames = sourceSeasonNames;
+ }
+ else if (targetSeasonNames.Count != sourceSeasonNames.Count || !sourceSeasonNames.Keys.All(targetSeasonNames.ContainsKey))
+ {
+ foreach (var season in sourceSeasonNames)
+ {
+ var seasonNumber = season.Key;
+ if (!targetSeasonNames.ContainsKey(seasonNumber))
+ {
+ targetItem.SeasonNames[seasonNumber] = season.Value;
+ }
+ }
+ }
if (replaceData || string.IsNullOrEmpty(targetItem.AirTime))
{
@@ -86,7 +104,7 @@ namespace MediaBrowser.Providers.TV
private void RemoveObsoleteSeasons(Series series)
{
- // TODO Legacy. It's not really "physical" seasons as any virtual seasons are always converted to non-virtual in FillInMissingSeasonsAsync.
+ // TODO Legacy. It's not really "physical" seasons as any virtual seasons are always converted to non-virtual in UpdateAndCreateSeasonsAsync.
var physicalSeasonNumbers = new HashSet();
var virtualSeasons = new List();
foreach (var existingSeason in series.Children.OfType())
@@ -177,36 +195,43 @@ namespace MediaBrowser.Providers.TV
}
///
- /// Creates seasons for all episodes that aren't in a season folder.
+ /// Creates seasons for all episodes if they don't exist.
/// If no season number can be determined, a dummy season will be created.
+ /// Updates seasons names.
///
/// The series.
/// The cancellation token.
/// The async task.
- private async Task FillInMissingSeasonsAsync(Series series, CancellationToken cancellationToken)
+ private async Task UpdateAndCreateSeasonsAsync(Series series, CancellationToken cancellationToken)
{
+ var seasonNames = series.SeasonNames;
var seriesChildren = series.GetRecursiveChildren(i => i is Episode || i is Season);
- var episodesInSeriesFolder = seriesChildren
+ var seasons = seriesChildren.OfType().ToList();
+ var uniqueSeasonNumbers = seriesChildren
.OfType()
- .Where(i => !i.IsInSeasonFolder);
-
- List seasons = seriesChildren.OfType().ToList();
+ .Select(e => e.ParentIndexNumber >= 0 ? e.ParentIndexNumber : null)
+ .Distinct();
// Loop through the unique season numbers
- foreach (var episode in episodesInSeriesFolder)
+ foreach (var seasonNumber in uniqueSeasonNumbers)
{
// Null season numbers will have a 'dummy' season created because seasons are always required.
- var seasonNumber = episode.ParentIndexNumber >= 0 ? episode.ParentIndexNumber : null;
var existingSeason = seasons.FirstOrDefault(i => i.IndexNumber == seasonNumber);
+ string? seasonName = null;
+
+ if (seasonNumber.HasValue && seasonNames.ContainsKey(seasonNumber.Value))
+ {
+ seasonName = seasonNames[seasonNumber.Value];
+ }
if (existingSeason is null)
{
- var season = await CreateSeasonAsync(series, seasonNumber, cancellationToken).ConfigureAwait(false);
- seasons.Add(season);
+ var season = await CreateSeasonAsync(series, seasonName, seasonNumber, cancellationToken).ConfigureAwait(false);
+ series.AddChild(season);
}
- else if (existingSeason.IsVirtualItem)
+ else
{
- existingSeason.IsVirtualItem = false;
+ existingSeason.Name = GetValidSeasonNameForSeries(series, seasonName, seasonNumber);
await existingSeason.UpdateToRepositoryAsync(ItemUpdateType.MetadataEdit, cancellationToken).ConfigureAwait(false);
}
}
@@ -216,21 +241,17 @@ namespace MediaBrowser.Providers.TV
/// Creates a new season, adds it to the database by linking it to the [series] and refreshes the metadata.
///
/// The series.
+ /// The season name.
/// The season number.
/// The cancellation token.
/// The newly created season.
private async Task CreateSeasonAsync(
Series series,
+ string? seasonName,
int? seasonNumber,
CancellationToken cancellationToken)
{
- string seasonName = seasonNumber switch
- {
- null => _localizationManager.GetLocalizedString("NameSeasonUnknown"),
- 0 => LibraryManager.GetLibraryOptions(series).SeasonZeroDisplayName,
- _ => string.Format(CultureInfo.InvariantCulture, _localizationManager.GetLocalizedString("NameSeasonNumber"), seasonNumber.Value)
- };
-
+ seasonName = GetValidSeasonNameForSeries(series, seasonName, seasonNumber);
Logger.LogInformation("Creating Season {SeasonName} entry for {SeriesName}", seasonName, series.Name);
var season = new Season
@@ -251,5 +272,20 @@ namespace MediaBrowser.Providers.TV
return season;
}
+
+ private string GetValidSeasonNameForSeries(Series series, string? seasonName, int? seasonNumber)
+ {
+ if (string.IsNullOrEmpty(seasonName))
+ {
+ seasonName = seasonNumber switch
+ {
+ null => _localizationManager.GetLocalizedString("NameSeasonUnknown"),
+ 0 => LibraryManager.GetLibraryOptions(series).SeasonZeroDisplayName,
+ _ => string.Format(CultureInfo.InvariantCulture, _localizationManager.GetLocalizedString("NameSeasonNumber"), seasonNumber.Value)
+ };
+ }
+
+ return seasonName;
+ }
}
}
diff --git a/MediaBrowser.XbmcMetadata/Parsers/SeasonNfoParser.cs b/MediaBrowser.XbmcMetadata/Parsers/SeasonNfoParser.cs
index 2f5fd40e2f..51d5f932bc 100644
--- a/MediaBrowser.XbmcMetadata/Parsers/SeasonNfoParser.cs
+++ b/MediaBrowser.XbmcMetadata/Parsers/SeasonNfoParser.cs
@@ -55,6 +55,18 @@ namespace MediaBrowser.XbmcMetadata.Parsers
break;
}
+ case "seasonname":
+ {
+ var name = reader.ReadElementContentAsString();
+
+ if (!string.IsNullOrWhiteSpace(name))
+ {
+ item.Name = name;
+ }
+
+ break;
+ }
+
default:
base.FetchDataFromXmlNode(reader, itemResult);
break;
diff --git a/MediaBrowser.XbmcMetadata/Parsers/SeriesNfoParser.cs b/MediaBrowser.XbmcMetadata/Parsers/SeriesNfoParser.cs
index 3011d65a6d..f22b861eba 100644
--- a/MediaBrowser.XbmcMetadata/Parsers/SeriesNfoParser.cs
+++ b/MediaBrowser.XbmcMetadata/Parsers/SeriesNfoParser.cs
@@ -1,4 +1,6 @@
using System;
+using System.Collections.Generic;
+using System.Globalization;
using System.Xml;
using MediaBrowser.Common.Configuration;
using MediaBrowser.Controller.Entities.TV;
@@ -110,6 +112,19 @@ namespace MediaBrowser.XbmcMetadata.Parsers
break;
}
+ case "namedseason":
+ {
+ var parsed = int.TryParse(reader.GetAttribute("number"), NumberStyles.Integer, CultureInfo.InvariantCulture, out var seasonNumber);
+ var name = reader.ReadElementContentAsString();
+
+ if (!string.IsNullOrWhiteSpace(name) && parsed)
+ {
+ item.SeasonNames[seasonNumber] = name;
+ }
+
+ break;
+ }
+
default:
base.FetchDataFromXmlNode(reader, itemResult);
break;
From a496da24e3bebe66e5ed6d61a7cd1d51311d4c48 Mon Sep 17 00:00:00 2001
From: Shadowghost
Date: Sun, 21 May 2023 13:52:43 +0200
Subject: [PATCH 09/21] Apply suggestions from code review
Co-authored-by: Bond-009
---
MediaBrowser.Providers/TV/SeriesMetadataService.cs | 9 +++------
1 file changed, 3 insertions(+), 6 deletions(-)
diff --git a/MediaBrowser.Providers/TV/SeriesMetadataService.cs b/MediaBrowser.Providers/TV/SeriesMetadataService.cs
index b99f1cbdbf..85e2481147 100644
--- a/MediaBrowser.Providers/TV/SeriesMetadataService.cs
+++ b/MediaBrowser.Providers/TV/SeriesMetadataService.cs
@@ -79,10 +79,7 @@ namespace MediaBrowser.Providers.TV
foreach (var season in sourceSeasonNames)
{
var seasonNumber = season.Key;
- if (!targetSeasonNames.ContainsKey(seasonNumber))
- {
- targetItem.SeasonNames[seasonNumber] = season.Value;
- }
+ targetSeasonNames.TryAdd(seasonNumber, season.Value);
}
}
@@ -219,9 +216,9 @@ namespace MediaBrowser.Providers.TV
var existingSeason = seasons.FirstOrDefault(i => i.IndexNumber == seasonNumber);
string? seasonName = null;
- if (seasonNumber.HasValue && seasonNames.ContainsKey(seasonNumber.Value))
+ if (seasonNumber.HasValue && seasonNames.TryGetValue(seasonNumber.Value, out var tmp))
{
- seasonName = seasonNames[seasonNumber.Value];
+ seasonName = tmp;
}
if (existingSeason is null)
From 40ca923a71e8edb6687d69feffd24497dec27845 Mon Sep 17 00:00:00 2001
From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com>
Date: Thu, 8 Jun 2023 09:11:25 +0000
Subject: [PATCH 10/21] chore(deps): update
peter-evans/create-or-update-comment action to v3.0.2
---
.github/workflows/commands.yml | 10 +++++-----
.github/workflows/openapi.yml | 4 ++--
2 files changed, 7 insertions(+), 7 deletions(-)
diff --git a/.github/workflows/commands.yml b/.github/workflows/commands.yml
index ae06c4141b..bad6f45edf 100644
--- a/.github/workflows/commands.yml
+++ b/.github/workflows/commands.yml
@@ -17,7 +17,7 @@ jobs:
runs-on: ubuntu-latest
steps:
- name: Notify as seen
- uses: peter-evans/create-or-update-comment@ca08ebd5dc95aa0cd97021e9708fcd6b87138c9b # v3.0.1
+ uses: peter-evans/create-or-update-comment@c6c9a1a66007646a28c153e2a8580a5bad27bcfa # v3.0.2
with:
token: ${{ secrets.JF_BOT_TOKEN }}
comment-id: ${{ github.event.comment.id }}
@@ -43,7 +43,7 @@ jobs:
runs-on: ubuntu-latest
steps:
- name: Notify as seen
- uses: peter-evans/create-or-update-comment@ca08ebd5dc95aa0cd97021e9708fcd6b87138c9b # v3.0.1
+ uses: peter-evans/create-or-update-comment@c6c9a1a66007646a28c153e2a8580a5bad27bcfa # v3.0.2
if: ${{ github.event.comment != null }}
with:
token: ${{ secrets.JF_BOT_TOKEN }}
@@ -58,7 +58,7 @@ jobs:
- name: Notify as running
id: comment_running
- uses: peter-evans/create-or-update-comment@ca08ebd5dc95aa0cd97021e9708fcd6b87138c9b # v3.0.1
+ uses: peter-evans/create-or-update-comment@c6c9a1a66007646a28c153e2a8580a5bad27bcfa # v3.0.2
if: ${{ github.event.comment != null }}
with:
token: ${{ secrets.JF_BOT_TOKEN }}
@@ -93,7 +93,7 @@ jobs:
exit ${retcode}
- name: Notify with result success
- uses: peter-evans/create-or-update-comment@ca08ebd5dc95aa0cd97021e9708fcd6b87138c9b # v3.0.1
+ uses: peter-evans/create-or-update-comment@c6c9a1a66007646a28c153e2a8580a5bad27bcfa # v3.0.2
if: ${{ github.event.comment != null && success() }}
with:
token: ${{ secrets.JF_BOT_TOKEN }}
@@ -108,7 +108,7 @@ jobs:
reactions: hooray
- name: Notify with result failure
- uses: peter-evans/create-or-update-comment@ca08ebd5dc95aa0cd97021e9708fcd6b87138c9b # v3.0.1
+ uses: peter-evans/create-or-update-comment@c6c9a1a66007646a28c153e2a8580a5bad27bcfa # v3.0.2
if: ${{ github.event.comment != null && failure() }}
with:
token: ${{ secrets.JF_BOT_TOKEN }}
diff --git a/.github/workflows/openapi.yml b/.github/workflows/openapi.yml
index 539da7aefe..e8d080e9ad 100644
--- a/.github/workflows/openapi.yml
+++ b/.github/workflows/openapi.yml
@@ -110,7 +110,7 @@ jobs:
direction: last
body-includes: openapi-diff-workflow-comment
- name: Reply or edit difference comment (changed)
- uses: peter-evans/create-or-update-comment@ca08ebd5dc95aa0cd97021e9708fcd6b87138c9b # v3.0.1
+ uses: peter-evans/create-or-update-comment@c6c9a1a66007646a28c153e2a8580a5bad27bcfa # v3.0.2
if: ${{ steps.read-diff.outputs.body != '' }}
with:
issue-number: ${{ github.event.pull_request.number }}
@@ -125,7 +125,7 @@ jobs:
- name: Edit difference comment (unchanged)
- uses: peter-evans/create-or-update-comment@ca08ebd5dc95aa0cd97021e9708fcd6b87138c9b # v3.0.1
+ uses: peter-evans/create-or-update-comment@c6c9a1a66007646a28c153e2a8580a5bad27bcfa # v3.0.2
if: ${{ steps.read-diff.outputs.body == '' && steps.find-comment.outputs.comment-id != '' }}
with:
issue-number: ${{ github.event.pull_request.number }}
From 1330bd0b52346de0b505e663b1f8cc4bc550295a Mon Sep 17 00:00:00 2001
From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com>
Date: Sat, 10 Jun 2023 06:55:15 -0600
Subject: [PATCH 11/21] chore(deps): update actions/checkout action to v3.5.3
(#9876)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
---
.github/workflows/codeql-analysis.yml | 2 +-
.github/workflows/commands.yml | 4 ++--
.github/workflows/openapi.yml | 4 ++--
3 files changed, 5 insertions(+), 5 deletions(-)
diff --git a/.github/workflows/codeql-analysis.yml b/.github/workflows/codeql-analysis.yml
index d03d44a1ca..9f1be02327 100644
--- a/.github/workflows/codeql-analysis.yml
+++ b/.github/workflows/codeql-analysis.yml
@@ -20,7 +20,7 @@ jobs:
steps:
- name: Checkout repository
- uses: actions/checkout@8e5e7e5ab8b370d6c329ec480221332ada57f0ab # v3.5.2
+ uses: actions/checkout@c85c95e3d7251135ab7dc9ce3241c5835cc595a9 # v3.5.3
- name: Setup .NET
uses: actions/setup-dotnet@3447fd6a9f9e57506b15f895c5b76d3b197dc7c2 # v3.2.0
with:
diff --git a/.github/workflows/commands.yml b/.github/workflows/commands.yml
index bad6f45edf..178959afc9 100644
--- a/.github/workflows/commands.yml
+++ b/.github/workflows/commands.yml
@@ -24,7 +24,7 @@ jobs:
reactions: '+1'
- name: Checkout the latest code
- uses: actions/checkout@8e5e7e5ab8b370d6c329ec480221332ada57f0ab # v3.5.2
+ uses: actions/checkout@c85c95e3d7251135ab7dc9ce3241c5835cc595a9 # v3.5.3
with:
token: ${{ secrets.JF_BOT_TOKEN }}
fetch-depth: 0
@@ -51,7 +51,7 @@ jobs:
reactions: eyes
- name: Checkout the latest code
- uses: actions/checkout@8e5e7e5ab8b370d6c329ec480221332ada57f0ab # v3.5.2
+ uses: actions/checkout@c85c95e3d7251135ab7dc9ce3241c5835cc595a9 # v3.5.3
with:
token: ${{ secrets.JF_BOT_TOKEN }}
fetch-depth: 0
diff --git a/.github/workflows/openapi.yml b/.github/workflows/openapi.yml
index e8d080e9ad..ad1cedd52e 100644
--- a/.github/workflows/openapi.yml
+++ b/.github/workflows/openapi.yml
@@ -14,7 +14,7 @@ jobs:
permissions: read-all
steps:
- name: Checkout repository
- uses: actions/checkout@8e5e7e5ab8b370d6c329ec480221332ada57f0ab # v3.5.2
+ uses: actions/checkout@c85c95e3d7251135ab7dc9ce3241c5835cc595a9 # v3.5.3
with:
ref: ${{ github.event.pull_request.head.sha }}
repository: ${{ github.event.pull_request.head.repo.full_name }}
@@ -39,7 +39,7 @@ jobs:
permissions: read-all
steps:
- name: Checkout repository
- uses: actions/checkout@8e5e7e5ab8b370d6c329ec480221332ada57f0ab # v3.5.2
+ uses: actions/checkout@c85c95e3d7251135ab7dc9ce3241c5835cc595a9 # v3.5.3
with:
ref: ${{ github.event.pull_request.head.sha }}
repository: ${{ github.event.pull_request.head.repo.full_name }}
From a5005e3d01fe98364fd3449e8778bc3370ad0e65 Mon Sep 17 00:00:00 2001
From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com>
Date: Sat, 10 Jun 2023 07:01:34 -0600
Subject: [PATCH 12/21] chore(deps): update dependency serilog.sinks.graylog to
v3 (#9867)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
---
Directory.Packages.props | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/Directory.Packages.props b/Directory.Packages.props
index 64827256ce..49081399e1 100644
--- a/Directory.Packages.props
+++ b/Directory.Packages.props
@@ -62,7 +62,7 @@
-
+
From 898bb955641e9ddfe5347d4406960f363b100eac Mon Sep 17 00:00:00 2001
From: Bond-009
Date: Sat, 10 Jun 2023 15:01:47 +0200
Subject: [PATCH 13/21] Fix InvalidOpEx while trying to read
HttpResponseContent 2x (#9861)
---
Emby.Dlna/PlayTo/DlnaHttpClient.cs | 14 +++++++++-----
1 file changed, 9 insertions(+), 5 deletions(-)
diff --git a/Emby.Dlna/PlayTo/DlnaHttpClient.cs b/Emby.Dlna/PlayTo/DlnaHttpClient.cs
index 4e9903f26a..8b983e9e3d 100644
--- a/Emby.Dlna/PlayTo/DlnaHttpClient.cs
+++ b/Emby.Dlna/PlayTo/DlnaHttpClient.cs
@@ -49,20 +49,24 @@ namespace Emby.Dlna.PlayTo
private async Task SendRequestAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
- using var response = await _httpClientFactory.CreateClient(NamedClient.Dlna).SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false);
+ var client = _httpClientFactory.CreateClient(NamedClient.Dlna);
+ using var response = await client.SendAsync(request, cancellationToken).ConfigureAwait(false);
response.EnsureSuccessStatusCode();
- await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
+ await using MemoryStream ms = new MemoryStream();
+ await response.Content.CopyToAsync(ms, cancellationToken).ConfigureAwait(false);
try
{
return await XDocument.LoadAsync(
- stream,
+ ms,
LoadOptions.None,
cancellationToken).ConfigureAwait(false);
}
catch (XmlException)
{
// try correcting the Xml response with common errors
- var xmlString = await response.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false);
+ ms.Position = 0;
+ using StreamReader sr = new StreamReader(ms);
+ var xmlString = await sr.ReadToEndAsync(cancellationToken).ConfigureAwait(false);
// find and replace unescaped ampersands (&)
xmlString = EscapeAmpersandRegex().Replace(xmlString, "&");
@@ -70,7 +74,7 @@ namespace Emby.Dlna.PlayTo
try
{
// retry reading Xml
- var xmlReader = new StringReader(xmlString);
+ using var xmlReader = new StringReader(xmlString);
return await XDocument.LoadAsync(
xmlReader,
LoadOptions.None,
From 198b9aa5300236d2eb02310702b2333085d0b796 Mon Sep 17 00:00:00 2001
From: Cody Robibero
Date: Sat, 10 Jun 2023 07:04:23 -0600
Subject: [PATCH 14/21] Update
MediaBrowser.Providers/TV/SeriesMetadataService.cs
Co-authored-by: Bond-009
---
MediaBrowser.Providers/TV/SeriesMetadataService.cs | 5 ++---
1 file changed, 2 insertions(+), 3 deletions(-)
diff --git a/MediaBrowser.Providers/TV/SeriesMetadataService.cs b/MediaBrowser.Providers/TV/SeriesMetadataService.cs
index 85e2481147..9016e5de0c 100644
--- a/MediaBrowser.Providers/TV/SeriesMetadataService.cs
+++ b/MediaBrowser.Providers/TV/SeriesMetadataService.cs
@@ -76,10 +76,9 @@ namespace MediaBrowser.Providers.TV
}
else if (targetSeasonNames.Count != sourceSeasonNames.Count || !sourceSeasonNames.Keys.All(targetSeasonNames.ContainsKey))
{
- foreach (var season in sourceSeasonNames)
+ foreach (var (number, name) in sourceSeasonNames)
{
- var seasonNumber = season.Key;
- targetSeasonNames.TryAdd(seasonNumber, season.Value);
+ targetSeasonNames.TryAdd(number, name);
}
}
From 9a0dfc00f1e36092476f62984ba66886032f4f89 Mon Sep 17 00:00:00 2001
From: Cody Robibero
Date: Sat, 10 Jun 2023 07:28:21 -0600
Subject: [PATCH 15/21] Add all websocket messages to generated openapi spec
(#9682)
* Add all websocket messages to generated openapi spec
* Use oneOf
* JsonIgnore ServerId
* Oops
* Add discriminators
* Add WebSocketMessage container for Inbound and Outbound messages
---
.../Filters/AdditionalModelFilter.cs | 148 ++++++++++++++++--
.../Net/WebSocketMessage.cs | 28 ++++
.../Net/WebSocketMessageOfT.cs | 33 ++++
.../IInboundWebSocketMessage.cs | 10 ++
.../IOutboundWebSocketMessage.cs | 10 ++
.../Inbound/ActivityLogEntryStartMessage.cs | 25 +++
.../Inbound/ActivityLogEntryStopMessage.cs | 25 +++
.../Inbound/ScheduledTasksInfoStartMessage.cs | 25 +++
.../Inbound/ScheduledTasksInfoStopMessage.cs | 25 +++
.../Inbound/SessionsStartMessage.cs | 24 +++
.../Inbound/SessionsStopMessage.cs | 24 +++
.../InboundWebSocketMessage.cs | 9 ++
.../Outbound/ActivityLogEntryMessage.cs | 25 +++
.../Outbound/ForceKeepAliveMessage.cs | 23 +++
.../Outbound/GeneralCommandMessage.cs | 23 +++
.../Outbound/LibraryChangedMessage.cs | 24 +++
.../WebSocketMessages/Outbound/PlayMessage.cs | 23 +++
.../Outbound/PlaystateMessage.cs | 23 +++
.../PluginInstallationCancelledMessage.cs | 24 +++
.../PluginInstallationCompletedMessage.cs | 24 +++
.../PluginInstallationFailedMessage.cs | 24 +++
.../Outbound/PluginInstallingMessage.cs | 24 +++
.../Outbound/PluginUninstalledMessage.cs | 24 +++
.../Outbound/RefreshProgressMessage.cs | 24 +++
.../Outbound/RestartRequiredMessage.cs | 14 ++
.../Outbound/ScheduledTaskEndedMessage.cs | 24 +++
.../Outbound/ScheduledTasksInfoMessage.cs | 25 +++
.../Outbound/SeriesTimerCancelledMessage.cs | 24 +++
.../Outbound/SeriesTimerCreatedMessage.cs | 24 +++
.../Outbound/ServerRestartingMessage.cs | 14 ++
.../Outbound/ServerShuttingDownMessage.cs | 14 ++
.../Outbound/SessionsMessage.cs | 24 +++
.../Outbound/SyncPlayCommandMessage.cs | 24 +++
.../SyncPlayGroupUpdateCommandMessage.cs | 24 +++
...layGroupUpdateCommandOfGroupInfoMessage.cs | 25 +++
...pUpdateCommandOfGroupStateUpdateMessage.cs | 25 +++
...upUpdateCommandOfPlayQueueUpdateMessage.cs | 25 +++
...ncPlayGroupUpdateCommandOfStringMessage.cs | 25 +++
.../Outbound/TimerCancelledMessage.cs | 24 +++
.../Outbound/TimerCreatedMessage.cs | 24 +++
.../Outbound/UserDataChangedMessage.cs | 23 +++
.../Outbound/UserDeletedMessage.cs | 24 +++
.../Outbound/UserUpdatedMessage.cs | 24 +++
.../OutboundWebSocketMessage.cs | 9 ++
.../Shared/KeepAliveMessage.cs | 23 +++
.../SyncPlay/Queue/PlayQueueManager.cs | 24 +--
MediaBrowser.Model/Net/WebSocketMessage.cs | 31 ----
MediaBrowser.Model/SyncPlay/GroupUpdate.cs | 54 +++----
MediaBrowser.Model/SyncPlay/GroupUpdateOfT.cs | 31 ++++
.../SyncPlay/PlayQueueUpdate.cs | 4 +-
.../{QueueItem.cs => SyncPlayQueueItem.cs} | 6 +-
51 files changed, 1192 insertions(+), 91 deletions(-)
create mode 100644 MediaBrowser.Controller/Net/WebSocketMessage.cs
create mode 100644 MediaBrowser.Controller/Net/WebSocketMessageOfT.cs
create mode 100644 MediaBrowser.Controller/Net/WebSocketMessages/IInboundWebSocketMessage.cs
create mode 100644 MediaBrowser.Controller/Net/WebSocketMessages/IOutboundWebSocketMessage.cs
create mode 100644 MediaBrowser.Controller/Net/WebSocketMessages/Inbound/ActivityLogEntryStartMessage.cs
create mode 100644 MediaBrowser.Controller/Net/WebSocketMessages/Inbound/ActivityLogEntryStopMessage.cs
create mode 100644 MediaBrowser.Controller/Net/WebSocketMessages/Inbound/ScheduledTasksInfoStartMessage.cs
create mode 100644 MediaBrowser.Controller/Net/WebSocketMessages/Inbound/ScheduledTasksInfoStopMessage.cs
create mode 100644 MediaBrowser.Controller/Net/WebSocketMessages/Inbound/SessionsStartMessage.cs
create mode 100644 MediaBrowser.Controller/Net/WebSocketMessages/Inbound/SessionsStopMessage.cs
create mode 100644 MediaBrowser.Controller/Net/WebSocketMessages/InboundWebSocketMessage.cs
create mode 100644 MediaBrowser.Controller/Net/WebSocketMessages/Outbound/ActivityLogEntryMessage.cs
create mode 100644 MediaBrowser.Controller/Net/WebSocketMessages/Outbound/ForceKeepAliveMessage.cs
create mode 100644 MediaBrowser.Controller/Net/WebSocketMessages/Outbound/GeneralCommandMessage.cs
create mode 100644 MediaBrowser.Controller/Net/WebSocketMessages/Outbound/LibraryChangedMessage.cs
create mode 100644 MediaBrowser.Controller/Net/WebSocketMessages/Outbound/PlayMessage.cs
create mode 100644 MediaBrowser.Controller/Net/WebSocketMessages/Outbound/PlaystateMessage.cs
create mode 100644 MediaBrowser.Controller/Net/WebSocketMessages/Outbound/PluginInstallationCancelledMessage.cs
create mode 100644 MediaBrowser.Controller/Net/WebSocketMessages/Outbound/PluginInstallationCompletedMessage.cs
create mode 100644 MediaBrowser.Controller/Net/WebSocketMessages/Outbound/PluginInstallationFailedMessage.cs
create mode 100644 MediaBrowser.Controller/Net/WebSocketMessages/Outbound/PluginInstallingMessage.cs
create mode 100644 MediaBrowser.Controller/Net/WebSocketMessages/Outbound/PluginUninstalledMessage.cs
create mode 100644 MediaBrowser.Controller/Net/WebSocketMessages/Outbound/RefreshProgressMessage.cs
create mode 100644 MediaBrowser.Controller/Net/WebSocketMessages/Outbound/RestartRequiredMessage.cs
create mode 100644 MediaBrowser.Controller/Net/WebSocketMessages/Outbound/ScheduledTaskEndedMessage.cs
create mode 100644 MediaBrowser.Controller/Net/WebSocketMessages/Outbound/ScheduledTasksInfoMessage.cs
create mode 100644 MediaBrowser.Controller/Net/WebSocketMessages/Outbound/SeriesTimerCancelledMessage.cs
create mode 100644 MediaBrowser.Controller/Net/WebSocketMessages/Outbound/SeriesTimerCreatedMessage.cs
create mode 100644 MediaBrowser.Controller/Net/WebSocketMessages/Outbound/ServerRestartingMessage.cs
create mode 100644 MediaBrowser.Controller/Net/WebSocketMessages/Outbound/ServerShuttingDownMessage.cs
create mode 100644 MediaBrowser.Controller/Net/WebSocketMessages/Outbound/SessionsMessage.cs
create mode 100644 MediaBrowser.Controller/Net/WebSocketMessages/Outbound/SyncPlayCommandMessage.cs
create mode 100644 MediaBrowser.Controller/Net/WebSocketMessages/Outbound/SyncPlayGroupUpdateCommandMessage.cs
create mode 100644 MediaBrowser.Controller/Net/WebSocketMessages/Outbound/SyncPlayGroupUpdateCommandOfGroupInfoMessage.cs
create mode 100644 MediaBrowser.Controller/Net/WebSocketMessages/Outbound/SyncPlayGroupUpdateCommandOfGroupStateUpdateMessage.cs
create mode 100644 MediaBrowser.Controller/Net/WebSocketMessages/Outbound/SyncPlayGroupUpdateCommandOfPlayQueueUpdateMessage.cs
create mode 100644 MediaBrowser.Controller/Net/WebSocketMessages/Outbound/SyncPlayGroupUpdateCommandOfStringMessage.cs
create mode 100644 MediaBrowser.Controller/Net/WebSocketMessages/Outbound/TimerCancelledMessage.cs
create mode 100644 MediaBrowser.Controller/Net/WebSocketMessages/Outbound/TimerCreatedMessage.cs
create mode 100644 MediaBrowser.Controller/Net/WebSocketMessages/Outbound/UserDataChangedMessage.cs
create mode 100644 MediaBrowser.Controller/Net/WebSocketMessages/Outbound/UserDeletedMessage.cs
create mode 100644 MediaBrowser.Controller/Net/WebSocketMessages/Outbound/UserUpdatedMessage.cs
create mode 100644 MediaBrowser.Controller/Net/WebSocketMessages/OutboundWebSocketMessage.cs
create mode 100644 MediaBrowser.Controller/Net/WebSocketMessages/Shared/KeepAliveMessage.cs
delete mode 100644 MediaBrowser.Model/Net/WebSocketMessage.cs
create mode 100644 MediaBrowser.Model/SyncPlay/GroupUpdateOfT.cs
rename MediaBrowser.Model/SyncPlay/{QueueItem.cs => SyncPlayQueueItem.cs} (80%)
diff --git a/Jellyfin.Server/Filters/AdditionalModelFilter.cs b/Jellyfin.Server/Filters/AdditionalModelFilter.cs
index 645696e319..bf38f741cd 100644
--- a/Jellyfin.Server/Filters/AdditionalModelFilter.cs
+++ b/Jellyfin.Server/Filters/AdditionalModelFilter.cs
@@ -1,12 +1,16 @@
using System;
+using System.Collections.Generic;
+using System.ComponentModel;
using System.Linq;
+using System.Reflection;
using Jellyfin.Extensions;
using Jellyfin.Server.Migrations;
using MediaBrowser.Common.Plugins;
using MediaBrowser.Controller.Configuration;
-using MediaBrowser.Controller.LiveTv;
+using MediaBrowser.Controller.Net;
+using MediaBrowser.Controller.Net.WebSocketMessages;
+using MediaBrowser.Controller.Net.WebSocketMessages.Outbound;
using MediaBrowser.Model.ApiClient;
-using MediaBrowser.Model.Entities;
using MediaBrowser.Model.Session;
using MediaBrowser.Model.SyncPlay;
using Microsoft.OpenApi.Any;
@@ -36,17 +40,141 @@ namespace Jellyfin.Server.Filters
///
public void Apply(OpenApiDocument swaggerDoc, DocumentFilterContext context)
{
- context.SchemaGenerator.GenerateSchema(typeof(LibraryUpdateInfo), context.SchemaRepository);
context.SchemaGenerator.GenerateSchema(typeof(IPlugin), context.SchemaRepository);
- context.SchemaGenerator.GenerateSchema(typeof(PlayRequest), context.SchemaRepository);
- context.SchemaGenerator.GenerateSchema(typeof(PlaystateRequest), context.SchemaRepository);
- context.SchemaGenerator.GenerateSchema(typeof(TimerEventInfo), context.SchemaRepository);
- context.SchemaGenerator.GenerateSchema(typeof(SendCommand), context.SchemaRepository);
- context.SchemaGenerator.GenerateSchema(typeof(GeneralCommandType), context.SchemaRepository);
- context.SchemaGenerator.GenerateSchema(typeof(GroupUpdate
/// The sorted playlist, or play queue of the group.
- private List _sortedPlaylist = new List();
+ private List _sortedPlaylist = new List();
///
/// The shuffled playlist.
///
/// The shuffled playlist, or play queue of the group.
- private List _shuffledPlaylist = new List();
+ private List _shuffledPlaylist = new List();
///
/// Initializes a new instance of the class.
@@ -76,7 +76,7 @@ namespace MediaBrowser.Controller.SyncPlay.Queue
/// Gets the current playlist considering the shuffle mode.
///
/// The playlist.
- public IReadOnlyList GetPlaylist()
+ public IReadOnlyList GetPlaylist()
{
return GetPlaylistInternal();
}
@@ -93,7 +93,7 @@ namespace MediaBrowser.Controller.SyncPlay.Queue
_sortedPlaylist = CreateQueueItemsFromArray(items);
if (ShuffleMode.Equals(GroupShuffleMode.Shuffle))
{
- _shuffledPlaylist = new List(_sortedPlaylist);
+ _shuffledPlaylist = new List(_sortedPlaylist);
_shuffledPlaylist.Shuffle();
}
@@ -125,14 +125,14 @@ namespace MediaBrowser.Controller.SyncPlay.Queue
{
if (PlayingItemIndex == NoPlayingItemIndex)
{
- _shuffledPlaylist = new List(_sortedPlaylist);
+ _shuffledPlaylist = new List(_sortedPlaylist);
_shuffledPlaylist.Shuffle();
}
else if (ShuffleMode.Equals(GroupShuffleMode.Sorted))
{
// First time shuffle.
var playingItem = _sortedPlaylist[PlayingItemIndex];
- _shuffledPlaylist = new List(_sortedPlaylist);
+ _shuffledPlaylist = new List(_sortedPlaylist);
_shuffledPlaylist.RemoveAt(PlayingItemIndex);
_shuffledPlaylist.Shuffle();
_shuffledPlaylist.Insert(0, playingItem);
@@ -407,7 +407,7 @@ namespace MediaBrowser.Controller.SyncPlay.Queue
/// Gets the next item in the playlist considering repeat mode and shuffle mode.
///
/// The next item in the playlist.
- public QueueItem GetNextItemPlaylistId()
+ public SyncPlayQueueItem GetNextItemPlaylistId()
{
int newIndex;
var playlist = GetPlaylistInternal();
@@ -502,12 +502,12 @@ namespace MediaBrowser.Controller.SyncPlay.Queue
/// Creates a list from the array of items. Each item is given an unique playlist identifier.
///
/// The list of queue items.
- private List CreateQueueItemsFromArray(IReadOnlyList items)
+ private List CreateQueueItemsFromArray(IReadOnlyList items)
{
- var list = new List();
+ var list = new List();
foreach (var item in items)
{
- var queueItem = new QueueItem(item);
+ var queueItem = new SyncPlayQueueItem(item);
list.Add(queueItem);
}
@@ -518,7 +518,7 @@ namespace MediaBrowser.Controller.SyncPlay.Queue
/// Gets the current playlist considering the shuffle mode.
///
/// The playlist.
- private List GetPlaylistInternal()
+ private List GetPlaylistInternal()
{
if (ShuffleMode.Equals(GroupShuffleMode.Shuffle))
{
@@ -532,7 +532,7 @@ namespace MediaBrowser.Controller.SyncPlay.Queue
/// Gets the current playing item, depending on the shuffle mode.
///
/// The playing item.
- private QueueItem GetPlayingItem()
+ private SyncPlayQueueItem GetPlayingItem()
{
if (PlayingItemIndex == NoPlayingItemIndex)
{
diff --git a/MediaBrowser.Model/Net/WebSocketMessage.cs b/MediaBrowser.Model/Net/WebSocketMessage.cs
deleted file mode 100644
index b00158cb33..0000000000
--- a/MediaBrowser.Model/Net/WebSocketMessage.cs
+++ /dev/null
@@ -1,31 +0,0 @@
-#nullable disable
-#pragma warning disable CS1591
-
-using System;
-using MediaBrowser.Model.Session;
-
-namespace MediaBrowser.Model.Net
-{
- ///
- /// Class WebSocketMessage.
- ///
- /// The type of the data.
- public class WebSocketMessage
- {
- ///
- /// Gets or sets the type of the message.
- ///
- /// The type of the message.
- public SessionMessageType MessageType { get; set; }
-
- public Guid MessageId { get; set; }
-
- public string ServerId { get; set; }
-
- ///
- /// Gets or sets the data.
- ///
- /// The data.
- public T Data { get; set; }
- }
-}
diff --git a/MediaBrowser.Model/SyncPlay/GroupUpdate.cs b/MediaBrowser.Model/SyncPlay/GroupUpdate.cs
index 6f159d653c..ec67d7ea87 100644
--- a/MediaBrowser.Model/SyncPlay/GroupUpdate.cs
+++ b/MediaBrowser.Model/SyncPlay/GroupUpdate.cs
@@ -1,42 +1,30 @@
using System;
-namespace MediaBrowser.Model.SyncPlay
+namespace MediaBrowser.Model.SyncPlay;
+
+///
+/// Group update without data.
+///
+public abstract class GroupUpdate
{
///
- /// Class GroupUpdate.
+ /// Initializes a new instance of the class.
///
- /// The type of the data of the message.
- public class GroupUpdate
+ /// The group identifier.
+ protected GroupUpdate(Guid groupId)
{
- ///
- /// Initializes a new instance of the class.
- ///
- /// The group identifier.
- /// The update type.
- /// The update data.
- public GroupUpdate(Guid groupId, GroupUpdateType type, T data)
- {
- GroupId = groupId;
- Type = type;
- Data = data;
- }
-
- ///
- /// Gets the group identifier.
- ///
- /// The group identifier.
- public Guid GroupId { get; }
+ GroupId = groupId;
+ }
- ///
- /// Gets the update type.
- ///
- /// The update type.
- public GroupUpdateType Type { get; }
+ ///
+ /// Gets the group identifier.
+ ///
+ /// The group identifier.
+ public Guid GroupId { get; }
- ///
- /// Gets the update data.
- ///
- /// The update data.
- public T Data { get; }
- }
+ ///
+ /// Gets the update type.
+ ///
+ /// The update type.
+ public GroupUpdateType Type { get; init; }
}
diff --git a/MediaBrowser.Model/SyncPlay/GroupUpdateOfT.cs b/MediaBrowser.Model/SyncPlay/GroupUpdateOfT.cs
new file mode 100644
index 0000000000..25cd444611
--- /dev/null
+++ b/MediaBrowser.Model/SyncPlay/GroupUpdateOfT.cs
@@ -0,0 +1,31 @@
+#pragma warning disable SA1649
+
+using System;
+
+namespace MediaBrowser.Model.SyncPlay;
+
+///
+/// Class GroupUpdate.
+///
+/// The type of the data of the message.
+public class GroupUpdate : GroupUpdate
+{
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// The group identifier.
+ /// The update type.
+ /// The update data.
+ public GroupUpdate(Guid groupId, GroupUpdateType type, T data)
+ : base(groupId)
+ {
+ Data = data;
+ Type = type;
+ }
+
+ ///
+ /// Gets the update data.
+ ///
+ /// The update data.
+ public T Data { get; }
+}
diff --git a/MediaBrowser.Model/SyncPlay/PlayQueueUpdate.cs b/MediaBrowser.Model/SyncPlay/PlayQueueUpdate.cs
index cce99c77d5..376d926c9a 100644
--- a/MediaBrowser.Model/SyncPlay/PlayQueueUpdate.cs
+++ b/MediaBrowser.Model/SyncPlay/PlayQueueUpdate.cs
@@ -19,7 +19,7 @@ namespace MediaBrowser.Model.SyncPlay
/// The playing item status.
/// The shuffle mode.
/// The repeat mode.
- public PlayQueueUpdate(PlayQueueUpdateReason reason, DateTime lastUpdate, IReadOnlyList playlist, int playingItemIndex, long startPositionTicks, bool isPlaying, GroupShuffleMode shuffleMode, GroupRepeatMode repeatMode)
+ public PlayQueueUpdate(PlayQueueUpdateReason reason, DateTime lastUpdate, IReadOnlyList playlist, int playingItemIndex, long startPositionTicks, bool isPlaying, GroupShuffleMode shuffleMode, GroupRepeatMode repeatMode)
{
Reason = reason;
LastUpdate = lastUpdate;
@@ -47,7 +47,7 @@ namespace MediaBrowser.Model.SyncPlay
/// Gets the playlist.
///
/// The playlist.
- public IReadOnlyList Playlist { get; }
+ public IReadOnlyList Playlist { get; }
///
/// Gets the playing item index in the playlist.
diff --git a/MediaBrowser.Model/SyncPlay/QueueItem.cs b/MediaBrowser.Model/SyncPlay/SyncPlayQueueItem.cs
similarity index 80%
rename from MediaBrowser.Model/SyncPlay/QueueItem.cs
rename to MediaBrowser.Model/SyncPlay/SyncPlayQueueItem.cs
index a6dcc109ed..da81fecbdc 100644
--- a/MediaBrowser.Model/SyncPlay/QueueItem.cs
+++ b/MediaBrowser.Model/SyncPlay/SyncPlayQueueItem.cs
@@ -5,13 +5,13 @@ namespace MediaBrowser.Model.SyncPlay
///
/// Class QueueItem.
///
- public class QueueItem
+ public class SyncPlayQueueItem
{
///
- /// Initializes a new instance of the class.
+ /// Initializes a new instance of the class.
///
/// The item identifier.
- public QueueItem(Guid itemId)
+ public SyncPlayQueueItem(Guid itemId)
{
ItemId = itemId;
}
From ed88c8bd2d3b7d53d26e16386957e7bc13b7edd7 Mon Sep 17 00:00:00 2001
From: nyanmisaka
Date: Tue, 13 Jun 2023 10:44:06 -0400
Subject: [PATCH 16/21] Backport pull request #9411 from
jellyfin/release-10.8.z
Fix codec checking in CodecProfiles conditions
Original-merge: 5921379a29583804fd1e99d1aad81bd4aad7f019
Merged-by: Bond-009
Backported-by: Bond_009
---
MediaBrowser.Model/Dlna/StreamBuilder.cs | 19 ++++++++++++++-----
1 file changed, 14 insertions(+), 5 deletions(-)
diff --git a/MediaBrowser.Model/Dlna/StreamBuilder.cs b/MediaBrowser.Model/Dlna/StreamBuilder.cs
index df185e40c5..2d2086ac3a 100644
--- a/MediaBrowser.Model/Dlna/StreamBuilder.cs
+++ b/MediaBrowser.Model/Dlna/StreamBuilder.cs
@@ -757,8 +757,8 @@ namespace MediaBrowser.Model.Dlna
if (options.AllowVideoStreamCopy)
{
// prefer direct copy profile
- float videoFramerate = videoStream is null ? 0 : videoStream.AverageFrameRate ?? videoStream.AverageFrameRate ?? 0;
- TransportStreamTimestamp? timestamp = videoStream is null ? TransportStreamTimestamp.None : item.Timestamp;
+ float videoFramerate = videoStream?.AverageFrameRate ?? videoStream?.RealFrameRate ?? 0;
+ TransportStreamTimestamp? timestamp = videoStream == null ? TransportStreamTimestamp.None : item.Timestamp;
int? numAudioStreams = item.GetStreamCount(MediaStreamType.Audio);
int? numVideoStreams = item.GetStreamCount(MediaStreamType.Video);
@@ -772,6 +772,7 @@ namespace MediaBrowser.Model.Dlna
var container = transcodingProfile.Container;
var appliedVideoConditions = options.Profile.CodecProfiles
.Where(i => i.Type == CodecType.Video &&
+ (string.IsNullOrEmpty(i.Codec) || string.Equals(i.Codec, videoStream?.Codec, StringComparison.OrdinalIgnoreCase)) &&
i.ContainsAnyCodec(videoCodec, container) &&
i.ApplyConditions.All(applyCondition => ConditionProcessor.IsVideoConditionSatisfied(applyCondition, videoStream?.Width, videoStream?.Height, videoStream?.BitDepth, videoStream?.BitRate, videoStream?.Profile, videoStream?.VideoRangeType, videoStream?.Level, videoFramerate, videoStream?.PacketLength, timestamp, videoStream?.IsAnamorphic, videoStream?.IsInterlaced, videoStream?.RefFrames, numVideoStreams, numAudioStreams, videoStream?.CodecTag, videoStream?.IsAVC)))
.Select(i =>
@@ -905,6 +906,7 @@ namespace MediaBrowser.Model.Dlna
var appliedVideoConditions = options.Profile.CodecProfiles
.Where(i => i.Type == CodecType.Video &&
+ (string.IsNullOrEmpty(i.Codec) || string.Equals(i.Codec, videoStream?.Codec, StringComparison.OrdinalIgnoreCase)) &&
i.ContainsAnyCodec(videoCodec, container) &&
i.ApplyConditions.All(applyCondition => ConditionProcessor.IsVideoConditionSatisfied(applyCondition, width, height, bitDepth, videoBitrate, videoProfile, videoRangeType, videoLevel, videoFramerate, packetLength, timestamp, isAnamorphic, isInterlaced, refFrames, numVideoStreams, numAudioStreams, videoCodecTag, isAvc)));
var isFirstAppliedCodecProfile = true;
@@ -937,6 +939,7 @@ namespace MediaBrowser.Model.Dlna
var appliedAudioConditions = options.Profile.CodecProfiles
.Where(i => i.Type == CodecType.VideoAudio &&
+ (string.IsNullOrEmpty(i.Codec) || string.Equals(i.Codec, audioStream?.Codec, StringComparison.OrdinalIgnoreCase)) &&
i.ContainsAnyCodec(audioCodec, container) &&
i.ApplyConditions.All(applyCondition => ConditionProcessor.IsVideoAudioConditionSatisfied(applyCondition, audioChannels, inputAudioBitrate, inputAudioSampleRate, inputAudioBitDepth, audioProfile, isSecondaryAudio)));
isFirstAppliedCodecProfile = true;
@@ -1176,7 +1179,9 @@ namespace MediaBrowser.Model.Dlna
profile,
"VideoCodecProfile",
profile.CodecProfiles
- .Where(codecProfile => codecProfile.Type == CodecType.Video && codecProfile.ContainsAnyCodec(videoStream?.Codec, container) &&
+ .Where(codecProfile => codecProfile.Type == CodecType.Video &&
+ (string.IsNullOrEmpty(codecProfile.Codec) || string.Equals(codecProfile.Codec, videoStream?.Codec, StringComparison.OrdinalIgnoreCase)) &&
+ codecProfile.ContainsAnyCodec(videoStream?.Codec, container) &&
!checkVideoConditions(codecProfile.ApplyConditions).Any())
.SelectMany(codecProfile => checkVideoConditions(codecProfile.Conditions)));
@@ -1585,7 +1590,9 @@ namespace MediaBrowser.Model.Dlna
bool? isSecondaryAudio)
{
return codecProfiles
- .Where(profile => profile.Type == CodecType.VideoAudio && profile.ContainsAnyCodec(codec, container) &&
+ .Where(profile => profile.Type == CodecType.VideoAudio &&
+ (string.IsNullOrEmpty(profile.Codec) || string.Equals(profile.Codec, codec, StringComparison.OrdinalIgnoreCase)) &&
+ profile.ContainsAnyCodec(codec, container) &&
profile.ApplyConditions.All(applyCondition => ConditionProcessor.IsVideoAudioConditionSatisfied(applyCondition, audioChannels, audioBitrate, audioSampleRate, audioBitDepth, audioProfile, isSecondaryAudio)))
.SelectMany(profile => profile.Conditions)
.Where(condition => !ConditionProcessor.IsVideoAudioConditionSatisfied(condition, audioChannels, audioBitrate, audioSampleRate, audioBitDepth, audioProfile, isSecondaryAudio));
@@ -1602,7 +1609,9 @@ namespace MediaBrowser.Model.Dlna
bool checkConditions)
{
var conditions = codecProfiles
- .Where(profile => profile.Type == CodecType.Audio && profile.ContainsAnyCodec(codec, container) &&
+ .Where(profile => profile.Type == CodecType.Audio &&
+ (string.IsNullOrEmpty(profile.Codec) || string.Equals(profile.Codec, codec, StringComparison.OrdinalIgnoreCase)) &&
+ profile.ContainsAnyCodec(codec, container) &&
profile.ApplyConditions.All(applyCondition => ConditionProcessor.IsAudioConditionSatisfied(applyCondition, audioChannels, audioBitrate, audioSampleRate, audioBitDepth)))
.SelectMany(profile => profile.Conditions);
From 67bc81ec96dd7a3ef712907303aacb10b175cf56 Mon Sep 17 00:00:00 2001
From: TheTyrius <16269108+TheTyrius@users.noreply.github.com>
Date: Tue, 13 Jun 2023 10:44:06 -0400
Subject: [PATCH 17/21] Backport pull request #9538 from
jellyfin/release-10.8.z
Fix nvenc preset order
Original-merge: 79bb7560dc7848608cfab538b3aaf56dea545d8f
Merged-by: Cody Robibero
Backported-by: Bond_009
---
CONTRIBUTORS.md | 1 +
MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs | 6 +++---
2 files changed, 4 insertions(+), 3 deletions(-)
diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md
index 0b322685d1..dfb61df0a1 100644
--- a/CONTRIBUTORS.md
+++ b/CONTRIBUTORS.md
@@ -165,6 +165,7 @@
- [MinecraftPlaye](https://github.com/MinecraftPlaye)
- [RealGreenDragon](https://github.com/RealGreenDragon)
- [ipitio](https://github.com/ipitio)
+ - [TheTyrius](https://github.com/TheTyrius)
# Emby Contributors
diff --git a/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs b/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs
index 920925fc68..906a04a610 100644
--- a/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs
+++ b/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs
@@ -1549,11 +1549,11 @@ namespace MediaBrowser.Controller.MediaEncoding
param += " -preset p7";
break;
- case "slow":
+ case "slower":
param += " -preset p6";
break;
- case "slower":
+ case "slow":
param += " -preset p5";
break;
@@ -1586,8 +1586,8 @@ namespace MediaBrowser.Controller.MediaEncoding
switch (encodingOptions.EncoderPreset)
{
case "veryslow":
- case "slow":
case "slower":
+ case "slow":
param += " -quality quality";
break;
From 4c8d3827658342b630472cc4dc1601ae56ffe39c Mon Sep 17 00:00:00 2001
From: nyanmisaka
Date: Tue, 13 Jun 2023 10:53:35 -0400
Subject: [PATCH 18/21] Backport pull request #9642 from
jellyfin/release-10.8.z
Fix the brightness of VPP tonemap and add the tonemap mode
Original-merge: d5a8419bc52ba06c070012849ba166dd2fbff8b0
Merged-by: Cody Robibero
Backported-by: Bond_009
---
.../MediaEncoding/EncodingHelper.cs | 23 +++++++++++++++----
.../Configuration/EncodingOptions.cs | 16 ++++++-------
2 files changed, 26 insertions(+), 13 deletions(-)
diff --git a/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs b/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs
index 906a04a610..b6fa49fcd3 100644
--- a/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs
+++ b/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs
@@ -45,6 +45,7 @@ namespace MediaBrowser.Controller.MediaEncoding
private readonly Version _minFFmpegImplictHwaccel = new Version(6, 0);
private readonly Version _minFFmpegHwaUnsafeOutput = new Version(6, 0);
+ private readonly Version _minFFmpegOclCuTonemapMode = new Version(5, 1, 3);
private static readonly string[] _videoProfilesH264 = new[]
{
@@ -2929,7 +2930,7 @@ namespace MediaBrowser.Controller.MediaEncoding
return string.Empty;
}
- public static string GetHwTonemapFilter(EncodingOptions options, string hwTonemapSuffix, string videoFormat)
+ public string GetHwTonemapFilter(EncodingOptions options, string hwTonemapSuffix, string videoFormat)
{
if (string.IsNullOrEmpty(hwTonemapSuffix))
{
@@ -2941,7 +2942,8 @@ namespace MediaBrowser.Controller.MediaEncoding
if (string.Equals(hwTonemapSuffix, "vaapi", StringComparison.OrdinalIgnoreCase))
{
- args = "tonemap_vaapi=format={0}:p=bt709:t=bt709:m=bt709,procamp_vaapi=b={1}:c={2}:extra_hw_frames=16";
+ args = "procamp_vaapi=b={2}:c={3}," + args + ":extra_hw_frames=32";
+
return string.Format(
CultureInfo.InvariantCulture,
args,
@@ -2972,14 +2974,24 @@ namespace MediaBrowser.Controller.MediaEncoding
{
args = "tonemap_{0}=format={1}:p=bt709:t=bt709:m=bt709:tonemap={2}:peak={3}:desat={4}";
+ if (string.Equals(options.TonemappingMode, "max", StringComparison.OrdinalIgnoreCase)
+ || string.Equals(options.TonemappingMode, "rgb", StringComparison.OrdinalIgnoreCase))
+ {
+ if (_mediaEncoder.EncoderVersion >= _minFFmpegOclCuTonemapMode)
+ {
+ args += ":tonemap_mode={5}";
+ }
+ }
+
if (options.TonemappingParam != 0)
{
- args += ":param={5}";
+ args += ":param={6}";
}
- if (!string.Equals(options.TonemappingRange, "auto", StringComparison.OrdinalIgnoreCase))
+ if (string.Equals(options.TonemappingRange, "tv", StringComparison.OrdinalIgnoreCase)
+ || string.Equals(options.TonemappingRange, "pc", StringComparison.OrdinalIgnoreCase))
{
- args += ":range={6}";
+ args += ":range={7}";
}
}
@@ -2991,6 +3003,7 @@ namespace MediaBrowser.Controller.MediaEncoding
algorithm,
options.TonemappingPeak,
options.TonemappingDesat,
+ options.TonemappingMode,
options.TonemappingParam,
options.TonemappingRange);
}
diff --git a/MediaBrowser.Model/Configuration/EncodingOptions.cs b/MediaBrowser.Model/Configuration/EncodingOptions.cs
index f9f63f751a..ac2f1e71a3 100644
--- a/MediaBrowser.Model/Configuration/EncodingOptions.cs
+++ b/MediaBrowser.Model/Configuration/EncodingOptions.cs
@@ -27,13 +27,13 @@ public class EncodingOptions
EnableTonemapping = false;
EnableVppTonemapping = false;
TonemappingAlgorithm = "bt2390";
+ TonemappingMode = "auto";
TonemappingRange = "auto";
TonemappingDesat = 0;
- TonemappingThreshold = 0.8;
TonemappingPeak = 100;
TonemappingParam = 0;
- VppTonemappingBrightness = 0;
- VppTonemappingContrast = 1.2;
+ VppTonemappingBrightness = 16;
+ VppTonemappingContrast = 1;
H264Crf = 23;
H265Crf = 28;
DeinterlaceDoubleRate = false;
@@ -137,6 +137,11 @@ public class EncodingOptions
///
public string TonemappingAlgorithm { get; set; }
+ ///
+ /// Gets or sets the tone-mapping mode.
+ ///
+ public string TonemappingMode { get; set; }
+
///
/// Gets or sets the tone-mapping range.
///
@@ -147,11 +152,6 @@ public class EncodingOptions
///
public double TonemappingDesat { get; set; }
- ///
- /// Gets or sets the tone-mapping threshold.
- ///
- public double TonemappingThreshold { get; set; }
-
///
/// Gets or sets the tone-mapping peak.
///
From fdc16e23c43bf46e551c9b5d64572f566a2afaf3 Mon Sep 17 00:00:00 2001
From: nyanmisaka
Date: Tue, 13 Jun 2023 10:55:15 -0400
Subject: [PATCH 19/21] Backport pull request #9671 from
jellyfin/release-10.8.z
Fix the canvas size for DVBSUB and DVDSUB subtitles
Original-merge: eba95cc7f0304ebc9c1a8c0fc11a29ffca6fc97d
Merged-by: Joshua M. Boniface
Backported-by: Bond_009
---
MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs | 5 ++++-
1 file changed, 4 insertions(+), 1 deletion(-)
diff --git a/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs b/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs
index b6fa49fcd3..ff183daa03 100644
--- a/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs
+++ b/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs
@@ -755,9 +755,12 @@ namespace MediaBrowser.Controller.MediaEncoding
public string GetGraphicalSubCanvasSize(EncodingJobInfo state)
{
+ // DVBSUB and DVDSUB use the fixed canvas size 720x576
if (state.SubtitleStream is not null
&& state.SubtitleDeliveryMethod == SubtitleDeliveryMethod.Encode
- && !state.SubtitleStream.IsTextSubtitleStream)
+ && !state.SubtitleStream.IsTextSubtitleStream
+ && !string.Equals(state.SubtitleStream.Codec, "DVBSUB", StringComparison.OrdinalIgnoreCase)
+ && !string.Equals(state.SubtitleStream.Codec, "DVDSUB", StringComparison.OrdinalIgnoreCase))
{
var inW = state.VideoStream?.Width;
var inH = state.VideoStream?.Height;
From 14d061f543d3f9da6568272227dd0666065a1673 Mon Sep 17 00:00:00 2001
From: Dmitry Lyzo
Date: Tue, 13 Jun 2023 10:55:16 -0400
Subject: [PATCH 20/21] Backport pull request #9723 from
jellyfin/release-10.8.z
Fix multiple codec checking in CodecProfiles conditions
Original-merge: bec8d7b3f5923c240bbc5bcf160c19f7cc591211
Merged-by: Bond-009
Backported-by: Bond_009
---
MediaBrowser.Model/Dlna/StreamBuilder.cs | 12 +++---------
1 file changed, 3 insertions(+), 9 deletions(-)
diff --git a/MediaBrowser.Model/Dlna/StreamBuilder.cs b/MediaBrowser.Model/Dlna/StreamBuilder.cs
index 2d2086ac3a..0a955e917f 100644
--- a/MediaBrowser.Model/Dlna/StreamBuilder.cs
+++ b/MediaBrowser.Model/Dlna/StreamBuilder.cs
@@ -768,11 +768,10 @@ namespace MediaBrowser.Model.Dlna
if (ContainerProfile.ContainsContainer(videoCodecs, item.VideoStream?.Codec))
{
- var videoCodec = transcodingProfile.VideoCodec;
+ var videoCodec = videoStream?.Codec;
var container = transcodingProfile.Container;
var appliedVideoConditions = options.Profile.CodecProfiles
.Where(i => i.Type == CodecType.Video &&
- (string.IsNullOrEmpty(i.Codec) || string.Equals(i.Codec, videoStream?.Codec, StringComparison.OrdinalIgnoreCase)) &&
i.ContainsAnyCodec(videoCodec, container) &&
i.ApplyConditions.All(applyCondition => ConditionProcessor.IsVideoConditionSatisfied(applyCondition, videoStream?.Width, videoStream?.Height, videoStream?.BitDepth, videoStream?.BitRate, videoStream?.Profile, videoStream?.VideoRangeType, videoStream?.Level, videoFramerate, videoStream?.PacketLength, timestamp, videoStream?.IsAnamorphic, videoStream?.IsInterlaced, videoStream?.RefFrames, numVideoStreams, numAudioStreams, videoStream?.CodecTag, videoStream?.IsAVC)))
.Select(i =>
@@ -906,8 +905,7 @@ namespace MediaBrowser.Model.Dlna
var appliedVideoConditions = options.Profile.CodecProfiles
.Where(i => i.Type == CodecType.Video &&
- (string.IsNullOrEmpty(i.Codec) || string.Equals(i.Codec, videoStream?.Codec, StringComparison.OrdinalIgnoreCase)) &&
- i.ContainsAnyCodec(videoCodec, container) &&
+ i.ContainsAnyCodec(videoStream?.Codec, container) &&
i.ApplyConditions.All(applyCondition => ConditionProcessor.IsVideoConditionSatisfied(applyCondition, width, height, bitDepth, videoBitrate, videoProfile, videoRangeType, videoLevel, videoFramerate, packetLength, timestamp, isAnamorphic, isInterlaced, refFrames, numVideoStreams, numAudioStreams, videoCodecTag, isAvc)));
var isFirstAppliedCodecProfile = true;
foreach (var i in appliedVideoConditions)
@@ -939,8 +937,7 @@ namespace MediaBrowser.Model.Dlna
var appliedAudioConditions = options.Profile.CodecProfiles
.Where(i => i.Type == CodecType.VideoAudio &&
- (string.IsNullOrEmpty(i.Codec) || string.Equals(i.Codec, audioStream?.Codec, StringComparison.OrdinalIgnoreCase)) &&
- i.ContainsAnyCodec(audioCodec, container) &&
+ i.ContainsAnyCodec(audioStream?.Codec, container) &&
i.ApplyConditions.All(applyCondition => ConditionProcessor.IsVideoAudioConditionSatisfied(applyCondition, audioChannels, inputAudioBitrate, inputAudioSampleRate, inputAudioBitDepth, audioProfile, isSecondaryAudio)));
isFirstAppliedCodecProfile = true;
foreach (var codecProfile in appliedAudioConditions)
@@ -1180,7 +1177,6 @@ namespace MediaBrowser.Model.Dlna
"VideoCodecProfile",
profile.CodecProfiles
.Where(codecProfile => codecProfile.Type == CodecType.Video &&
- (string.IsNullOrEmpty(codecProfile.Codec) || string.Equals(codecProfile.Codec, videoStream?.Codec, StringComparison.OrdinalIgnoreCase)) &&
codecProfile.ContainsAnyCodec(videoStream?.Codec, container) &&
!checkVideoConditions(codecProfile.ApplyConditions).Any())
.SelectMany(codecProfile => checkVideoConditions(codecProfile.Conditions)));
@@ -1591,7 +1587,6 @@ namespace MediaBrowser.Model.Dlna
{
return codecProfiles
.Where(profile => profile.Type == CodecType.VideoAudio &&
- (string.IsNullOrEmpty(profile.Codec) || string.Equals(profile.Codec, codec, StringComparison.OrdinalIgnoreCase)) &&
profile.ContainsAnyCodec(codec, container) &&
profile.ApplyConditions.All(applyCondition => ConditionProcessor.IsVideoAudioConditionSatisfied(applyCondition, audioChannels, audioBitrate, audioSampleRate, audioBitDepth, audioProfile, isSecondaryAudio)))
.SelectMany(profile => profile.Conditions)
@@ -1610,7 +1605,6 @@ namespace MediaBrowser.Model.Dlna
{
var conditions = codecProfiles
.Where(profile => profile.Type == CodecType.Audio &&
- (string.IsNullOrEmpty(profile.Codec) || string.Equals(profile.Codec, codec, StringComparison.OrdinalIgnoreCase)) &&
profile.ContainsAnyCodec(codec, container) &&
profile.ApplyConditions.All(applyCondition => ConditionProcessor.IsAudioConditionSatisfied(applyCondition, audioChannels, audioBitrate, audioSampleRate, audioBitDepth)))
.SelectMany(profile => profile.Conditions);
From 23b90555476de9509dcc2bb42bfa6f8ad0e42b74 Mon Sep 17 00:00:00 2001
From: nyanmisaka
Date: Tue, 13 Jun 2023 01:13:48 +0800
Subject: [PATCH 21/21] Rearrage the Amd vaapi-vulkan pipeline for
synchronization
Signed-off-by: nyanmisaka
---
.../MediaEncoding/EncodingHelper.cs | 323 +++++++++++-------
1 file changed, 196 insertions(+), 127 deletions(-)
diff --git a/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs b/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs
index ff183daa03..39d53768e9 100644
--- a/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs
+++ b/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs
@@ -163,7 +163,8 @@ namespace MediaBrowser.Controller.MediaEncoding
private bool IsVaapiFullSupported()
{
- return _mediaEncoder.SupportsHwaccel("vaapi")
+ return _mediaEncoder.SupportsHwaccel("drm")
+ && _mediaEncoder.SupportsHwaccel("vaapi")
&& _mediaEncoder.SupportsFilter("scale_vaapi")
&& _mediaEncoder.SupportsFilter("deinterlace_vaapi")
&& _mediaEncoder.SupportsFilter("tonemap_vaapi")
@@ -713,28 +714,43 @@ namespace MediaBrowser.Controller.MediaEncoding
options);
}
- private string GetVaapiDeviceArgs(string renderNodePath, string driver, string kernelDriver, string alias)
+ private string GetVaapiDeviceArgs(string renderNodePath, string driver, string kernelDriver, string srcDeviceAlias, string alias)
{
alias ??= VaapiAlias;
renderNodePath = renderNodePath ?? "/dev/dri/renderD128";
- var options = string.IsNullOrEmpty(driver)
- ? renderNodePath
- : ",driver=" + driver + (string.IsNullOrEmpty(kernelDriver) ? string.Empty : ",kernel_driver=" + kernelDriver);
+ var driverOpts = string.IsNullOrEmpty(driver)
+ ? ":" + renderNodePath
+ : ":,driver=" + driver + (string.IsNullOrEmpty(kernelDriver) ? string.Empty : ",kernel_driver=" + kernelDriver);
+ var options = string.IsNullOrEmpty(srcDeviceAlias)
+ ? driverOpts
+ : "@" + srcDeviceAlias;
return string.Format(
CultureInfo.InvariantCulture,
- " -init_hw_device vaapi={0}:{1}",
+ " -init_hw_device vaapi={0}{1}",
alias,
options);
}
+ private string GetDrmDeviceArgs(string renderNodePath, string alias)
+ {
+ alias ??= DrmAlias;
+ renderNodePath = renderNodePath ?? "/dev/dri/renderD128";
+
+ return string.Format(
+ CultureInfo.InvariantCulture,
+ " -init_hw_device drm={0}:{1}",
+ alias,
+ renderNodePath);
+ }
+
private string GetQsvDeviceArgs(string alias)
{
var arg = " -init_hw_device qsv=" + (alias ?? QsvAlias);
if (OperatingSystem.IsLinux())
{
// derive qsv from vaapi device
- return GetVaapiDeviceArgs(null, "iHD", "i915", VaapiAlias) + arg + "@" + VaapiAlias;
+ return GetVaapiDeviceArgs(null, "iHD", "i915", null, VaapiAlias) + arg + "@" + VaapiAlias;
}
if (OperatingSystem.IsWindows())
@@ -828,21 +844,17 @@ namespace MediaBrowser.Controller.MediaEncoding
if (_mediaEncoder.IsVaapiDeviceInteliHD)
{
- args.Append(GetVaapiDeviceArgs(null, "iHD", null, VaapiAlias));
+ args.Append(GetVaapiDeviceArgs(null, "iHD", null, null, VaapiAlias));
}
else if (_mediaEncoder.IsVaapiDeviceInteli965)
{
// Only override i965 since it has lower priority than iHD in libva lookup.
Environment.SetEnvironmentVariable("LIBVA_DRIVER_NAME", "i965");
Environment.SetEnvironmentVariable("LIBVA_DRIVER_NAME_JELLYFIN", "i965");
- args.Append(GetVaapiDeviceArgs(null, "i965", null, VaapiAlias));
- }
- else
- {
- args.Append(GetVaapiDeviceArgs(options.VaapiDevice, null, null, VaapiAlias));
+ args.Append(GetVaapiDeviceArgs(null, "i965", null, null, VaapiAlias));
}
- var filterDevArgs = GetFilterHwDeviceArgs(VaapiAlias);
+ var filterDevArgs = string.Empty;
var doOclTonemap = isHwTonemapAvailable && IsOpenclFullSupported();
if (_mediaEncoder.IsVaapiDeviceInteliHD || _mediaEncoder.IsVaapiDeviceInteli965)
@@ -859,15 +871,24 @@ namespace MediaBrowser.Controller.MediaEncoding
&& _mediaEncoder.IsVaapiDeviceSupportVulkanFmtModifier
&& Environment.OSVersion.Version >= _minKernelVersionAmdVkFmtModifier)
{
+ args.Append(GetDrmDeviceArgs(options.VaapiDevice, DrmAlias));
+ args.Append(GetVaapiDeviceArgs(null, null, null, DrmAlias, VaapiAlias));
+ args.Append(GetVulkanDeviceArgs(0, null, DrmAlias, VulkanAlias));
+
// libplacebo wants an explicitly set vulkan filter device.
- args.Append(GetVulkanDeviceArgs(0, null, VaapiAlias, VulkanAlias));
filterDevArgs = GetFilterHwDeviceArgs(VulkanAlias);
}
- else if (doOclTonemap)
+ else
{
- // ROCm/ROCr OpenCL runtime
- args.Append(GetOpenclDeviceArgs(0, "Advanced Micro Devices", null, OpenclAlias));
- filterDevArgs = GetFilterHwDeviceArgs(OpenclAlias);
+ args.Append(GetVaapiDeviceArgs(options.VaapiDevice, null, null, null, VaapiAlias));
+ filterDevArgs = GetFilterHwDeviceArgs(VaapiAlias);
+
+ if (doOclTonemap)
+ {
+ // ROCm/ROCr OpenCL runtime
+ args.Append(GetOpenclDeviceArgs(0, "Advanced Micro Devices", null, OpenclAlias));
+ filterDevArgs = GetFilterHwDeviceArgs(OpenclAlias);
+ }
}
}
else if (doOclTonemap)
@@ -3011,6 +3032,75 @@ namespace MediaBrowser.Controller.MediaEncoding
options.TonemappingRange);
}
+ public string GetLibplaceboFilter(
+ EncodingOptions options,
+ string videoFormat,
+ bool doTonemap,
+ int? videoWidth,
+ int? videoHeight,
+ int? requestedWidth,
+ int? requestedHeight,
+ int? requestedMaxWidth,
+ int? requestedMaxHeight)
+ {
+ var (outWidth, outHeight) = GetFixedOutputSize(
+ videoWidth,
+ videoHeight,
+ requestedWidth,
+ requestedHeight,
+ requestedMaxWidth,
+ requestedMaxHeight);
+
+ var isFormatFixed = !string.IsNullOrEmpty(videoFormat);
+ var isSizeFixed = !videoWidth.HasValue
+ || outWidth.Value != videoWidth.Value
+ || !videoHeight.HasValue
+ || outHeight.Value != videoHeight.Value;
+
+ var sizeArg = isSizeFixed ? (":w=" + outWidth.Value + ":h=" + outHeight.Value) : string.Empty;
+ var formatArg = isFormatFixed ? (":format=" + videoFormat) : string.Empty;
+ var tonemapArg = string.Empty;
+
+ if (doTonemap)
+ {
+ var algorithm = options.TonemappingAlgorithm;
+ var mode = options.TonemappingMode;
+ var range = options.TonemappingRange;
+
+ if (string.Equals(algorithm, "bt2390", StringComparison.OrdinalIgnoreCase))
+ {
+ algorithm = "bt.2390";
+ }
+ else if (string.Equals(algorithm, "none", StringComparison.OrdinalIgnoreCase))
+ {
+ algorithm = "clip";
+ }
+
+ tonemapArg = ":tonemapping=" + algorithm;
+
+ if (string.Equals(mode, "max", StringComparison.OrdinalIgnoreCase)
+ || string.Equals(mode, "rgb", StringComparison.OrdinalIgnoreCase))
+ {
+ tonemapArg += ":tonemapping_mode=" + mode;
+ }
+
+ tonemapArg += ":peak_detect=0:color_primaries=bt709:color_trc=bt709:colorspace=bt709";
+
+ if (string.Equals(range, "tv", StringComparison.OrdinalIgnoreCase)
+ || string.Equals(range, "pc", StringComparison.OrdinalIgnoreCase))
+ {
+ tonemapArg += ":range=" + range;
+ }
+ }
+
+ return string.Format(
+ CultureInfo.InvariantCulture,
+ "libplacebo=upscaler=none:downscaler=none{0}{1}{2}",
+ sizeArg,
+ formatArg,
+ tonemapArg);
+ }
+
///
/// Gets the parameter of software filter chain.
///
@@ -4240,7 +4330,6 @@ namespace MediaBrowser.Controller.MediaEncoding
var isVaapiEncoder = vidEncoder.Contains("vaapi", StringComparison.OrdinalIgnoreCase);
var isSwDecoder = string.IsNullOrEmpty(vidDecoder);
var isSwEncoder = !isVaapiEncoder;
- var isVaInVaOut = isVaapiDecoder && isVaapiEncoder;
var doDeintH264 = state.DeInterlace("h264", true) || state.DeInterlace("avc", true);
var doDeintHevc = state.DeInterlace("h265", true) || state.DeInterlace("hevc", true);
@@ -4269,99 +4358,81 @@ namespace MediaBrowser.Controller.MediaEncoding
mainFilters.Add(swDeintFilter);
}
- var outFormat = doVkTonemap ? "yuv420p10le" : "nv12";
- var swScaleFilter = GetSwScaleFilter(state, options, vidEncoder, inW, inH, threeDFormat, reqW, reqH, reqMaxW, reqMaxH);
- // sw scale
- mainFilters.Add(swScaleFilter);
- mainFilters.Add("format=" + outFormat);
-
- // keep video at memory except vk tonemap,
- // since the overhead caused by hwupload >>> using sw filter.
- // sw => hw
- if (doVkTonemap)
+ if (doVkTonemap || hasSubs)
{
- mainFilters.Add("hwupload=derive_device=vaapi");
- mainFilters.Add("format=vaapi");
- mainFilters.Add("hwmap=derive_device=vulkan");
+ // sw => hw
+ mainFilters.Add("hwupload=derive_device=vulkan");
mainFilters.Add("format=vulkan");
}
+ else
+ {
+ // sw scale
+ var swScaleFilter = GetSwScaleFilter(state, options, vidEncoder, inW, inH, threeDFormat, reqW, reqH, reqMaxW, reqMaxH);
+ mainFilters.Add(swScaleFilter);
+ mainFilters.Add("format=nv12");
+ }
}
else if (isVaapiDecoder)
{
// INPUT vaapi surface(vram)
- // hw deint
- if (doDeintH2645)
+ if (doVkTonemap || hasSubs)
{
- var deintFilter = GetHwDeinterlaceFilter(state, options, "vaapi");
- mainFilters.Add(deintFilter);
+ // map from vaapi to vulkan/drm via interop (Vega/gfx9+).
+ mainFilters.Add("hwmap=derive_device=vulkan");
+ mainFilters.Add("format=vulkan");
}
-
- var outFormat = doVkTonemap ? string.Empty : (hasSubs && isVaInVaOut ? "bgra" : "nv12");
- var hwScaleFilter = GetHwScaleFilter("vaapi", outFormat, inW, inH, reqW, reqH, reqMaxW, reqMaxH);
-
- // allocate extra pool sizes for overlay_vulkan
- if (!string.IsNullOrEmpty(hwScaleFilter) && isVaInVaOut && hasSubs)
+ else
{
- hwScaleFilter += ":extra_hw_frames=32";
- }
-
- // hw scale
- mainFilters.Add(hwScaleFilter);
- }
+ // hw deint
+ if (doDeintH2645)
+ {
+ var deintFilter = GetHwDeinterlaceFilter(state, options, "vaapi");
+ mainFilters.Add(deintFilter);
+ }
- if ((isVaapiDecoder && doVkTonemap) || (isVaInVaOut && (doVkTonemap || hasSubs)))
- {
- // map from vaapi to vulkan via vaapi-vulkan interop (Vega/gfx9+).
- mainFilters.Add("hwmap=derive_device=vulkan");
- mainFilters.Add("format=vulkan");
+ // hw scale
+ var hwScaleFilter = GetHwScaleFilter("vaapi", "nv12", inW, inH, reqW, reqH, reqMaxW, reqMaxH);
+ mainFilters.Add(hwScaleFilter);
+ }
}
- // vk tonemap
- if (doVkTonemap)
+ // vk libplacebo
+ if (doVkTonemap || hasSubs)
{
- var outFormat = isVaInVaOut && hasSubs ? "bgra" : "nv12";
- var tonemapFilter = GetHwTonemapFilter(options, "vulkan", outFormat);
- mainFilters.Add(tonemapFilter);
+ var libplaceboFilter = GetLibplaceboFilter(options, "bgra", doVkTonemap, inW, inH, reqW, reqH, reqMaxW, reqMaxH);
+ mainFilters.Add(libplaceboFilter);
}
- if (doVkTonemap && isVaInVaOut && !hasSubs)
+ if (doVkTonemap && !hasSubs)
{
- // OUTPUT vaapi(nv12/bgra) surface(vram)
- // reverse-mapping via vaapi-vulkan interop.
- mainFilters.Add("hwmap=derive_device=vaapi:reverse=1");
+ // OUTPUT vaapi(nv12) surface(vram)
+ // map from vulkan/drm to vaapi via interop (Vega/gfx9+).
+ mainFilters.Add("hwmap=derive_device=drm");
+ mainFilters.Add("format=drm_prime");
+ mainFilters.Add("hwmap=derive_device=vaapi");
mainFilters.Add("format=vaapi");
- }
- var memoryOutput = false;
- var isUploadForVkTonemap = isSwDecoder && doVkTonemap;
- if ((isVaapiDecoder && isSwEncoder) || isUploadForVkTonemap)
- {
- memoryOutput = true;
+ // clear the surf->meta_offset and output nv12
+ mainFilters.Add("scale_vaapi=format=nv12");
- // OUTPUT nv12 surface(memory)
- mainFilters.Add("hwdownload");
- mainFilters.Add("format=nv12");
- }
-
- // OUTPUT nv12 surface(memory)
- if (isSwDecoder && isVaapiEncoder)
- {
- memoryOutput = true;
+ // hw deint
+ if (doDeintH2645)
+ {
+ var deintFilter = GetHwDeinterlaceFilter(state, options, "vaapi");
+ mainFilters.Add(deintFilter);
+ }
}
- if (memoryOutput)
+ if (!hasSubs)
{
- // text subtitles
- if (hasTextSubs)
+ // OUTPUT nv12 surface(memory)
+ if (isSwEncoder && (doVkTonemap || isVaapiDecoder))
{
- var textSubtitlesFilter = GetTextSubtitlesFilter(state, false, false);
- mainFilters.Add(textSubtitlesFilter);
+ mainFilters.Add("hwdownload");
+ mainFilters.Add("format=nv12");
}
- }
- if (memoryOutput && isVaapiEncoder)
- {
- if (!hasGraphicalSubs)
+ if (isSwDecoder && isVaapiEncoder && !doVkTonemap)
{
mainFilters.Add("hwupload_vaapi");
}
@@ -4370,55 +4441,53 @@ namespace MediaBrowser.Controller.MediaEncoding
/* Make sub and overlay filters for subtitle stream */
var subFilters = new List();
var overlayFilters = new List();
- if (isVaInVaOut)
+ if (hasSubs)
{
- if (hasSubs)
+ if (hasGraphicalSubs)
{
- if (hasGraphicalSubs)
- {
- // scale=s=1280x720,format=bgra,hwupload
- var subSwScaleFilter = GetCustomSwScaleFilter(inW, inH, reqW, reqH, reqMaxW, reqMaxH);
- subFilters.Add(subSwScaleFilter);
- subFilters.Add("format=bgra");
- }
- else if (hasTextSubs)
- {
- var alphaSrcFilter = GetAlphaSrcFilter(state, inW, inH, reqW, reqH, reqMaxW, reqMaxH, hasAssSubs ? 10 : 5);
- var subTextSubtitlesFilter = GetTextSubtitlesFilter(state, true, true);
- subFilters.Add(alphaSrcFilter);
- subFilters.Add("format=bgra");
- subFilters.Add(subTextSubtitlesFilter);
- }
-
- // prefer vaapi hwupload to vulkan hwupload,
- // Mesa RADV does not support a dedicated transfer queue.
- subFilters.Add("hwupload=derive_device=vaapi");
- subFilters.Add("format=vaapi");
- subFilters.Add("hwmap=derive_device=vulkan");
- subFilters.Add("format=vulkan");
+ // scale=s=1280x720,format=bgra,hwupload
+ var subSwScaleFilter = GetCustomSwScaleFilter(inW, inH, reqW, reqH, reqMaxW, reqMaxH);
+ subFilters.Add(subSwScaleFilter);
+ subFilters.Add("format=bgra");
+ }
+ else if (hasTextSubs)
+ {
+ var alphaSrcFilter = GetAlphaSrcFilter(state, inW, inH, reqW, reqH, reqMaxW, reqMaxH, hasAssSubs ? 10 : 5);
+ var subTextSubtitlesFilter = GetTextSubtitlesFilter(state, true, true);
+ subFilters.Add(alphaSrcFilter);
+ subFilters.Add("format=bgra");
+ subFilters.Add(subTextSubtitlesFilter);
+ }
- overlayFilters.Add("overlay_vulkan=eof_action=endall:shortest=1:repeatlast=0");
+ subFilters.Add("hwupload=derive_device=vulkan");
+ subFilters.Add("format=vulkan");
- // TODO: figure out why libplacebo can sync without vaSyncSurface VPP support in radeonsi.
- overlayFilters.Add("libplacebo=format=nv12:apply_filmgrain=0:apply_dolbyvision=0:upscaler=none:downscaler=none:dithering=none");
+ overlayFilters.Add("overlay_vulkan=eof_action=endall:shortest=1:repeatlast=0");
- // OUTPUT vaapi(nv12/bgra) surface(vram)
- // reverse-mapping via vaapi-vulkan interop.
- overlayFilters.Add("hwmap=derive_device=vaapi:reverse=1");
- overlayFilters.Add("format=vaapi");
+ if (isSwEncoder)
+ {
+ // OUTPUT nv12 surface(memory)
+ overlayFilters.Add("scale_vulkan=format=nv12");
+ overlayFilters.Add("hwdownload");
+ overlayFilters.Add("format=nv12");
}
- }
- else if (memoryOutput)
- {
- if (hasGraphicalSubs)
+ else if (isVaapiEncoder)
{
- var subSwScaleFilter = GetCustomSwScaleFilter(inW, inH, reqW, reqH, reqMaxW, reqMaxH);
- subFilters.Add(subSwScaleFilter);
- overlayFilters.Add("overlay=eof_action=pass:shortest=1:repeatlast=0");
+ // OUTPUT vaapi(nv12) surface(vram)
+ // map from vulkan/drm to vaapi via interop (Vega/gfx9+).
+ overlayFilters.Add("hwmap=derive_device=drm");
+ overlayFilters.Add("format=drm_prime");
+ overlayFilters.Add("hwmap=derive_device=vaapi");
+ overlayFilters.Add("format=vaapi");
- if (isVaapiEncoder)
+ // clear the surf->meta_offset and output nv12
+ overlayFilters.Add("scale_vaapi=format=nv12");
+
+ // hw deint
+ if (doDeintH2645)
{
- overlayFilters.Add("hwupload_vaapi");
+ var deintFilter = GetHwDeinterlaceFilter(state, options, "vaapi");
+ overlayFilters.Add(deintFilter);
}
}
}