aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--.config/dotnet-tools.json2
-rw-r--r--.devcontainer/Dev - Server Ffmpeg/devcontainer.json28
-rw-r--r--.devcontainer/Dev - Server Ffmpeg/install-ffmpeg.sh32
-rw-r--r--.github/ISSUE_TEMPLATE/issue report.yml49
-rw-r--r--.github/workflows/ci-codeql-analysis.yml6
-rw-r--r--.github/workflows/ci-openapi.yml8
-rw-r--r--.github/workflows/ci-tests.yml2
-rw-r--r--.vscode/extensions.json2
-rw-r--r--.vscode/launch.json12
-rw-r--r--CONTRIBUTORS.md5
-rw-r--r--Directory.Packages.props39
-rw-r--r--Emby.Server.Implementations/ApplicationHost.cs35
-rw-r--r--Emby.Server.Implementations/EntryPoints/LibraryChangedNotifier.cs45
-rw-r--r--Emby.Server.Implementations/EntryPoints/UserDataChangeNotifier.cs88
-rw-r--r--Emby.Server.Implementations/IO/LibraryMonitor.cs71
-rw-r--r--Emby.Server.Implementations/IO/LibraryMonitorStartup.cs35
-rw-r--r--Emby.Server.Implementations/Library/LibraryManager.cs19
-rw-r--r--Emby.Server.Implementations/Library/LiveStreamHelper.cs17
-rw-r--r--Emby.Server.Implementations/Library/MediaSourceManager.cs21
-rw-r--r--Emby.Server.Implementations/Localization/Core/et.json2
-rw-r--r--Emby.Server.Implementations/Localization/Core/ga.json3
-rw-r--r--Emby.Server.Implementations/Localization/Core/ky.json1
-rw-r--r--Emby.Server.Implementations/Localization/Core/mk.json3
-rw-r--r--Emby.Server.Implementations/Localization/Core/or.json10
-rw-r--r--Emby.Server.Implementations/ScheduledTasks/ScheduledTaskWorker.cs3
-rw-r--r--Jellyfin.Api/Controllers/DynamicHlsController.cs133
-rw-r--r--Jellyfin.Api/Controllers/LibraryController.cs4
-rw-r--r--Jellyfin.Api/Controllers/LibraryStructureController.cs8
-rw-r--r--Jellyfin.Api/Controllers/LiveTvController.cs58
-rw-r--r--Jellyfin.Api/Controllers/SystemController.cs12
-rw-r--r--Jellyfin.Api/Controllers/VideosController.cs6
-rw-r--r--Jellyfin.Api/Helpers/DynamicHlsHelper.cs25
-rw-r--r--Jellyfin.Api/Helpers/FileStreamResponseHelpers.cs8
-rw-r--r--Jellyfin.Api/Helpers/StreamingHelpers.cs21
-rw-r--r--Jellyfin.Api/Models/SessionDtos/ClientCapabilitiesDto.cs13
-rw-r--r--Jellyfin.Server.Implementations/Jellyfin.Server.Implementations.csproj1
-rw-r--r--Jellyfin.Server.Implementations/Trickplay/TrickplayManager.cs143
-rw-r--r--Jellyfin.Server.Implementations/Users/DeviceAccessEntryPoint.cs64
-rw-r--r--Jellyfin.Server.Implementations/Users/DeviceAccessHost.cs76
-rw-r--r--Jellyfin.Server/Jellyfin.Server.csproj5
-rw-r--r--Jellyfin.Server/Jellyfin.Server.icobin0 -> 40883 bytes
-rw-r--r--Jellyfin.Server/Startup.cs10
-rw-r--r--MediaBrowser.Common/Progress/ActionableProgress.cs37
-rw-r--r--MediaBrowser.Common/Progress/SimpleProgress.cs17
-rw-r--r--MediaBrowser.Controller/Channels/Channel.cs3
-rw-r--r--MediaBrowser.Controller/Drawing/ImageStream.cs42
-rw-r--r--MediaBrowser.Controller/Entities/Folder.cs35
-rw-r--r--MediaBrowser.Controller/Library/ILibraryMonitor.cs9
-rw-r--r--MediaBrowser.Controller/LiveTv/IGuideManager.cs26
-rw-r--r--MediaBrowser.Controller/LiveTv/IListingsManager.cs79
-rw-r--r--MediaBrowser.Controller/LiveTv/ILiveTvManager.cs44
-rw-r--r--MediaBrowser.Controller/LiveTv/TunerChannelMapping.cs17
-rw-r--r--MediaBrowser.Controller/MediaEncoding/BaseEncodingJobOptions.cs6
-rw-r--r--MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs469
-rw-r--r--MediaBrowser.Controller/MediaEncoding/EncodingJobInfo.cs20
-rw-r--r--MediaBrowser.Controller/MediaEncoding/ITranscodeManager.cs7
-rw-r--r--MediaBrowser.Controller/MediaEncoding/ImageEncodingOptions.cs23
-rw-r--r--MediaBrowser.Controller/MediaEncoding/MediaEncoderHelpers.cs11
-rw-r--r--MediaBrowser.Controller/Plugins/IRunBeforeStartup.cs9
-rw-r--r--MediaBrowser.Controller/Plugins/IServerEntryPoint.cs20
-rw-r--r--MediaBrowser.MediaEncoding/Attachments/AttachmentExtractor.cs46
-rw-r--r--MediaBrowser.MediaEncoding/Encoder/EncoderValidator.cs21
-rw-r--r--MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs65
-rw-r--r--MediaBrowser.MediaEncoding/MediaBrowser.MediaEncoding.csproj3
-rw-r--r--MediaBrowser.MediaEncoding/Probing/ProbeResultNormalizer.cs19
-rw-r--r--MediaBrowser.MediaEncoding/Subtitles/SubtitleEncoder.cs280
-rw-r--r--MediaBrowser.MediaEncoding/Transcoding/TranscodeManager.cs61
-rw-r--r--MediaBrowser.Model/ClientLog/ClientLogEvent.cs75
-rw-r--r--MediaBrowser.Model/Dlna/StreamBuilder.cs32
-rw-r--r--MediaBrowser.Model/Dto/ImageByNameInfo.cs38
-rw-r--r--MediaBrowser.Model/Entities/SpecialFolder.cs36
-rw-r--r--MediaBrowser.Model/LiveTv/ChannelMappingOptionsDto.cs (renamed from Jellyfin.Api/Models/LiveTvDtos/ChannelMappingOptionsDto.cs)3
-rw-r--r--MediaBrowser.Model/LiveTv/TunerChannelMapping.cs16
-rw-r--r--MediaBrowser.Model/Net/MimeTypes.cs13
-rw-r--r--MediaBrowser.Model/Net/SocketReceiveResult.cs32
-rw-r--r--MediaBrowser.Model/Session/ClientCapabilities.cs11
-rw-r--r--MediaBrowser.Model/Session/HardwareEncodingType.cs7
-rw-r--r--MediaBrowser.Model/System/SystemInfo.cs29
-rw-r--r--MediaBrowser.Providers/Manager/ProviderManager.cs7
-rw-r--r--MediaBrowser.XbmcMetadata/EntryPoint.cs78
-rw-r--r--MediaBrowser.XbmcMetadata/NfoUserDataSaver.cs87
-rw-r--r--MediaBrowser.XbmcMetadata/Parsers/BaseNfoParser.cs26
-rw-r--r--README.md27
-rw-r--r--deployment/Dockerfile.centos.amd642
-rw-r--r--deployment/Dockerfile.fedora.amd642
-rw-r--r--src/Jellyfin.Drawing.Skia/SkiaCodecException.cs44
-rw-r--r--src/Jellyfin.Drawing.Skia/SkiaEncoder.cs1
-rw-r--r--src/Jellyfin.Drawing.Skia/SkiaException.cs38
-rw-r--r--src/Jellyfin.Drawing/ImageProcessor.cs16
-rw-r--r--src/Jellyfin.Drawing/Jellyfin.Drawing.csproj4
-rw-r--r--src/Jellyfin.LiveTv/Channels/ChannelManager.cs18
-rw-r--r--src/Jellyfin.LiveTv/Channels/RefreshChannelsScheduledTask.cs3
-rw-r--r--src/Jellyfin.LiveTv/EmbyTV/EmbyTV.cs320
-rw-r--r--src/Jellyfin.LiveTv/EmbyTV/EntryPoint.cs21
-rw-r--r--src/Jellyfin.LiveTv/EmbyTV/LiveTvHost.cs31
-rw-r--r--src/Jellyfin.LiveTv/Extensions/LiveTvServiceCollectionExtensions.cs7
-rw-r--r--src/Jellyfin.LiveTv/Guide/GuideManager.cs707
-rw-r--r--src/Jellyfin.LiveTv/Guide/RefreshGuideScheduledTask.cs74
-rw-r--r--src/Jellyfin.LiveTv/Jellyfin.LiveTv.csproj3
-rw-r--r--src/Jellyfin.LiveTv/Listings/EpgChannelData.cs (renamed from src/Jellyfin.LiveTv/EmbyTV/EpgChannelData.cs)2
-rw-r--r--src/Jellyfin.LiveTv/Listings/ListingsManager.cs461
-rw-r--r--src/Jellyfin.LiveTv/Listings/SchedulesDirect.cs115
-rw-r--r--src/Jellyfin.LiveTv/LiveTvManager.cs876
-rw-r--r--src/Jellyfin.LiveTv/RecordingNotifier.cs73
-rw-r--r--src/Jellyfin.LiveTv/RefreshGuideScheduledTask.cs70
-rw-r--r--src/Jellyfin.LiveTv/TunerHosts/TunerHostManager.cs1
-rw-r--r--src/Jellyfin.Networking/PortForwardingHost.cs (renamed from src/Jellyfin.Networking/ExternalPortForwarding.cs)71
-rw-r--r--tests/Jellyfin.Api.Tests/Controllers/SystemControllerTests.cs35
-rw-r--r--tests/Jellyfin.MediaEncoding.Tests/Probing/ProbeResultNormalizerTests.cs17
-rw-r--r--tests/Jellyfin.MediaEncoding.Tests/Test Data/Probing/video_webm.json106
-rw-r--r--tests/Jellyfin.Model.Tests/Dlna/StreamBuilderTests.cs10
-rw-r--r--tests/Jellyfin.Model.Tests/Net/MimeTypesTests.cs13
-rw-r--r--tests/Jellyfin.Model.Tests/Test Data/MediaSourceInfo-mkv-av1-aac-srt-2600k.json2
-rw-r--r--tests/Jellyfin.Model.Tests/Test Data/MediaSourceInfo-mkv-vp9-aac-srt-2600k.json2
-rw-r--r--tests/Jellyfin.Model.Tests/Test Data/MediaSourceInfo-mkv-vp9-ac3-srt-2600k.json2
115 files changed, 3391 insertions, 2767 deletions
diff --git a/.config/dotnet-tools.json b/.config/dotnet-tools.json
index 81fe5add4..d9b689bb6 100644
--- a/.config/dotnet-tools.json
+++ b/.config/dotnet-tools.json
@@ -3,7 +3,7 @@
"isRoot": true,
"tools": {
"dotnet-ef": {
- "version": "8.0.1",
+ "version": "8.0.2",
"commands": [
"dotnet-ef"
]
diff --git a/.devcontainer/Dev - Server Ffmpeg/devcontainer.json b/.devcontainer/Dev - Server Ffmpeg/devcontainer.json
new file mode 100644
index 000000000..0b848d9f3
--- /dev/null
+++ b/.devcontainer/Dev - Server Ffmpeg/devcontainer.json
@@ -0,0 +1,28 @@
+{
+ "name": "Development Jellyfin Server - FFmpeg",
+ "image":"mcr.microsoft.com/devcontainers/dotnet:8.0-jammy",
+ // restores nuget packages, installs the dotnet workloads and installs the dev https certificate
+ "postStartCommand": "dotnet restore; dotnet workload update; dotnet dev-certs https --trust; sudo bash \"./.devcontainer/Dev - Server Ffmpeg/install-ffmpeg.sh\"",
+ // reads the extensions list and installs them
+ "postAttachCommand": "cat .vscode/extensions.json | jq -r .recommendations[] | xargs -n 1 code --install-extension",
+ "features": {
+ "ghcr.io/devcontainers/features/dotnet:2": {
+ "version": "none",
+ "dotnetRuntimeVersions": "8.0",
+ "aspNetCoreRuntimeVersions": "8.0"
+ },
+ "ghcr.io/devcontainers-contrib/features/apt-packages:1": {
+ "preserve_apt_list": false,
+ "packages": ["libfontconfig1"]
+ },
+ "ghcr.io/devcontainers/features/docker-in-docker:2": {
+ "dockerDashComposeVersion": "v2"
+ },
+ "ghcr.io/devcontainers/features/github-cli:1": {},
+ "ghcr.io/eitsupi/devcontainer-features/jq-likes:2": {}
+ },
+ "hostRequirements": {
+ "memory": "8gb",
+ "cpus": 4
+ }
+}
diff --git a/.devcontainer/Dev - Server Ffmpeg/install-ffmpeg.sh b/.devcontainer/Dev - Server Ffmpeg/install-ffmpeg.sh
new file mode 100644
index 000000000..c867ef538
--- /dev/null
+++ b/.devcontainer/Dev - Server Ffmpeg/install-ffmpeg.sh
@@ -0,0 +1,32 @@
+#!/bin/bash
+
+## configure the following for a manuall install of a specific version from the repo
+
+# wget https://repo.jellyfin.org/releases/server/ubuntu/versions/jellyfin-ffmpeg/6.0.1-1/jellyfin-ffmpeg6_6.0.1-1-jammy_amd64.deb -O ffmpeg.deb
+
+# sudo apt update
+# sudo apt install -f ./ffmpeg.deb -y
+# rm ffmpeg.deb
+
+
+## Add the jellyfin repo
+sudo apt install curl gnupg -y
+sudo apt-get install software-properties-common -y
+sudo add-apt-repository universe -y
+
+sudo mkdir -p /etc/apt/keyrings
+curl -fsSL https://repo.jellyfin.org/jellyfin_team.gpg.key | sudo gpg --dearmor -o /etc/apt/keyrings/jellyfin.gpg
+export VERSION_OS="$( awk -F'=' '/^ID=/{ print $NF }' /etc/os-release )"
+export VERSION_CODENAME="$( awk -F'=' '/^VERSION_CODENAME=/{ print $NF }' /etc/os-release )"
+export DPKG_ARCHITECTURE="$( dpkg --print-architecture )"
+cat <<EOF | sudo tee /etc/apt/sources.list.d/jellyfin.sources
+Types: deb
+URIs: https://repo.jellyfin.org/${VERSION_OS}
+Suites: ${VERSION_CODENAME}
+Components: main
+Architectures: ${DPKG_ARCHITECTURE}
+Signed-By: /etc/apt/keyrings/jellyfin.gpg
+EOF
+
+sudo apt update -y
+sudo apt install jellyfin-ffmpeg6 -y
diff --git a/.github/ISSUE_TEMPLATE/issue report.yml b/.github/ISSUE_TEMPLATE/issue report.yml
index 587802833..b690b82c2 100644
--- a/.github/ISSUE_TEMPLATE/issue report.yml
+++ b/.github/ISSUE_TEMPLATE/issue report.yml
@@ -6,7 +6,11 @@ body:
- type: markdown
attributes:
value: |
- Thanks for taking the time to fill out this bug report! Please provide as much detail as necessary, most questions may not be applicable to you. If you need real-time help, join us on [Matrix](https://matrix.to/#/#jellyfin-troubleshooting:matrix.org) or [Discord](https://discord.gg/zHBxVSXdBV).
+ Thanks for taking the time to report an issue. Before submitting a report, please do the following:
+ 1. Please head to our forum or chat rooms and troubleshoot with volunteers if you haven't already. Links can be found here: https://jellyfin.org/contact/
+ 2. Please search the bug tracker for similar issues. If you do find one, please comment there instead of opening a new bug report.
+ 3. If you decide to open a new report, please provide as much detail as possible.
+ 4. Please **ONLY** report **ONE** issue per report. If you are experiencing multiple issues, please open multiple reports.
- type: textarea
id: what-happened
attributes:
@@ -14,14 +18,18 @@ body:
description: Also tell us, what did you expect to happen?
placeholder: |
The more information that you are able to provide, the better. Did you do anything before this happened? Did you upgrade or change anything? Any screenshots or logs you can provide will be helpful.
-
- This is my issue.
-
- Steps to Reproduce
- 1. In this environment...
- 2. With this config...
- 3. Run '...'
- 4. See error...
+ If you are using an old release of Jellyfin, please also explain why.
+ validations:
+ required: true
+ - type: textarea
+ id: repro-steps
+ attributes:
+ label: Reproduction Steps
+ placeholder: |
+ 1. In this environment...
+ 2. With this config...
+ 3. Run '...'
+ 4. See error...
validations:
required: true
- type: dropdown
@@ -30,11 +38,10 @@ body:
label: Jellyfin Version
description: What version of Jellyfin are you running?
options:
- - 10.8.z
- - 10.8.9
- - 10.7.7
- - 10.6.4
- - Other
+ - 10.8.13
+ - 10.8.12
+ - 10.8.11 or older (please specify)
+ - Unstable (master branch)
validations:
required: true
- type: input
@@ -77,6 +84,18 @@ body:
- Networking:
- Storage:
render: markdown
+ validations:
+ required: true
+ - type: markdown
+ attributes:
+ value: |
+ When providing logs, please keep the following things in mind.
+ 1. **DO NOT** use external paste services.
+ 2. Please provide complete logs.
+ - For server logs, include everything you think is important plus *10 lines before and after*
+ - For ffmpeg logs, please provide the entire file unmodified.
+ 3. Please do not run logs through any translation program. Especially beware if your browser translates pages by default.
+ 4. Please do not include logs as screenshots, with the only exception being client logs in browsers.
- type: textarea
id: logs
attributes:
@@ -84,6 +103,8 @@ body:
description: Please copy and paste any relevant log output. This can be found in Dashboard > Logs.
placeholder: For playback issues, browser/client and FFmpeg logs may be more useful.
render: shell
+ validations:
+ required: true
- type: textarea
id: ffmpeg-logs
attributes:
diff --git a/.github/workflows/ci-codeql-analysis.yml b/.github/workflows/ci-codeql-analysis.yml
index e92a404d2..f8012e90e 100644
--- a/.github/workflows/ci-codeql-analysis.yml
+++ b/.github/workflows/ci-codeql-analysis.yml
@@ -27,11 +27,11 @@ jobs:
dotnet-version: '8.0.x'
- name: Initialize CodeQL
- uses: github/codeql-action/init@b7bf0a3ed3ecfa44160715d7c442788f65f0f923 # v3.23.2
+ uses: github/codeql-action/init@379614612a29c9e28f31f39a59013eb8012a51f0 # v3.24.3
with:
languages: ${{ matrix.language }}
queries: +security-extended
- name: Autobuild
- uses: github/codeql-action/autobuild@b7bf0a3ed3ecfa44160715d7c442788f65f0f923 # v3.23.2
+ uses: github/codeql-action/autobuild@379614612a29c9e28f31f39a59013eb8012a51f0 # v3.24.3
- name: Perform CodeQL Analysis
- uses: github/codeql-action/analyze@b7bf0a3ed3ecfa44160715d7c442788f65f0f923 # v3.23.2
+ uses: github/codeql-action/analyze@379614612a29c9e28f31f39a59013eb8012a51f0 # v3.24.3
diff --git a/.github/workflows/ci-openapi.yml b/.github/workflows/ci-openapi.yml
index 17fe0400a..97f1a33e7 100644
--- a/.github/workflows/ci-openapi.yml
+++ b/.github/workflows/ci-openapi.yml
@@ -25,7 +25,7 @@ jobs:
- name: Generate openapi.json
run: dotnet test tests/Jellyfin.Server.Integration.Tests/Jellyfin.Server.Integration.Tests.csproj -c Release --filter "Jellyfin.Server.Integration.Tests.OpenApiSpecTests"
- name: Upload openapi.json
- uses: actions/upload-artifact@26f96dfa697d77e81fd5907df203aa23a56210a8 # v4.3.0
+ uses: actions/upload-artifact@5d5d22a31266ced268874388b861e4b58bb5c2f3 # v4.3.1
with:
name: openapi-head
retention-days: 14
@@ -59,7 +59,7 @@ jobs:
- name: Generate openapi.json
run: dotnet test tests/Jellyfin.Server.Integration.Tests/Jellyfin.Server.Integration.Tests.csproj -c Release --filter "Jellyfin.Server.Integration.Tests.OpenApiSpecTests"
- name: Upload openapi.json
- uses: actions/upload-artifact@26f96dfa697d77e81fd5907df203aa23a56210a8 # v4.3.0
+ uses: actions/upload-artifact@5d5d22a31266ced268874388b861e4b58bb5c2f3 # v4.3.1
with:
name: openapi-base
retention-days: 14
@@ -78,12 +78,12 @@ jobs:
- openapi-base
steps:
- name: Download openapi-head
- uses: actions/download-artifact@6b208ae046db98c579e8a3aa621ab581ff575935 # v4.1.1
+ uses: actions/download-artifact@eaceaf801fd36c7dee90939fad912460b18a1ffe # v4.1.2
with:
name: openapi-head
path: openapi-head
- name: Download openapi-base
- uses: actions/download-artifact@6b208ae046db98c579e8a3aa621ab581ff575935 # v4.1.1
+ uses: actions/download-artifact@eaceaf801fd36c7dee90939fad912460b18a1ffe # v4.1.2
with:
name: openapi-base
path: openapi-base
diff --git a/.github/workflows/ci-tests.yml b/.github/workflows/ci-tests.yml
index 0dacbc5c6..4b5db14ae 100644
--- a/.github/workflows/ci-tests.yml
+++ b/.github/workflows/ci-tests.yml
@@ -34,7 +34,7 @@ jobs:
--verbosity minimal
- name: Merge code coverage results
- uses: danielpalme/ReportGenerator-GitHub-Action@4d510cbed8a05af5aefea46c7fd6e05b95844c89 # 5.2.0
+ uses: danielpalme/ReportGenerator-GitHub-Action@68f1963d9876d2ac78bfd1c41c395514b7318855 # 5.2.1
with:
reports: "**/coverage.cobertura.xml"
targetdir: "merged/"
diff --git a/.vscode/extensions.json b/.vscode/extensions.json
index d738e9fba..3be946e44 100644
--- a/.vscode/extensions.json
+++ b/.vscode/extensions.json
@@ -2,7 +2,7 @@
"recommendations": [
"ms-dotnettools.csharp",
"editorconfig.editorconfig",
- "GitHub.vscode-github-actions",
+ "github.vscode-github-actions",
"ms-dotnettools.vscode-dotnet-runtime",
"ms-dotnettools.csdevkit"
],
diff --git a/.vscode/launch.json b/.vscode/launch.json
index be55764fd..7e50d4f0a 100644
--- a/.vscode/launch.json
+++ b/.vscode/launch.json
@@ -30,6 +30,18 @@
"internalConsoleOptions": "openOnSessionStart"
},
{
+ "name": "ghcs .NET Launch (nowebclient, ffmpeg)",
+ "type": "coreclr",
+ "request": "launch",
+ "preLaunchTask": "build",
+ "program": "${workspaceFolder}/Jellyfin.Server/bin/Debug/net8.0/jellyfin.dll",
+ "args": ["--nowebclient", "--ffmpeg", "/usr/lib/jellyfin-ffmpeg/ffmpeg"],
+ "cwd": "${workspaceFolder}/Jellyfin.Server",
+ "console": "internalConsole",
+ "stopAtEntry": false,
+ "internalConsoleOptions": "openOnSessionStart"
+ },
+ {
"name": ".NET Attach",
"type": "coreclr",
"request": "attach",
diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md
index 457f59e0f..55642e4e2 100644
--- a/CONTRIBUTORS.md
+++ b/CONTRIBUTORS.md
@@ -4,6 +4,7 @@
- [97carmine](https://github.com/97carmine)
- [Abbe98](https://github.com/Abbe98)
- [agrenott](https://github.com/agrenott)
+ - [alltilla](https://github.com/alltilla)
- [AndreCarvalho](https://github.com/AndreCarvalho)
- [anthonylavado](https://github.com/anthonylavado)
- [Artiume](https://github.com/Artiume)
@@ -77,6 +78,7 @@
- [Marenz](https://github.com/Marenz)
- [marius-luca-87](https://github.com/marius-luca-87)
- [mark-monteiro](https://github.com/mark-monteiro)
+ - [MarkCiliaVincenti](https://github.com/MarkCiliaVincenti)
- [Matt07211](https://github.com/Matt07211)
- [Maxr1998](https://github.com/Maxr1998)
- [mcarlton00](https://github.com/mcarlton00)
@@ -175,7 +177,9 @@
- [Chris-Codes-It](https://github.com/Chris-Codes-It)
- [Pithaya](https://github.com/Pithaya)
- [Çağrı Sakaoğlu](https://github.com/ilovepilav)
+ _ [Barasingha](https://github.com/MaVdbussche)
- [Gauvino](https://github.com/Gauvino)
+ - [felix920506](https://github.com/felix920506)
# Emby Contributors
@@ -247,3 +251,4 @@
- [Utku Özdemir](https://github.com/utkuozdemir)
- [JPUC1143](https://github.com/Jpuc1143/)
- [0x25CBFC4F](https://github.com/0x25CBFC4F)
+ - [Robert Lützner](https://github.com/rluetzner)
diff --git a/Directory.Packages.props b/Directory.Packages.props
index c88b9e808..1d7ebfaf4 100644
--- a/Directory.Packages.props
+++ b/Directory.Packages.props
@@ -4,34 +4,35 @@
</PropertyGroup>
<!-- Run "dotnet list package (dash,dash)outdated" to see the latest versions of each package.-->
<ItemGroup Label="Package Dependencies">
+ <PackageVersion Include="AsyncKeyedLock" Version="6.3.4" />
<PackageVersion Include="AutoFixture.AutoMoq" Version="4.18.1" />
<PackageVersion Include="AutoFixture.Xunit2" Version="4.18.1" />
<PackageVersion Include="AutoFixture" Version="4.18.1" />
<PackageVersion Include="BDInfo" Version="0.7.6.2" />
- <PackageVersion Include="BlurHashSharp.SkiaSharp" Version="1.3.0" />
- <PackageVersion Include="BlurHashSharp" Version="1.3.0" />
+ <PackageVersion Include="BlurHashSharp.SkiaSharp" Version="1.3.2" />
+ <PackageVersion Include="BlurHashSharp" Version="1.3.2" />
<PackageVersion Include="CommandLineParser" Version="2.9.1" />
- <PackageVersion Include="coverlet.collector" Version="6.0.0" />
+ <PackageVersion Include="coverlet.collector" Version="6.0.1" />
<PackageVersion Include="Diacritics" Version="3.3.27" />
<PackageVersion Include="DiscUtils.Udf" Version="0.16.13" />
<PackageVersion Include="DotNet.Glob" Version="3.1.3" />
- <PackageVersion Include="EFCoreSecondLevelCacheInterceptor" Version="4.2.0" />
+ <PackageVersion Include="EFCoreSecondLevelCacheInterceptor" Version="4.2.2" />
<PackageVersion Include="FsCheck.Xunit" Version="2.16.6" />
<PackageVersion Include="HarfBuzzSharp.NativeAssets.Linux" Version="7.3.0.1" />
- <PackageVersion Include="IDisposableAnalyzers" Version="4.0.4" />
+ <PackageVersion Include="IDisposableAnalyzers" Version="4.0.7" />
<PackageVersion Include="Jellyfin.XmlTv" Version="10.8.0" />
<PackageVersion Include="libse" Version="3.6.13" />
<PackageVersion Include="LrcParser" Version="2023.524.0" />
<PackageVersion Include="MetaBrainz.MusicBrainz" Version="6.1.0" />
- <PackageVersion Include="Microsoft.AspNetCore.Authorization" Version="8.0.1" />
+ <PackageVersion Include="Microsoft.AspNetCore.Authorization" Version="8.0.2" />
<PackageVersion Include="Microsoft.AspNetCore.HttpOverrides" Version="2.2.0" />
- <PackageVersion Include="Microsoft.AspNetCore.Mvc.Testing" Version="8.0.1" />
+ <PackageVersion Include="Microsoft.AspNetCore.Mvc.Testing" Version="8.0.2" />
<PackageVersion Include="Microsoft.CodeAnalysis.BannedApiAnalyzers" Version="3.3.4" />
- <PackageVersion Include="Microsoft.Data.Sqlite" Version="8.0.1" />
- <PackageVersion Include="Microsoft.EntityFrameworkCore.Design" Version="8.0.1" />
- <PackageVersion Include="Microsoft.EntityFrameworkCore.Relational" Version="8.0.1" />
- <PackageVersion Include="Microsoft.EntityFrameworkCore.Sqlite" Version="8.0.1" />
- <PackageVersion Include="Microsoft.EntityFrameworkCore.Tools" Version="8.0.1" />
+ <PackageVersion Include="Microsoft.Data.Sqlite" Version="8.0.2" />
+ <PackageVersion Include="Microsoft.EntityFrameworkCore.Design" Version="8.0.2" />
+ <PackageVersion Include="Microsoft.EntityFrameworkCore.Relational" Version="8.0.2" />
+ <PackageVersion Include="Microsoft.EntityFrameworkCore.Sqlite" Version="8.0.2" />
+ <PackageVersion Include="Microsoft.EntityFrameworkCore.Tools" Version="8.0.2" />
<PackageVersion Include="Microsoft.Extensions.Caching.Abstractions" Version="8.0.0" />
<PackageVersion Include="Microsoft.Extensions.Caching.Memory" Version="8.0.0" />
<PackageVersion Include="Microsoft.Extensions.Configuration.Abstractions" Version="8.0.0" />
@@ -40,14 +41,14 @@
<PackageVersion Include="Microsoft.Extensions.Configuration.Json" Version="8.0.0" />
<PackageVersion Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="8.0.0" />
<PackageVersion Include="Microsoft.Extensions.DependencyInjection" Version="8.0.0" />
- <PackageVersion Include="Microsoft.Extensions.Diagnostics.HealthChecks.EntityFrameworkCore" Version="8.0.1" />
- <PackageVersion Include="Microsoft.Extensions.Diagnostics.HealthChecks" Version="8.0.1" />
+ <PackageVersion Include="Microsoft.Extensions.Diagnostics.HealthChecks.EntityFrameworkCore" Version="8.0.2" />
+ <PackageVersion Include="Microsoft.Extensions.Diagnostics.HealthChecks" Version="8.0.2" />
<PackageVersion Include="Microsoft.Extensions.Hosting.Abstractions" Version="8.0.0" />
<PackageVersion Include="Microsoft.Extensions.Http" Version="8.0.0" />
<PackageVersion Include="Microsoft.Extensions.Logging.Abstractions" Version="8.0.0" />
<PackageVersion Include="Microsoft.Extensions.Logging" Version="8.0.0" />
- <PackageVersion Include="Microsoft.Extensions.Options" Version="8.0.1" />
- <PackageVersion Include="Microsoft.NET.Test.Sdk" Version="17.8.0" />
+ <PackageVersion Include="Microsoft.Extensions.Options" Version="8.0.2" />
+ <PackageVersion Include="Microsoft.NET.Test.Sdk" Version="17.9.0" />
<PackageVersion Include="MimeTypes" Version="2.4.0" />
<PackageVersion Include="Mono.Nat" Version="3.0.4" />
<PackageVersion Include="Moq" Version="4.18.4" />
@@ -77,14 +78,14 @@
<PackageVersion Include="System.Globalization" Version="4.3.0" />
<PackageVersion Include="System.Linq.Async" Version="6.0.1" />
<PackageVersion Include="System.Text.Encoding.CodePages" Version="8.0.0" />
- <PackageVersion Include="System.Text.Json" Version="8.0.1" />
+ <PackageVersion Include="System.Text.Json" Version="8.0.2" />
<PackageVersion Include="System.Threading.Tasks.Dataflow" Version="8.0.0" />
<PackageVersion Include="TagLibSharp" Version="2.3.0" />
<PackageVersion Include="TMDbLib" Version="2.1.0" />
<PackageVersion Include="UTF.Unknown" Version="2.5.1" />
<PackageVersion Include="Xunit.Priority" Version="1.1.6" />
- <PackageVersion Include="xunit.runner.visualstudio" Version="2.5.6" />
+ <PackageVersion Include="xunit.runner.visualstudio" Version="2.5.7" />
<PackageVersion Include="Xunit.SkippableFact" Version="1.4.13" />
- <PackageVersion Include="xunit" Version="2.6.6" />
+ <PackageVersion Include="xunit" Version="2.7.0" />
</ItemGroup>
</Project>
diff --git a/Emby.Server.Implementations/ApplicationHost.cs b/Emby.Server.Implementations/ApplicationHost.cs
index 5870fed76..550c16b4c 100644
--- a/Emby.Server.Implementations/ApplicationHost.cs
+++ b/Emby.Server.Implementations/ApplicationHost.cs
@@ -62,7 +62,6 @@ using MediaBrowser.Controller.MediaEncoding;
using MediaBrowser.Controller.Net;
using MediaBrowser.Controller.Persistence;
using MediaBrowser.Controller.Playlists;
-using MediaBrowser.Controller.Plugins;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Controller.QuickConnect;
using MediaBrowser.Controller.Resolvers;
@@ -393,7 +392,7 @@ namespace Emby.Server.Implementations
/// Runs the startup tasks.
/// </summary>
/// <returns><see cref="Task" />.</returns>
- public async Task RunStartupTasksAsync()
+ public Task RunStartupTasksAsync()
{
Logger.LogInformation("Running startup tasks");
@@ -405,38 +404,10 @@ namespace Emby.Server.Implementations
Resolve<IMediaEncoder>().SetFFmpegPath();
Logger.LogInformation("ServerId: {ServerId}", SystemId);
-
- var entryPoints = GetExports<IServerEntryPoint>();
-
- var stopWatch = new Stopwatch();
- stopWatch.Start();
-
- await Task.WhenAll(StartEntryPoints(entryPoints, true)).ConfigureAwait(false);
- Logger.LogInformation("Executed all pre-startup entry points in {Elapsed:g}", stopWatch.Elapsed);
-
Logger.LogInformation("Core startup complete");
CoreStartupHasCompleted = true;
- stopWatch.Restart();
-
- await Task.WhenAll(StartEntryPoints(entryPoints, false)).ConfigureAwait(false);
- Logger.LogInformation("Executed all post-startup entry points in {Elapsed:g}", stopWatch.Elapsed);
- stopWatch.Stop();
- }
-
- private IEnumerable<Task> StartEntryPoints(IEnumerable<IServerEntryPoint> entryPoints, bool isBeforeStartup)
- {
- foreach (var entryPoint in entryPoints)
- {
- if (isBeforeStartup != (entryPoint is IRunBeforeStartup))
- {
- continue;
- }
-
- Logger.LogDebug("Starting entry point {Type}", entryPoint.GetType());
-
- yield return entryPoint.RunAsync();
- }
+ return Task.CompletedTask;
}
/// <inheritdoc/>
@@ -695,8 +666,6 @@ namespace Emby.Server.Implementations
GetExports<IMetadataSaver>(),
GetExports<IExternalId>());
- Resolve<ILiveTvManager>().AddParts(GetExports<ILiveTvService>(), GetExports<IListingsProvider>());
-
Resolve<IMediaSourceManager>().AddParts(GetExports<IMediaSourceProvider>());
}
diff --git a/Emby.Server.Implementations/EntryPoints/LibraryChangedNotifier.cs b/Emby.Server.Implementations/EntryPoints/LibraryChangedNotifier.cs
index 83e7b230d..4c668379c 100644
--- a/Emby.Server.Implementations/EntryPoints/LibraryChangedNotifier.cs
+++ b/Emby.Server.Implementations/EntryPoints/LibraryChangedNotifier.cs
@@ -13,19 +13,19 @@ using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Entities.Audio;
using MediaBrowser.Controller.Library;
-using MediaBrowser.Controller.Plugins;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Controller.Session;
using MediaBrowser.Model.Entities;
using MediaBrowser.Model.Session;
+using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
namespace Emby.Server.Implementations.EntryPoints;
/// <summary>
-/// A <see cref="IServerEntryPoint"/> that notifies users when libraries are updated.
+/// A <see cref="IHostedService"/> responsible for notifying users when libraries are updated.
/// </summary>
-public sealed class LibraryChangedNotifier : IServerEntryPoint
+public sealed class LibraryChangedNotifier : IHostedService, IDisposable
{
private readonly ILibraryManager _libraryManager;
private readonly IServerConfigurationManager _configurationManager;
@@ -70,7 +70,7 @@ public sealed class LibraryChangedNotifier : IServerEntryPoint
}
/// <inheritdoc />
- public Task RunAsync()
+ public Task StartAsync(CancellationToken cancellationToken)
{
_libraryManager.ItemAdded += OnLibraryItemAdded;
_libraryManager.ItemUpdated += OnLibraryItemUpdated;
@@ -83,6 +83,20 @@ public sealed class LibraryChangedNotifier : IServerEntryPoint
return Task.CompletedTask;
}
+ /// <inheritdoc />
+ public Task StopAsync(CancellationToken cancellationToken)
+ {
+ _libraryManager.ItemAdded -= OnLibraryItemAdded;
+ _libraryManager.ItemUpdated -= OnLibraryItemUpdated;
+ _libraryManager.ItemRemoved -= OnLibraryItemRemoved;
+
+ _providerManager.RefreshCompleted -= OnProviderRefreshCompleted;
+ _providerManager.RefreshStarted -= OnProviderRefreshStarted;
+ _providerManager.RefreshProgress -= OnProviderRefreshProgress;
+
+ return Task.CompletedTask;
+ }
+
private void OnProviderRefreshProgress(object? sender, GenericEventArgs<Tuple<BaseItem, double>> e)
{
var item = e.Argument.Item1;
@@ -137,9 +151,7 @@ public sealed class LibraryChangedNotifier : IServerEntryPoint
}
private void OnProviderRefreshStarted(object? sender, GenericEventArgs<BaseItem> e)
- {
- OnProviderRefreshProgress(sender, new GenericEventArgs<Tuple<BaseItem, double>>(new Tuple<BaseItem, double>(e.Argument, 0)));
- }
+ => OnProviderRefreshProgress(sender, new GenericEventArgs<Tuple<BaseItem, double>>(new Tuple<BaseItem, double>(e.Argument, 0)));
private void OnProviderRefreshCompleted(object? sender, GenericEventArgs<BaseItem> e)
{
@@ -342,7 +354,7 @@ public sealed class LibraryChangedNotifier : IServerEntryPoint
return item.SourceType == SourceType.Library;
}
- private IEnumerable<string> GetTopParentIds(List<BaseItem> items, List<Folder> allUserRootChildren)
+ private static IEnumerable<string> GetTopParentIds(List<BaseItem> items, List<Folder> allUserRootChildren)
{
var list = new List<string>();
@@ -363,7 +375,7 @@ public sealed class LibraryChangedNotifier : IServerEntryPoint
return list.Distinct(StringComparer.Ordinal);
}
- private IEnumerable<T> TranslatePhysicalItemToUserLibrary<T>(T item, User user, bool includeIfNotFound = false)
+ private T[] TranslatePhysicalItemToUserLibrary<T>(T item, User user, bool includeIfNotFound = false)
where T : BaseItem
{
// If the physical root changed, return the user root
@@ -384,18 +396,7 @@ public sealed class LibraryChangedNotifier : IServerEntryPoint
/// <inheritdoc />
public void Dispose()
{
- _libraryManager.ItemAdded -= OnLibraryItemAdded;
- _libraryManager.ItemUpdated -= OnLibraryItemUpdated;
- _libraryManager.ItemRemoved -= OnLibraryItemRemoved;
-
- _providerManager.RefreshCompleted -= OnProviderRefreshCompleted;
- _providerManager.RefreshStarted -= OnProviderRefreshStarted;
- _providerManager.RefreshProgress -= OnProviderRefreshProgress;
-
- if (_libraryUpdateTimer is not null)
- {
- _libraryUpdateTimer.Dispose();
- _libraryUpdateTimer = null;
- }
+ _libraryUpdateTimer?.Dispose();
+ _libraryUpdateTimer = null;
}
}
diff --git a/Emby.Server.Implementations/EntryPoints/UserDataChangeNotifier.cs b/Emby.Server.Implementations/EntryPoints/UserDataChangeNotifier.cs
index d32759017..957ad9c01 100644
--- a/Emby.Server.Implementations/EntryPoints/UserDataChangeNotifier.cs
+++ b/Emby.Server.Implementations/EntryPoints/UserDataChangeNotifier.cs
@@ -1,5 +1,3 @@
-#pragma warning disable CS1591
-
using System;
using System.Collections.Generic;
using System.Globalization;
@@ -8,14 +6,17 @@ using System.Threading;
using System.Threading.Tasks;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Library;
-using MediaBrowser.Controller.Plugins;
using MediaBrowser.Controller.Session;
using MediaBrowser.Model.Entities;
using MediaBrowser.Model.Session;
+using Microsoft.Extensions.Hosting;
namespace Emby.Server.Implementations.EntryPoints
{
- public sealed class UserDataChangeNotifier : IServerEntryPoint
+ /// <summary>
+ /// <see cref="IHostedService"/> responsible for notifying users when associated item data is updated.
+ /// </summary>
+ public sealed class UserDataChangeNotifier : IHostedService, IDisposable
{
private const int UpdateDuration = 500;
@@ -23,25 +24,43 @@ namespace Emby.Server.Implementations.EntryPoints
private readonly IUserDataManager _userDataManager;
private readonly IUserManager _userManager;
- private readonly Dictionary<Guid, List<BaseItem>> _changedItems = new Dictionary<Guid, List<BaseItem>>();
+ private readonly Dictionary<Guid, List<BaseItem>> _changedItems = new();
+ private readonly object _syncLock = new();
- private readonly object _syncLock = new object();
private Timer? _updateTimer;
- public UserDataChangeNotifier(IUserDataManager userDataManager, ISessionManager sessionManager, IUserManager userManager)
+ /// <summary>
+ /// Initializes a new instance of the <see cref="UserDataChangeNotifier"/> class.
+ /// </summary>
+ /// <param name="userDataManager">The <see cref="IUserDataManager"/>.</param>
+ /// <param name="sessionManager">The <see cref="ISessionManager"/>.</param>
+ /// <param name="userManager">The <see cref="IUserManager"/>.</param>
+ public UserDataChangeNotifier(
+ IUserDataManager userDataManager,
+ ISessionManager sessionManager,
+ IUserManager userManager)
{
_userDataManager = userDataManager;
_sessionManager = sessionManager;
_userManager = userManager;
}
- public Task RunAsync()
+ /// <inheritdoc />
+ public Task StartAsync(CancellationToken cancellationToken)
{
_userDataManager.UserDataSaved += OnUserDataManagerUserDataSaved;
return Task.CompletedTask;
}
+ /// <inheritdoc />
+ public Task StopAsync(CancellationToken cancellationToken)
+ {
+ _userDataManager.UserDataSaved -= OnUserDataManagerUserDataSaved;
+
+ return Task.CompletedTask;
+ }
+
private void OnUserDataManagerUserDataSaved(object? sender, UserDataSaveEventArgs e)
{
if (e.SaveReason == UserDataSaveReason.PlaybackProgress)
@@ -103,55 +122,40 @@ namespace Emby.Server.Implementations.EntryPoints
}
}
- await SendNotifications(changes, CancellationToken.None).ConfigureAwait(false);
- }
-
- private async Task SendNotifications(List<KeyValuePair<Guid, List<BaseItem>>> changes, CancellationToken cancellationToken)
- {
- foreach ((var key, var value) in changes)
+ foreach (var (userId, changedItems) in changes)
{
- await SendNotifications(key, value, cancellationToken).ConfigureAwait(false);
+ await _sessionManager.SendMessageToUserSessions(
+ [userId],
+ SessionMessageType.UserDataChanged,
+ () => GetUserDataChangeInfo(userId, changedItems),
+ default).ConfigureAwait(false);
}
}
- private Task SendNotifications(Guid userId, List<BaseItem> changedItems, CancellationToken cancellationToken)
- {
- return _sessionManager.SendMessageToUserSessions(new List<Guid> { userId }, SessionMessageType.UserDataChanged, () => GetUserDataChangeInfo(userId, changedItems), cancellationToken);
- }
-
private UserDataChangeInfo GetUserDataChangeInfo(Guid userId, List<BaseItem> changedItems)
{
var user = _userManager.GetUserById(userId);
- var dtoList = changedItems
- .DistinctBy(x => x.Id)
- .Select(i =>
- {
- var dto = _userDataManager.GetUserDataDto(i, user);
- dto.ItemId = i.Id.ToString("N", CultureInfo.InvariantCulture);
- return dto;
- })
- .ToArray();
-
- var userIdString = userId.ToString("N", CultureInfo.InvariantCulture);
-
return new UserDataChangeInfo
{
- UserId = userIdString,
-
- UserDataList = dtoList
+ UserId = userId.ToString("N", CultureInfo.InvariantCulture),
+ UserDataList = changedItems
+ .DistinctBy(x => x.Id)
+ .Select(i =>
+ {
+ var dto = _userDataManager.GetUserDataDto(i, user);
+ dto.ItemId = i.Id.ToString("N", CultureInfo.InvariantCulture);
+ return dto;
+ })
+ .ToArray()
};
}
+ /// <inheritdoc />
public void Dispose()
{
- if (_updateTimer is not null)
- {
- _updateTimer.Dispose();
- _updateTimer = null;
- }
-
- _userDataManager.UserDataSaved -= OnUserDataManagerUserDataSaved;
+ _updateTimer?.Dispose();
+ _updateTimer = null;
}
}
}
diff --git a/Emby.Server.Implementations/IO/LibraryMonitor.cs b/Emby.Server.Implementations/IO/LibraryMonitor.cs
index dde38906f..31617d1a5 100644
--- a/Emby.Server.Implementations/IO/LibraryMonitor.cs
+++ b/Emby.Server.Implementations/IO/LibraryMonitor.cs
@@ -1,5 +1,3 @@
-#pragma warning disable CS1591
-
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
@@ -11,11 +9,13 @@ using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Library;
using MediaBrowser.Model.IO;
+using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
namespace Emby.Server.Implementations.IO
{
- public class LibraryMonitor : ILibraryMonitor
+ /// <inheritdoc cref="ILibraryMonitor" />
+ public sealed class LibraryMonitor : ILibraryMonitor, IDisposable
{
private readonly ILogger<LibraryMonitor> _logger;
private readonly ILibraryManager _libraryManager;
@@ -25,19 +25,19 @@ namespace Emby.Server.Implementations.IO
/// <summary>
/// The file system watchers.
/// </summary>
- private readonly ConcurrentDictionary<string, FileSystemWatcher> _fileSystemWatchers = new ConcurrentDictionary<string, FileSystemWatcher>(StringComparer.OrdinalIgnoreCase);
+ private readonly ConcurrentDictionary<string, FileSystemWatcher> _fileSystemWatchers = new(StringComparer.OrdinalIgnoreCase);
/// <summary>
/// The affected paths.
/// </summary>
- private readonly List<FileRefresher> _activeRefreshers = new List<FileRefresher>();
+ private readonly List<FileRefresher> _activeRefreshers = [];
/// <summary>
/// A dynamic list of paths that should be ignored. Added to during our own file system modifications.
/// </summary>
- private readonly ConcurrentDictionary<string, string> _tempIgnoredPaths = new ConcurrentDictionary<string, string>(StringComparer.OrdinalIgnoreCase);
+ private readonly ConcurrentDictionary<string, string> _tempIgnoredPaths = new(StringComparer.OrdinalIgnoreCase);
- private bool _disposed = false;
+ private bool _disposed;
/// <summary>
/// Initializes a new instance of the <see cref="LibraryMonitor" /> class.
@@ -46,34 +46,31 @@ namespace Emby.Server.Implementations.IO
/// <param name="libraryManager">The library manager.</param>
/// <param name="configurationManager">The configuration manager.</param>
/// <param name="fileSystem">The filesystem.</param>
+ /// <param name="appLifetime">The <see cref="IHostApplicationLifetime"/>.</param>
public LibraryMonitor(
ILogger<LibraryMonitor> logger,
ILibraryManager libraryManager,
IServerConfigurationManager configurationManager,
- IFileSystem fileSystem)
+ IFileSystem fileSystem,
+ IHostApplicationLifetime appLifetime)
{
_libraryManager = libraryManager;
_logger = logger;
_configurationManager = configurationManager;
_fileSystem = fileSystem;
- }
- /// <summary>
- /// Add the path to our temporary ignore list. Use when writing to a path within our listening scope.
- /// </summary>
- /// <param name="path">The path.</param>
- private void TemporarilyIgnore(string path)
- {
- _tempIgnoredPaths[path] = path;
+ appLifetime.ApplicationStarted.Register(Start);
}
+ /// <inheritdoc />
public void ReportFileSystemChangeBeginning(string path)
{
ArgumentException.ThrowIfNullOrEmpty(path);
- TemporarilyIgnore(path);
+ _tempIgnoredPaths[path] = path;
}
+ /// <inheritdoc />
public async void ReportFileSystemChangeComplete(string path, bool refreshPath)
{
ArgumentException.ThrowIfNullOrEmpty(path);
@@ -107,14 +104,10 @@ namespace Emby.Server.Implementations.IO
var options = _libraryManager.GetLibraryOptions(item);
- if (options is not null)
- {
- return options.EnableRealtimeMonitor;
- }
-
- return false;
+ return options is not null && options.EnableRealtimeMonitor;
}
+ /// <inheritdoc />
public void Start()
{
_libraryManager.ItemAdded += OnLibraryManagerItemAdded;
@@ -306,21 +299,12 @@ namespace Emby.Server.Implementations.IO
{
if (removeFromList)
{
- RemoveWatcherFromList(watcher);
+ _fileSystemWatchers.TryRemove(watcher.Path, out _);
}
}
}
/// <summary>
- /// Removes the watcher from list.
- /// </summary>
- /// <param name="watcher">The watcher.</param>
- private void RemoveWatcherFromList(FileSystemWatcher watcher)
- {
- _fileSystemWatchers.TryRemove(watcher.Path, out _);
- }
-
- /// <summary>
/// Handles the Error event of the watcher control.
/// </summary>
/// <param name="sender">The source of the event.</param>
@@ -352,6 +336,7 @@ namespace Emby.Server.Implementations.IO
}
}
+ /// <inheritdoc />
public void ReportFileSystemChanged(string path)
{
ArgumentException.ThrowIfNullOrEmpty(path);
@@ -479,31 +464,15 @@ namespace Emby.Server.Implementations.IO
}
}
- /// <summary>
- /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
- /// </summary>
+ /// <inheritdoc />
public void Dispose()
{
- Dispose(true);
- GC.SuppressFinalize(this);
- }
-
- /// <summary>
- /// Releases unmanaged and - optionally - managed resources.
- /// </summary>
- /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
- protected virtual void Dispose(bool disposing)
- {
if (_disposed)
{
return;
}
- if (disposing)
- {
- Stop();
- }
-
+ Stop();
_disposed = true;
}
}
diff --git a/Emby.Server.Implementations/IO/LibraryMonitorStartup.cs b/Emby.Server.Implementations/IO/LibraryMonitorStartup.cs
deleted file mode 100644
index c51cf0545..000000000
--- a/Emby.Server.Implementations/IO/LibraryMonitorStartup.cs
+++ /dev/null
@@ -1,35 +0,0 @@
-using System.Threading.Tasks;
-using MediaBrowser.Controller.Library;
-using MediaBrowser.Controller.Plugins;
-
-namespace Emby.Server.Implementations.IO
-{
- /// <summary>
- /// <see cref="IServerEntryPoint" /> which is responsible for starting the library monitor.
- /// </summary>
- public sealed class LibraryMonitorStartup : IServerEntryPoint
- {
- private readonly ILibraryMonitor _monitor;
-
- /// <summary>
- /// Initializes a new instance of the <see cref="LibraryMonitorStartup"/> class.
- /// </summary>
- /// <param name="monitor">The library monitor.</param>
- public LibraryMonitorStartup(ILibraryMonitor monitor)
- {
- _monitor = monitor;
- }
-
- /// <inheritdoc />
- public Task RunAsync()
- {
- _monitor.Start();
- return Task.CompletedTask;
- }
-
- /// <inheritdoc />
- public void Dispose()
- {
- }
- }
-}
diff --git a/Emby.Server.Implementations/Library/LibraryManager.cs b/Emby.Server.Implementations/Library/LibraryManager.cs
index 8ae913dad..7998ce34a 100644
--- a/Emby.Server.Implementations/Library/LibraryManager.cs
+++ b/Emby.Server.Implementations/Library/LibraryManager.cs
@@ -22,7 +22,6 @@ using Jellyfin.Data.Entities;
using Jellyfin.Data.Enums;
using Jellyfin.Extensions;
using MediaBrowser.Common.Extensions;
-using MediaBrowser.Common.Progress;
using MediaBrowser.Controller;
using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Drawing;
@@ -1022,7 +1021,7 @@ namespace Emby.Server.Implementations.Library
// Start by just validating the children of the root, but go no further
await RootFolder.ValidateChildren(
- new SimpleProgress<double>(),
+ new Progress<double>(),
new MetadataRefreshOptions(new DirectoryService(_fileSystem)),
recursive: false,
cancellationToken).ConfigureAwait(false);
@@ -1030,7 +1029,7 @@ namespace Emby.Server.Implementations.Library
await GetUserRootFolder().RefreshMetadata(cancellationToken).ConfigureAwait(false);
await GetUserRootFolder().ValidateChildren(
- new SimpleProgress<double>(),
+ new Progress<double>(),
new MetadataRefreshOptions(new DirectoryService(_fileSystem)),
recursive: false,
cancellationToken).ConfigureAwait(false);
@@ -1048,18 +1047,14 @@ namespace Emby.Server.Implementations.Library
await ValidateTopLibraryFolders(cancellationToken).ConfigureAwait(false);
- var innerProgress = new ActionableProgress<double>();
-
- innerProgress.RegisterAction(pct => progress.Report(pct * 0.96));
+ var innerProgress = new Progress<double>(pct => progress.Report(pct * 0.96));
// Validate the entire media library
await RootFolder.ValidateChildren(innerProgress, new MetadataRefreshOptions(new DirectoryService(_fileSystem)), recursive: true, cancellationToken).ConfigureAwait(false);
progress.Report(96);
- innerProgress = new ActionableProgress<double>();
-
- innerProgress.RegisterAction(pct => progress.Report(96 + (pct * .04)));
+ innerProgress = new Progress<double>(pct => progress.Report(96 + (pct * .04)));
await RunPostScanTasks(innerProgress, cancellationToken).ConfigureAwait(false);
@@ -1081,12 +1076,10 @@ namespace Emby.Server.Implementations.Library
foreach (var task in tasks)
{
- var innerProgress = new ActionableProgress<double>();
-
// Prevent access to modified closure
var currentNumComplete = numComplete;
- innerProgress.RegisterAction(pct =>
+ var innerProgress = new Progress<double>(pct =>
{
double innerPercent = pct;
innerPercent /= 100;
@@ -2954,7 +2947,7 @@ namespace Emby.Server.Implementations.Library
Task.Run(() =>
{
// No need to start if scanning the library because it will handle it
- ValidateMediaLibrary(new SimpleProgress<double>(), CancellationToken.None);
+ ValidateMediaLibrary(new Progress<double>(), CancellationToken.None);
});
}
diff --git a/Emby.Server.Implementations/Library/LiveStreamHelper.cs b/Emby.Server.Implementations/Library/LiveStreamHelper.cs
index 59d705ace..d4aeae41a 100644
--- a/Emby.Server.Implementations/Library/LiveStreamHelper.cs
+++ b/Emby.Server.Implementations/Library/LiveStreamHelper.cs
@@ -48,20 +48,23 @@ namespace Emby.Server.Implementations.Library
if (!string.IsNullOrEmpty(cacheKey))
{
- FileStream jsonStream = AsyncFile.OpenRead(cacheFilePath);
try
{
- mediaInfo = await JsonSerializer.DeserializeAsync<MediaInfo>(jsonStream, _jsonOptions, cancellationToken).ConfigureAwait(false);
+ FileStream jsonStream = AsyncFile.OpenRead(cacheFilePath);
- // _logger.LogDebug("Found cached media info");
+ await using (jsonStream.ConfigureAwait(false))
+ {
+ mediaInfo = await JsonSerializer.DeserializeAsync<MediaInfo>(jsonStream, _jsonOptions, cancellationToken).ConfigureAwait(false);
+ // _logger.LogDebug("Found cached media info");
+ }
}
- catch (Exception ex)
+ catch (IOException ex)
{
- _logger.LogError(ex, "Error deserializing mediainfo cache");
+ _logger.LogDebug(ex, "Could not open cached media info");
}
- finally
+ catch (Exception ex)
{
- await jsonStream.DisposeAsync().ConfigureAwait(false);
+ _logger.LogError(ex, "Error opening cached media info");
}
}
diff --git a/Emby.Server.Implementations/Library/MediaSourceManager.cs b/Emby.Server.Implementations/Library/MediaSourceManager.cs
index c38f1af91..18ada6aeb 100644
--- a/Emby.Server.Implementations/Library/MediaSourceManager.cs
+++ b/Emby.Server.Implementations/Library/MediaSourceManager.cs
@@ -11,6 +11,7 @@ using System.Linq;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
+using AsyncKeyedLock;
using Jellyfin.Data.Entities;
using Jellyfin.Data.Enums;
using Jellyfin.Extensions;
@@ -52,7 +53,7 @@ namespace Emby.Server.Implementations.Library
private readonly IDirectoryService _directoryService;
private readonly ConcurrentDictionary<string, ILiveStream> _openStreams = new ConcurrentDictionary<string, ILiveStream>(StringComparer.OrdinalIgnoreCase);
- private readonly SemaphoreSlim _liveStreamSemaphore = new SemaphoreSlim(1, 1);
+ private readonly AsyncNonKeyedLocker _liveStreamLocker = new(1);
private readonly JsonSerializerOptions _jsonOptions = JsonDefaults.Options;
private IMediaSourceProvider[] _providers;
@@ -468,12 +469,10 @@ namespace Emby.Server.Implementations.Library
public async Task<Tuple<LiveStreamResponse, IDirectStreamProvider>> OpenLiveStreamInternal(LiveStreamRequest request, CancellationToken cancellationToken)
{
- await _liveStreamSemaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
-
MediaSourceInfo mediaSource;
ILiveStream liveStream;
- try
+ using (await _liveStreamLocker.LockAsync(cancellationToken).ConfigureAwait(false))
{
var (provider, keyId) = GetProvider(request.OpenToken);
@@ -493,10 +492,6 @@ namespace Emby.Server.Implementations.Library
_openStreams[mediaSource.LiveStreamId] = liveStream;
}
- finally
- {
- _liveStreamSemaphore.Release();
- }
try
{
@@ -837,9 +832,7 @@ namespace Emby.Server.Implementations.Library
{
ArgumentException.ThrowIfNullOrEmpty(id);
- await _liveStreamSemaphore.WaitAsync().ConfigureAwait(false);
-
- try
+ using (await _liveStreamLocker.LockAsync().ConfigureAwait(false))
{
if (_openStreams.TryGetValue(id, out ILiveStream liveStream))
{
@@ -858,10 +851,6 @@ namespace Emby.Server.Implementations.Library
}
}
}
- finally
- {
- _liveStreamSemaphore.Release();
- }
}
private (IMediaSourceProvider MediaSourceProvider, string KeyId) GetProvider(string key)
@@ -898,7 +887,7 @@ namespace Emby.Server.Implementations.Library
CloseLiveStream(key).GetAwaiter().GetResult();
}
- _liveStreamSemaphore.Dispose();
+ _liveStreamLocker.Dispose();
}
}
}
diff --git a/Emby.Server.Implementations/Localization/Core/et.json b/Emby.Server.Implementations/Localization/Core/et.json
index c78ffa28c..977307b06 100644
--- a/Emby.Server.Implementations/Localization/Core/et.json
+++ b/Emby.Server.Implementations/Localization/Core/et.json
@@ -31,7 +31,7 @@
"VersionNumber": "Versioon {0}",
"ValueSpecialEpisodeName": "Eriepisood - {0}",
"ValueHasBeenAddedToLibrary": "{0} lisati meediakogusse",
- "UserStartedPlayingItemWithValues": "{0} taasesitab {1} serveris {2}",
+ "UserStartedPlayingItemWithValues": "{0} taasesitab {1} seadmes {2}",
"UserPasswordChangedWithName": "Kasutaja {0} parool muudeti",
"UserLockedOutWithName": "Kasutaja {0} lukustati",
"UserDeletedWithName": "Kasutaja {0} kustutati",
diff --git a/Emby.Server.Implementations/Localization/Core/ga.json b/Emby.Server.Implementations/Localization/Core/ga.json
new file mode 100644
index 000000000..28e54bff5
--- /dev/null
+++ b/Emby.Server.Implementations/Localization/Core/ga.json
@@ -0,0 +1,3 @@
+{
+ "Albums": "Albaim"
+}
diff --git a/Emby.Server.Implementations/Localization/Core/ky.json b/Emby.Server.Implementations/Localization/Core/ky.json
new file mode 100644
index 000000000..0967ef424
--- /dev/null
+++ b/Emby.Server.Implementations/Localization/Core/ky.json
@@ -0,0 +1 @@
+{}
diff --git a/Emby.Server.Implementations/Localization/Core/mk.json b/Emby.Server.Implementations/Localization/Core/mk.json
index cbccad87f..7ef907918 100644
--- a/Emby.Server.Implementations/Localization/Core/mk.json
+++ b/Emby.Server.Implementations/Localization/Core/mk.json
@@ -122,5 +122,6 @@
"TaskRefreshChapterImagesDescription": "Создава тамбнеил за видеата шти имаат поглавја.",
"TaskCleanActivityLogDescription": "Избришува логови на активности постари од определеното време.",
"TaskCleanActivityLog": "Избриши Лог на Активности",
- "External": "Надворешен"
+ "External": "Надворешен",
+ "HearingImpaired": "Оштетен слух"
}
diff --git a/Emby.Server.Implementations/Localization/Core/or.json b/Emby.Server.Implementations/Localization/Core/or.json
index 0e9d81ee8..8251c1290 100644
--- a/Emby.Server.Implementations/Localization/Core/or.json
+++ b/Emby.Server.Implementations/Localization/Core/or.json
@@ -1,4 +1,12 @@
{
"External": "ବହିଃସ୍ଥ",
- "Genres": "ଧରଣ"
+ "Genres": "ଧରଣ",
+ "Albums": "ଆଲବମଗୁଡ଼ିକ",
+ "Artists": "କଳାକାରଗୁଡ଼ିକ",
+ "Application": "ଆପ୍ଲିକେସନ",
+ "Books": "ବହିଗୁଡ଼ିକ",
+ "Channels": "ଚ୍ୟାନେଲଗୁଡ଼ିକ",
+ "ChapterNameValue": "ବିଭାଗ {0}",
+ "Collections": "ସଂଗ୍ରହଗୁଡ଼ିକ",
+ "Folders": "ଫୋଲ୍ଡରଗୁଡ଼ିକ"
}
diff --git a/Emby.Server.Implementations/ScheduledTasks/ScheduledTaskWorker.cs b/Emby.Server.Implementations/ScheduledTasks/ScheduledTaskWorker.cs
index 1af2c96d2..efb6436ae 100644
--- a/Emby.Server.Implementations/ScheduledTasks/ScheduledTaskWorker.cs
+++ b/Emby.Server.Implementations/ScheduledTasks/ScheduledTaskWorker.cs
@@ -14,7 +14,6 @@ using Jellyfin.Data.Events;
using Jellyfin.Extensions.Json;
using MediaBrowser.Common.Configuration;
using MediaBrowser.Common.Extensions;
-using MediaBrowser.Common.Progress;
using MediaBrowser.Model.Tasks;
using Microsoft.Extensions.Logging;
@@ -371,7 +370,7 @@ namespace Emby.Server.Implementations.ScheduledTasks
throw new InvalidOperationException("Cannot execute a Task that is already running");
}
- var progress = new SimpleProgress<double>();
+ var progress = new Progress<double>();
CurrentCancellationTokenSource = new CancellationTokenSource();
diff --git a/Jellyfin.Api/Controllers/DynamicHlsController.cs b/Jellyfin.Api/Controllers/DynamicHlsController.cs
index dda1e9d56..590cdc33f 100644
--- a/Jellyfin.Api/Controllers/DynamicHlsController.cs
+++ b/Jellyfin.Api/Controllers/DynamicHlsController.cs
@@ -294,9 +294,7 @@ public class DynamicHlsController : BaseJellyfinApiController
if (!System.IO.File.Exists(playlistPath))
{
- var transcodingLock = _transcodeManager.GetTranscodingLock(playlistPath);
- await transcodingLock.WaitAsync(cancellationToken).ConfigureAwait(false);
- try
+ using (await _transcodeManager.LockAsync(playlistPath, cancellationToken).ConfigureAwait(false))
{
if (!System.IO.File.Exists(playlistPath))
{
@@ -326,10 +324,6 @@ public class DynamicHlsController : BaseJellyfinApiController
}
}
}
- finally
- {
- transcodingLock.Release();
- }
}
job ??= _transcodeManager.OnTranscodeBeginRequest(playlistPath, TranscodingJobType);
@@ -1442,95 +1436,80 @@ public class DynamicHlsController : BaseJellyfinApiController
return await GetSegmentResult(state, playlistPath, segmentPath, segmentExtension, segmentId, job, cancellationToken).ConfigureAwait(false);
}
- var transcodingLock = _transcodeManager.GetTranscodingLock(playlistPath);
- await transcodingLock.WaitAsync(cancellationToken).ConfigureAwait(false);
- var released = false;
- var startTranscoding = false;
-
- try
+ using (await _transcodeManager.LockAsync(playlistPath, cancellationToken).ConfigureAwait(false))
{
+ var startTranscoding = false;
if (System.IO.File.Exists(segmentPath))
{
job = _transcodeManager.OnTranscodeBeginRequest(playlistPath, TranscodingJobType);
- transcodingLock.Release();
- released = true;
_logger.LogDebug("returning {0} [it exists, try 2]", segmentPath);
return await GetSegmentResult(state, playlistPath, segmentPath, segmentExtension, segmentId, job, cancellationToken).ConfigureAwait(false);
}
- else
- {
- var currentTranscodingIndex = GetCurrentTranscodingIndex(playlistPath, segmentExtension);
- var segmentGapRequiringTranscodingChange = 24 / state.SegmentLength;
-
- if (segmentId == -1)
- {
- _logger.LogDebug("Starting transcoding because fmp4 init file is being requested");
- startTranscoding = true;
- segmentId = 0;
- }
- else if (currentTranscodingIndex is null)
- {
- _logger.LogDebug("Starting transcoding because currentTranscodingIndex=null");
- startTranscoding = true;
- }
- else if (segmentId < currentTranscodingIndex.Value)
- {
- _logger.LogDebug("Starting transcoding because requestedIndex={0} and currentTranscodingIndex={1}", segmentId, currentTranscodingIndex);
- startTranscoding = true;
- }
- else if (segmentId - currentTranscodingIndex.Value > segmentGapRequiringTranscodingChange)
- {
- _logger.LogDebug("Starting transcoding because segmentGap is {0} and max allowed gap is {1}. requestedIndex={2}", segmentId - currentTranscodingIndex.Value, segmentGapRequiringTranscodingChange, segmentId);
- startTranscoding = true;
- }
- if (startTranscoding)
- {
- // If the playlist doesn't already exist, startup ffmpeg
- try
- {
- await _transcodeManager.KillTranscodingJobs(streamingRequest.DeviceId, streamingRequest.PlaySessionId, p => false)
- .ConfigureAwait(false);
+ var currentTranscodingIndex = GetCurrentTranscodingIndex(playlistPath, segmentExtension);
+ var segmentGapRequiringTranscodingChange = 24 / state.SegmentLength;
- if (currentTranscodingIndex.HasValue)
- {
- DeleteLastFile(playlistPath, segmentExtension, 0);
- }
+ if (segmentId == -1)
+ {
+ _logger.LogDebug("Starting transcoding because fmp4 init file is being requested");
+ startTranscoding = true;
+ segmentId = 0;
+ }
+ else if (currentTranscodingIndex is null)
+ {
+ _logger.LogDebug("Starting transcoding because currentTranscodingIndex=null");
+ startTranscoding = true;
+ }
+ else if (segmentId < currentTranscodingIndex.Value)
+ {
+ _logger.LogDebug("Starting transcoding because requestedIndex={0} and currentTranscodingIndex={1}", segmentId, currentTranscodingIndex);
+ startTranscoding = true;
+ }
+ else if (segmentId - currentTranscodingIndex.Value > segmentGapRequiringTranscodingChange)
+ {
+ _logger.LogDebug("Starting transcoding because segmentGap is {0} and max allowed gap is {1}. requestedIndex={2}", segmentId - currentTranscodingIndex.Value, segmentGapRequiringTranscodingChange, segmentId);
+ startTranscoding = true;
+ }
- streamingRequest.StartTimeTicks = streamingRequest.CurrentRuntimeTicks;
+ if (startTranscoding)
+ {
+ // If the playlist doesn't already exist, startup ffmpeg
+ try
+ {
+ await _transcodeManager.KillTranscodingJobs(streamingRequest.DeviceId, streamingRequest.PlaySessionId, p => false)
+ .ConfigureAwait(false);
- state.WaitForPath = segmentPath;
- job = await _transcodeManager.StartFfMpeg(
- state,
- playlistPath,
- GetCommandLineArguments(playlistPath, state, false, segmentId),
- Request.HttpContext.User.GetUserId(),
- TranscodingJobType,
- cancellationTokenSource).ConfigureAwait(false);
- }
- catch
+ if (currentTranscodingIndex.HasValue)
{
- state.Dispose();
- throw;
+ DeleteLastFile(playlistPath, segmentExtension, 0);
}
- // await WaitForMinimumSegmentCount(playlistPath, 1, cancellationTokenSource.Token).ConfigureAwait(false);
+ streamingRequest.StartTimeTicks = streamingRequest.CurrentRuntimeTicks;
+
+ state.WaitForPath = segmentPath;
+ job = await _transcodeManager.StartFfMpeg(
+ state,
+ playlistPath,
+ GetCommandLineArguments(playlistPath, state, false, segmentId),
+ Request.HttpContext.User.GetUserId(),
+ TranscodingJobType,
+ cancellationTokenSource).ConfigureAwait(false);
}
- else
+ catch
{
- job = _transcodeManager.OnTranscodeBeginRequest(playlistPath, TranscodingJobType);
- if (job?.TranscodingThrottler is not null)
- {
- await job.TranscodingThrottler.UnpauseTranscoding().ConfigureAwait(false);
- }
+ state.Dispose();
+ throw;
}
+
+ // await WaitForMinimumSegmentCount(playlistPath, 1, cancellationTokenSource.Token).ConfigureAwait(false);
}
- }
- finally
- {
- if (!released)
+ else
{
- transcodingLock.Release();
+ job = _transcodeManager.OnTranscodeBeginRequest(playlistPath, TranscodingJobType);
+ if (job?.TranscodingThrottler is not null)
+ {
+ await job.TranscodingThrottler.UnpauseTranscoding().ConfigureAwait(false);
+ }
}
}
diff --git a/Jellyfin.Api/Controllers/LibraryController.cs b/Jellyfin.Api/Controllers/LibraryController.cs
index a0bbc961f..e357588d1 100644
--- a/Jellyfin.Api/Controllers/LibraryController.cs
+++ b/Jellyfin.Api/Controllers/LibraryController.cs
@@ -7,7 +7,6 @@ using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Jellyfin.Api.Attributes;
-using Jellyfin.Api.Constants;
using Jellyfin.Api.Extensions;
using Jellyfin.Api.Helpers;
using Jellyfin.Api.ModelBinders;
@@ -17,7 +16,6 @@ using Jellyfin.Data.Enums;
using Jellyfin.Extensions;
using MediaBrowser.Common.Api;
using MediaBrowser.Common.Extensions;
-using MediaBrowser.Common.Progress;
using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Dto;
using MediaBrowser.Controller.Entities;
@@ -313,7 +311,7 @@ public class LibraryController : BaseJellyfinApiController
{
try
{
- await _libraryManager.ValidateMediaLibrary(new SimpleProgress<double>(), CancellationToken.None).ConfigureAwait(false);
+ await _libraryManager.ValidateMediaLibrary(new Progress<double>(), CancellationToken.None).ConfigureAwait(false);
}
catch (Exception ex)
{
diff --git a/Jellyfin.Api/Controllers/LibraryStructureController.cs b/Jellyfin.Api/Controllers/LibraryStructureController.cs
index d483ca4d2..23c430f85 100644
--- a/Jellyfin.Api/Controllers/LibraryStructureController.cs
+++ b/Jellyfin.Api/Controllers/LibraryStructureController.cs
@@ -6,11 +6,9 @@ using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
-using Jellyfin.Api.Constants;
using Jellyfin.Api.ModelBinders;
using Jellyfin.Api.Models.LibraryStructureDto;
using MediaBrowser.Common.Api;
-using MediaBrowser.Common.Progress;
using MediaBrowser.Controller;
using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Entities;
@@ -180,7 +178,7 @@ public class LibraryStructureController : BaseJellyfinApiController
// No need to start if scanning the library because it will handle it
if (refreshLibrary)
{
- await _libraryManager.ValidateMediaLibrary(new SimpleProgress<double>(), CancellationToken.None).ConfigureAwait(false);
+ await _libraryManager.ValidateMediaLibrary(new Progress<double>(), CancellationToken.None).ConfigureAwait(false);
}
else
{
@@ -224,7 +222,7 @@ public class LibraryStructureController : BaseJellyfinApiController
// No need to start if scanning the library because it will handle it
if (refreshLibrary)
{
- await _libraryManager.ValidateMediaLibrary(new SimpleProgress<double>(), CancellationToken.None).ConfigureAwait(false);
+ await _libraryManager.ValidateMediaLibrary(new Progress<double>(), CancellationToken.None).ConfigureAwait(false);
}
else
{
@@ -293,7 +291,7 @@ public class LibraryStructureController : BaseJellyfinApiController
// No need to start if scanning the library because it will handle it
if (refreshLibrary)
{
- await _libraryManager.ValidateMediaLibrary(new SimpleProgress<double>(), CancellationToken.None).ConfigureAwait(false);
+ await _libraryManager.ValidateMediaLibrary(new Progress<double>(), CancellationToken.None).ConfigureAwait(false);
}
else
{
diff --git a/Jellyfin.Api/Controllers/LiveTvController.cs b/Jellyfin.Api/Controllers/LiveTvController.cs
index 1b2f5750f..7f4cad951 100644
--- a/Jellyfin.Api/Controllers/LiveTvController.cs
+++ b/Jellyfin.Api/Controllers/LiveTvController.cs
@@ -43,7 +43,9 @@ namespace Jellyfin.Api.Controllers;
public class LiveTvController : BaseJellyfinApiController
{
private readonly ILiveTvManager _liveTvManager;
+ private readonly IGuideManager _guideManager;
private readonly ITunerHostManager _tunerHostManager;
+ private readonly IListingsManager _listingsManager;
private readonly IUserManager _userManager;
private readonly IHttpClientFactory _httpClientFactory;
private readonly ILibraryManager _libraryManager;
@@ -56,7 +58,9 @@ public class LiveTvController : BaseJellyfinApiController
/// Initializes a new instance of the <see cref="LiveTvController"/> class.
/// </summary>
/// <param name="liveTvManager">Instance of the <see cref="ILiveTvManager"/> interface.</param>
+ /// <param name="guideManager">Instance of the <see cref="IGuideManager"/> interface.</param>
/// <param name="tunerHostManager">Instance of the <see cref="ITunerHostManager"/> interface.</param>
+ /// <param name="listingsManager">Instance of the <see cref="IListingsManager"/> interface.</param>
/// <param name="userManager">Instance of the <see cref="IUserManager"/> interface.</param>
/// <param name="httpClientFactory">Instance of the <see cref="IHttpClientFactory"/> interface.</param>
/// <param name="libraryManager">Instance of the <see cref="ILibraryManager"/> interface.</param>
@@ -66,7 +70,9 @@ public class LiveTvController : BaseJellyfinApiController
/// <param name="transcodeManager">Instance of the <see cref="ITranscodeManager"/> interface.</param>
public LiveTvController(
ILiveTvManager liveTvManager,
+ IGuideManager guideManager,
ITunerHostManager tunerHostManager,
+ IListingsManager listingsManager,
IUserManager userManager,
IHttpClientFactory httpClientFactory,
ILibraryManager libraryManager,
@@ -76,7 +82,9 @@ public class LiveTvController : BaseJellyfinApiController
ITranscodeManager transcodeManager)
{
_liveTvManager = liveTvManager;
+ _guideManager = guideManager;
_tunerHostManager = tunerHostManager;
+ _listingsManager = listingsManager;
_userManager = userManager;
_httpClientFactory = httpClientFactory;
_libraryManager = libraryManager;
@@ -941,9 +949,7 @@ public class LiveTvController : BaseJellyfinApiController
[Authorize(Policy = Policies.LiveTvAccess)]
[ProducesResponseType(StatusCodes.Status200OK)]
public ActionResult<GuideInfo> GetGuideInfo()
- {
- return _liveTvManager.GetGuideInfo();
- }
+ => _guideManager.GetGuideInfo();
/// <summary>
/// Adds a tuner host.
@@ -1013,7 +1019,7 @@ public class LiveTvController : BaseJellyfinApiController
listingsProviderInfo.Password = Convert.ToHexString(SHA1.HashData(Encoding.UTF8.GetBytes(pw))).ToLowerInvariant();
}
- return await _liveTvManager.SaveListingProvider(listingsProviderInfo, validateLogin, validateListings).ConfigureAwait(false);
+ return await _listingsManager.SaveListingProvider(listingsProviderInfo, validateLogin, validateListings).ConfigureAwait(false);
}
/// <summary>
@@ -1027,7 +1033,7 @@ public class LiveTvController : BaseJellyfinApiController
[ProducesResponseType(StatusCodes.Status204NoContent)]
public ActionResult DeleteListingProvider([FromQuery] string? id)
{
- _liveTvManager.DeleteListingsProvider(id);
+ _listingsManager.DeleteListingsProvider(id);
return NoContent();
}
@@ -1048,9 +1054,7 @@ public class LiveTvController : BaseJellyfinApiController
[FromQuery] string? type,
[FromQuery] string? location,
[FromQuery] string? country)
- {
- return await _liveTvManager.GetLineups(type, id, country, location).ConfigureAwait(false);
- }
+ => await _listingsManager.GetLineups(type, id, country, location).ConfigureAwait(false);
/// <summary>
/// Gets available countries.
@@ -1081,48 +1085,20 @@ public class LiveTvController : BaseJellyfinApiController
[HttpGet("ChannelMappingOptions")]
[Authorize(Policy = Policies.LiveTvAccess)]
[ProducesResponseType(StatusCodes.Status200OK)]
- public async Task<ActionResult<ChannelMappingOptionsDto>> GetChannelMappingOptions([FromQuery] string? providerId)
- {
- var config = _configurationManager.GetConfiguration<LiveTvOptions>("livetv");
-
- var listingsProviderInfo = config.ListingProviders.First(i => string.Equals(providerId, i.Id, StringComparison.OrdinalIgnoreCase));
-
- var listingsProviderName = _liveTvManager.ListingProviders.First(i => string.Equals(i.Type, listingsProviderInfo.Type, StringComparison.OrdinalIgnoreCase)).Name;
-
- var tunerChannels = await _liveTvManager.GetChannelsForListingsProvider(providerId, CancellationToken.None)
- .ConfigureAwait(false);
-
- var providerChannels = await _liveTvManager.GetChannelsFromListingsProviderData(providerId, CancellationToken.None)
- .ConfigureAwait(false);
-
- var mappings = listingsProviderInfo.ChannelMappings;
-
- return new ChannelMappingOptionsDto
- {
- TunerChannels = tunerChannels.Select(i => _liveTvManager.GetTunerChannelMapping(i, mappings, providerChannels)).ToList(),
- ProviderChannels = providerChannels.Select(i => new NameIdPair
- {
- Name = i.Name,
- Id = i.Id
- }).ToList(),
- Mappings = mappings,
- ProviderName = listingsProviderName
- };
- }
+ public Task<ChannelMappingOptionsDto> GetChannelMappingOptions([FromQuery] string? providerId)
+ => _listingsManager.GetChannelMappingOptions(providerId);
/// <summary>
/// Set channel mappings.
/// </summary>
- /// <param name="setChannelMappingDto">The set channel mapping dto.</param>
+ /// <param name="dto">The set channel mapping dto.</param>
/// <response code="200">Created channel mapping returned.</response>
/// <returns>An <see cref="OkResult"/> containing the created channel mapping.</returns>
[HttpPost("ChannelMappings")]
[Authorize(Policy = Policies.LiveTvManagement)]
[ProducesResponseType(StatusCodes.Status200OK)]
- public async Task<ActionResult<TunerChannelMapping>> SetChannelMapping([FromBody, Required] SetChannelMappingDto setChannelMappingDto)
- {
- return await _liveTvManager.SetChannelMapping(setChannelMappingDto.ProviderId, setChannelMappingDto.TunerChannelId, setChannelMappingDto.ProviderChannelId).ConfigureAwait(false);
- }
+ public Task<TunerChannelMapping> SetChannelMapping([FromBody, Required] SetChannelMappingDto dto)
+ => _listingsManager.SetChannelMapping(dto.ProviderId, dto.TunerChannelId, dto.ProviderChannelId);
/// <summary>
/// Get tuner host types.
diff --git a/Jellyfin.Api/Controllers/SystemController.cs b/Jellyfin.Api/Controllers/SystemController.cs
index 3d4df0386..6c5ce4715 100644
--- a/Jellyfin.Api/Controllers/SystemController.cs
+++ b/Jellyfin.Api/Controllers/SystemController.cs
@@ -188,16 +188,24 @@ public class SystemController : BaseJellyfinApiController
/// <param name="name">The name of the log file to get.</param>
/// <response code="200">Log file retrieved.</response>
/// <response code="403">User does not have permission to get log files.</response>
+ /// <response code="404">Could not find a log file with the name.</response>
/// <returns>The log file.</returns>
[HttpGet("Logs/Log")]
[Authorize(Policy = Policies.RequiresElevation)]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status403Forbidden)]
+ [ProducesResponseType(StatusCodes.Status404NotFound)]
[ProducesFile(MediaTypeNames.Text.Plain)]
public ActionResult GetLogFile([FromQuery, Required] string name)
{
- var file = _fileSystem.GetFiles(_appPaths.LogDirectoryPath)
- .First(i => string.Equals(i.Name, name, StringComparison.OrdinalIgnoreCase));
+ var file = _fileSystem
+ .GetFiles(_appPaths.LogDirectoryPath)
+ .FirstOrDefault(i => string.Equals(i.Name, name, StringComparison.OrdinalIgnoreCase));
+
+ if (file is null)
+ {
+ return NotFound("Log file not found.");
+ }
// For older files, assume fully static
var fileShare = file.LastWriteTimeUtc < DateTime.UtcNow.AddHours(-1) ? FileShare.Read : FileShare.ReadWrite;
diff --git a/Jellyfin.Api/Controllers/VideosController.cs b/Jellyfin.Api/Controllers/VideosController.cs
index e6c319869..b3029d6fa 100644
--- a/Jellyfin.Api/Controllers/VideosController.cs
+++ b/Jellyfin.Api/Controllers/VideosController.cs
@@ -458,10 +458,8 @@ public class VideosController : BaseJellyfinApiController
return BadRequest($"Input protocol {state.InputProtocol} cannot be streamed statically");
}
- var outputPath = state.OutputFilePath;
-
// Static stream
- if (@static.HasValue && @static.Value)
+ if (@static.HasValue && @static.Value && !(state.MediaSource.VideoType == VideoType.BluRay || state.MediaSource.VideoType == VideoType.Dvd))
{
var contentType = state.GetMimeType("." + state.OutputContainer, false) ?? state.GetMimeType(state.MediaPath);
@@ -478,7 +476,7 @@ public class VideosController : BaseJellyfinApiController
// Need to start ffmpeg (because media can't be returned directly)
var encodingOptions = _serverConfigurationManager.GetEncodingOptions();
- var ffmpegCommandLineArguments = _encodingHelper.GetProgressiveVideoFullCommandLine(state, encodingOptions, outputPath, "superfast");
+ var ffmpegCommandLineArguments = _encodingHelper.GetProgressiveVideoFullCommandLine(state, encodingOptions, "superfast");
return await FileStreamResponseHelpers.GetTranscodedFile(
state,
isHeadRequest,
diff --git a/Jellyfin.Api/Helpers/DynamicHlsHelper.cs b/Jellyfin.Api/Helpers/DynamicHlsHelper.cs
index fa81fc284..f8d89119a 100644
--- a/Jellyfin.Api/Helpers/DynamicHlsHelper.cs
+++ b/Jellyfin.Api/Helpers/DynamicHlsHelper.cs
@@ -211,19 +211,8 @@ public class DynamicHlsHelper
var sdrVideoUrl = ReplaceProfile(playlistUrl, "hevc", string.Join(',', requestedVideoProfiles), "main");
sdrVideoUrl += "&AllowVideoStreamCopy=false";
- var sdrOutputVideoBitrate = _encodingHelper.GetVideoBitrateParamValue(state.VideoRequest, state.VideoStream, state.OutputVideoCodec);
- var sdrOutputAudioBitrate = 0;
- if (EncodingHelper.LosslessAudioCodecs.Contains(state.VideoRequest.AudioCodec, StringComparison.OrdinalIgnoreCase))
- {
- sdrOutputAudioBitrate = state.AudioStream.BitRate ?? 0;
- }
- else
- {
- sdrOutputAudioBitrate = _encodingHelper.GetAudioBitrateParam(state.VideoRequest, state.AudioStream, state.OutputAudioChannels) ?? 0;
- }
-
- var sdrTotalBitrate = sdrOutputAudioBitrate + sdrOutputVideoBitrate;
- AppendPlaylist(builder, state, sdrVideoUrl, sdrTotalBitrate, subtitleGroup);
+ // HACK: Use the same bitrate so that the client can choose by other attributes, such as color range.
+ AppendPlaylist(builder, state, sdrVideoUrl, totalBitrate, subtitleGroup);
// Restore the video codec
state.OutputVideoCodec = "copy";
@@ -325,6 +314,7 @@ public class DynamicHlsHelper
if (state.VideoStream is not null && state.VideoStream.VideoRange != VideoRange.Unknown)
{
var videoRange = state.VideoStream.VideoRange;
+ var videoRangeType = state.VideoStream.VideoRangeType;
if (EncodingHelper.IsCopyCodec(state.OutputVideoCodec))
{
if (videoRange == VideoRange.SDR)
@@ -334,7 +324,14 @@ public class DynamicHlsHelper
if (videoRange == VideoRange.HDR)
{
- builder.Append(",VIDEO-RANGE=PQ");
+ if (videoRangeType == VideoRangeType.HLG)
+ {
+ builder.Append(",VIDEO-RANGE=HLG");
+ }
+ else
+ {
+ builder.Append(",VIDEO-RANGE=PQ");
+ }
}
}
else
diff --git a/Jellyfin.Api/Helpers/FileStreamResponseHelpers.cs b/Jellyfin.Api/Helpers/FileStreamResponseHelpers.cs
index 5385979d4..cb178a61d 100644
--- a/Jellyfin.Api/Helpers/FileStreamResponseHelpers.cs
+++ b/Jellyfin.Api/Helpers/FileStreamResponseHelpers.cs
@@ -93,9 +93,7 @@ public static class FileStreamResponseHelpers
return new OkResult();
}
- var transcodingLock = transcodeManager.GetTranscodingLock(outputPath);
- await transcodingLock.WaitAsync(cancellationTokenSource.Token).ConfigureAwait(false);
- try
+ using (await transcodeManager.LockAsync(outputPath, cancellationTokenSource.Token).ConfigureAwait(false))
{
TranscodingJob? job;
if (!File.Exists(outputPath))
@@ -117,9 +115,5 @@ public static class FileStreamResponseHelpers
var stream = new ProgressiveFileStream(outputPath, job, transcodeManager);
return new FileStreamResult(stream, contentType);
}
- finally
- {
- transcodingLock.Release();
- }
}
}
diff --git a/Jellyfin.Api/Helpers/StreamingHelpers.cs b/Jellyfin.Api/Helpers/StreamingHelpers.cs
index 7a3842a9f..bfe71fd87 100644
--- a/Jellyfin.Api/Helpers/StreamingHelpers.cs
+++ b/Jellyfin.Api/Helpers/StreamingHelpers.cs
@@ -225,7 +225,7 @@ public static class StreamingHelpers
var ext = string.IsNullOrWhiteSpace(state.OutputContainer)
? GetOutputFileExtension(state, mediaSource)
- : ("." + state.OutputContainer);
+ : ("." + GetContainerFileExtension(state.OutputContainer));
state.OutputFilePath = GetOutputFilePath(state, ext, serverConfigurationManager, streamingRequest.DeviceId, streamingRequest.PlaySessionId);
@@ -559,4 +559,23 @@ public static class StreamingHelpers
}
}
}
+
+ /// <summary>
+ /// Parses the container into its file extension.
+ /// </summary>
+ /// <param name="container">The container.</param>
+ private static string? GetContainerFileExtension(string? container)
+ {
+ if (string.Equals(container, "mpegts", StringComparison.OrdinalIgnoreCase))
+ {
+ return "ts";
+ }
+
+ if (string.Equals(container, "matroska", StringComparison.OrdinalIgnoreCase))
+ {
+ return "mkv";
+ }
+
+ return container;
+ }
}
diff --git a/Jellyfin.Api/Models/SessionDtos/ClientCapabilitiesDto.cs b/Jellyfin.Api/Models/SessionDtos/ClientCapabilitiesDto.cs
index acd3f29e3..12ce19368 100644
--- a/Jellyfin.Api/Models/SessionDtos/ClientCapabilitiesDto.cs
+++ b/Jellyfin.Api/Models/SessionDtos/ClientCapabilitiesDto.cs
@@ -1,5 +1,6 @@
using System;
using System.Collections.Generic;
+using System.ComponentModel;
using System.Text.Json.Serialization;
using Jellyfin.Data.Enums;
using Jellyfin.Extensions.Json.Converters;
@@ -50,6 +51,18 @@ public class ClientCapabilitiesDto
/// </summary>
public string? IconUrl { get; set; }
+#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member
+ // TODO: Remove after 10.9
+ [Obsolete("Unused")]
+ [DefaultValue(false)]
+ public bool? SupportsContentUploading { get; set; }
+
+ // TODO: Remove after 10.9
+ [Obsolete("Unused")]
+ [DefaultValue(false)]
+ public bool? SupportsSync { get; set; }
+#pragma warning restore CS1591 // Missing XML comment for publicly visible type or member
+
/// <summary>
/// Convert the dto to the full <see cref="ClientCapabilities"/> model.
/// </summary>
diff --git a/Jellyfin.Server.Implementations/Jellyfin.Server.Implementations.csproj b/Jellyfin.Server.Implementations/Jellyfin.Server.Implementations.csproj
index 0ed1578c7..7c4155bfc 100644
--- a/Jellyfin.Server.Implementations/Jellyfin.Server.Implementations.csproj
+++ b/Jellyfin.Server.Implementations/Jellyfin.Server.Implementations.csproj
@@ -26,6 +26,7 @@
</ItemGroup>
<ItemGroup>
+ <PackageReference Include="AsyncKeyedLock" />
<PackageReference Include="EFCoreSecondLevelCacheInterceptor" />
<PackageReference Include="System.Linq.Async" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" />
diff --git a/Jellyfin.Server.Implementations/Trickplay/TrickplayManager.cs b/Jellyfin.Server.Implementations/Trickplay/TrickplayManager.cs
index b960feb7f..095bc9ed3 100644
--- a/Jellyfin.Server.Implementations/Trickplay/TrickplayManager.cs
+++ b/Jellyfin.Server.Implementations/Trickplay/TrickplayManager.cs
@@ -6,6 +6,7 @@ using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
+using AsyncKeyedLock;
using Jellyfin.Data.Entities;
using MediaBrowser.Common.Configuration;
using MediaBrowser.Controller.Configuration;
@@ -37,7 +38,7 @@ public class TrickplayManager : ITrickplayManager
private readonly IDbContextFactory<JellyfinDbContext> _dbProvider;
private readonly IApplicationPaths _appPaths;
- private static readonly SemaphoreSlim _resourcePool = new(1, 1);
+ private static readonly AsyncNonKeyedLocker _resourcePool = new(1);
private static readonly string[] _trickplayImgExtensions = { ".jpg" };
/// <summary>
@@ -107,93 +108,92 @@ public class TrickplayManager : ITrickplayManager
var imgTempDir = string.Empty;
var outputDir = GetTrickplayDirectory(video, width);
- await _resourcePool.WaitAsync(cancellationToken).ConfigureAwait(false);
-
- try
+ using (await _resourcePool.LockAsync(cancellationToken).ConfigureAwait(false))
{
- if (!replace && Directory.Exists(outputDir) && (await GetTrickplayResolutions(video.Id).ConfigureAwait(false)).ContainsKey(width))
- {
- _logger.LogDebug("Found existing trickplay files for {ItemId}. Exiting.", video.Id);
- return;
- }
-
- // Extract images
- // Note: Media sources under parent items exist as their own video/item as well. Only use this video stream for trickplay.
- var mediaSource = video.GetMediaSources(false).Find(source => Guid.Parse(source.Id).Equals(video.Id));
-
- if (mediaSource is null)
+ try
{
- _logger.LogDebug("Found no matching media source for item {ItemId}", video.Id);
- return;
- }
+ if (!replace && Directory.Exists(outputDir) && (await GetTrickplayResolutions(video.Id).ConfigureAwait(false)).ContainsKey(width))
+ {
+ _logger.LogDebug("Found existing trickplay files for {ItemId}. Exiting.", video.Id);
+ return;
+ }
- var mediaPath = mediaSource.Path;
- var mediaStream = mediaSource.VideoStream;
- var container = mediaSource.Container;
+ // Extract images
+ // Note: Media sources under parent items exist as their own video/item as well. Only use this video stream for trickplay.
+ var mediaSource = video.GetMediaSources(false).Find(source => Guid.Parse(source.Id).Equals(video.Id));
- _logger.LogInformation("Creating trickplay files at {Width} width, for {Path} [ID: {ItemId}]", width, mediaPath, video.Id);
- imgTempDir = await _mediaEncoder.ExtractVideoImagesOnIntervalAccelerated(
- mediaPath,
- container,
- mediaSource,
- mediaStream,
- width,
- TimeSpan.FromMilliseconds(options.Interval),
- options.EnableHwAcceleration,
- options.ProcessThreads,
- options.Qscale,
- options.ProcessPriority,
- _encodingHelper,
- cancellationToken).ConfigureAwait(false);
+ if (mediaSource is null)
+ {
+ _logger.LogDebug("Found no matching media source for item {ItemId}", video.Id);
+ return;
+ }
- if (string.IsNullOrEmpty(imgTempDir) || !Directory.Exists(imgTempDir))
- {
- throw new InvalidOperationException("Null or invalid directory from media encoder.");
- }
+ var mediaPath = mediaSource.Path;
+ var mediaStream = mediaSource.VideoStream;
+ var container = mediaSource.Container;
+
+ _logger.LogInformation("Creating trickplay files at {Width} width, for {Path} [ID: {ItemId}]", width, mediaPath, video.Id);
+ imgTempDir = await _mediaEncoder.ExtractVideoImagesOnIntervalAccelerated(
+ mediaPath,
+ container,
+ mediaSource,
+ mediaStream,
+ width,
+ TimeSpan.FromMilliseconds(options.Interval),
+ options.EnableHwAcceleration,
+ options.ProcessThreads,
+ options.Qscale,
+ options.ProcessPriority,
+ _encodingHelper,
+ cancellationToken).ConfigureAwait(false);
+
+ if (string.IsNullOrEmpty(imgTempDir) || !Directory.Exists(imgTempDir))
+ {
+ throw new InvalidOperationException("Null or invalid directory from media encoder.");
+ }
- var images = _fileSystem.GetFiles(imgTempDir, _trickplayImgExtensions, false, false)
- .Select(i => i.FullName)
- .OrderBy(i => i)
- .ToList();
+ var images = _fileSystem.GetFiles(imgTempDir, _trickplayImgExtensions, false, false)
+ .Select(i => i.FullName)
+ .OrderBy(i => i)
+ .ToList();
- // Create tiles
- var trickplayInfo = CreateTiles(images, width, options, outputDir);
+ // Create tiles
+ var trickplayInfo = CreateTiles(images, width, options, outputDir);
- // Save tiles info
- try
- {
- if (trickplayInfo is not null)
+ // Save tiles info
+ try
{
- trickplayInfo.ItemId = video.Id;
- await SaveTrickplayInfo(trickplayInfo).ConfigureAwait(false);
+ if (trickplayInfo is not null)
+ {
+ trickplayInfo.ItemId = video.Id;
+ await SaveTrickplayInfo(trickplayInfo).ConfigureAwait(false);
- _logger.LogInformation("Finished creation of trickplay files for {0}", mediaPath);
+ _logger.LogInformation("Finished creation of trickplay files for {0}", mediaPath);
+ }
+ else
+ {
+ throw new InvalidOperationException("Null trickplay tiles info from CreateTiles.");
+ }
}
- else
+ catch (Exception ex)
{
- throw new InvalidOperationException("Null trickplay tiles info from CreateTiles.");
+ _logger.LogError(ex, "Error while saving trickplay tiles info.");
+
+ // Make sure no files stay in metadata folders on failure
+ // if tiles info wasn't saved.
+ Directory.Delete(outputDir, true);
}
}
catch (Exception ex)
{
- _logger.LogError(ex, "Error while saving trickplay tiles info.");
-
- // Make sure no files stay in metadata folders on failure
- // if tiles info wasn't saved.
- Directory.Delete(outputDir, true);
+ _logger.LogError(ex, "Error creating trickplay images.");
}
- }
- catch (Exception ex)
- {
- _logger.LogError(ex, "Error creating trickplay images.");
- }
- finally
- {
- _resourcePool.Release();
-
- if (!string.IsNullOrEmpty(imgTempDir))
+ finally
{
- Directory.Delete(imgTempDir, true);
+ if (!string.IsNullOrEmpty(imgTempDir))
+ {
+ Directory.Delete(imgTempDir, true);
+ }
}
}
}
@@ -382,7 +382,7 @@ public class TrickplayManager : ITrickplayManager
if (trickplayInfo.ThumbnailCount > 0)
{
- const string urlFormat = "Trickplay/{0}/{1}.jpg?MediaSourceId={2}&api_key={3}";
+ const string urlFormat = "{0}.jpg?MediaSourceId={1}&api_key={2}";
const string decimalFormat = "{0:0.###}";
var resolution = $"{trickplayInfo.Width}x{trickplayInfo.Height}";
@@ -431,7 +431,6 @@ public class TrickplayManager : ITrickplayManager
.AppendFormat(
CultureInfo.InvariantCulture,
urlFormat,
- width.ToString(CultureInfo.InvariantCulture),
i.ToString(CultureInfo.InvariantCulture),
itemId.ToString("N"),
apiKey)
diff --git a/Jellyfin.Server.Implementations/Users/DeviceAccessEntryPoint.cs b/Jellyfin.Server.Implementations/Users/DeviceAccessEntryPoint.cs
deleted file mode 100644
index a471ea1d5..000000000
--- a/Jellyfin.Server.Implementations/Users/DeviceAccessEntryPoint.cs
+++ /dev/null
@@ -1,64 +0,0 @@
-#pragma warning disable CS1591
-
-using System.Threading.Tasks;
-using Jellyfin.Data.Entities;
-using Jellyfin.Data.Enums;
-using Jellyfin.Data.Events;
-using Jellyfin.Data.Queries;
-using MediaBrowser.Controller.Devices;
-using MediaBrowser.Controller.Library;
-using MediaBrowser.Controller.Plugins;
-using MediaBrowser.Controller.Session;
-
-namespace Jellyfin.Server.Implementations.Users
-{
- public sealed class DeviceAccessEntryPoint : IServerEntryPoint
- {
- private readonly IUserManager _userManager;
- private readonly IDeviceManager _deviceManager;
- private readonly ISessionManager _sessionManager;
-
- public DeviceAccessEntryPoint(IUserManager userManager, IDeviceManager deviceManager, ISessionManager sessionManager)
- {
- _userManager = userManager;
- _deviceManager = deviceManager;
- _sessionManager = sessionManager;
- }
-
- public Task RunAsync()
- {
- _userManager.OnUserUpdated += OnUserUpdated;
-
- return Task.CompletedTask;
- }
-
- public void Dispose()
- {
- }
-
- private async void OnUserUpdated(object? sender, GenericEventArgs<User> e)
- {
- var user = e.Argument;
- if (!user.HasPermission(PermissionKind.EnableAllDevices))
- {
- await UpdateDeviceAccess(user).ConfigureAwait(false);
- }
- }
-
- private async Task UpdateDeviceAccess(User user)
- {
- var existing = (await _deviceManager.GetDevices(new DeviceQuery
- {
- UserId = user.Id
- }).ConfigureAwait(false)).Items;
-
- foreach (var device in existing)
- {
- if (!string.IsNullOrEmpty(device.DeviceId) && !_deviceManager.CanAccessDevice(user, device.DeviceId))
- {
- await _sessionManager.Logout(device).ConfigureAwait(false);
- }
- }
- }
- }
-}
diff --git a/Jellyfin.Server.Implementations/Users/DeviceAccessHost.cs b/Jellyfin.Server.Implementations/Users/DeviceAccessHost.cs
new file mode 100644
index 000000000..e40b541a3
--- /dev/null
+++ b/Jellyfin.Server.Implementations/Users/DeviceAccessHost.cs
@@ -0,0 +1,76 @@
+using System.Threading;
+using System.Threading.Tasks;
+using Jellyfin.Data.Entities;
+using Jellyfin.Data.Enums;
+using Jellyfin.Data.Events;
+using Jellyfin.Data.Queries;
+using MediaBrowser.Controller.Devices;
+using MediaBrowser.Controller.Library;
+using MediaBrowser.Controller.Session;
+using Microsoft.Extensions.Hosting;
+
+namespace Jellyfin.Server.Implementations.Users;
+
+/// <summary>
+/// <see cref="IHostedService"/> responsible for managing user device permissions.
+/// </summary>
+public sealed class DeviceAccessHost : IHostedService
+{
+ private readonly IUserManager _userManager;
+ private readonly IDeviceManager _deviceManager;
+ private readonly ISessionManager _sessionManager;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="DeviceAccessHost"/> class.
+ /// </summary>
+ /// <param name="userManager">The <see cref="IUserManager"/>.</param>
+ /// <param name="deviceManager">The <see cref="IDeviceManager"/>.</param>
+ /// <param name="sessionManager">The <see cref="ISessionManager"/>.</param>
+ public DeviceAccessHost(IUserManager userManager, IDeviceManager deviceManager, ISessionManager sessionManager)
+ {
+ _userManager = userManager;
+ _deviceManager = deviceManager;
+ _sessionManager = sessionManager;
+ }
+
+ /// <inheritdoc />
+ public Task StartAsync(CancellationToken cancellationToken)
+ {
+ _userManager.OnUserUpdated += OnUserUpdated;
+
+ return Task.CompletedTask;
+ }
+
+ /// <inheritdoc />
+ public Task StopAsync(CancellationToken cancellationToken)
+ {
+ _userManager.OnUserUpdated -= OnUserUpdated;
+
+ return Task.CompletedTask;
+ }
+
+ private async void OnUserUpdated(object? sender, GenericEventArgs<User> e)
+ {
+ var user = e.Argument;
+ if (!user.HasPermission(PermissionKind.EnableAllDevices))
+ {
+ await UpdateDeviceAccess(user).ConfigureAwait(false);
+ }
+ }
+
+ private async Task UpdateDeviceAccess(User user)
+ {
+ var existing = (await _deviceManager.GetDevices(new DeviceQuery
+ {
+ UserId = user.Id
+ }).ConfigureAwait(false)).Items;
+
+ foreach (var device in existing)
+ {
+ if (!string.IsNullOrEmpty(device.DeviceId) && !_deviceManager.CanAccessDevice(user, device.DeviceId))
+ {
+ await _sessionManager.Logout(device).ConfigureAwait(false);
+ }
+ }
+ }
+}
diff --git a/Jellyfin.Server/Jellyfin.Server.csproj b/Jellyfin.Server/Jellyfin.Server.csproj
index 21c6e6f01..e18212908 100644
--- a/Jellyfin.Server/Jellyfin.Server.csproj
+++ b/Jellyfin.Server/Jellyfin.Server.csproj
@@ -12,6 +12,7 @@
<ServerGarbageCollection>false</ServerGarbageCollection>
<GenerateAssemblyInfo>false</GenerateAssemblyInfo>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
+ <ApplicationIcon>Jellyfin.Server.ico</ApplicationIcon>
</PropertyGroup>
<ItemGroup>
@@ -19,6 +20,10 @@
</ItemGroup>
<ItemGroup>
+ <Content Include="Jellyfin.Server.ico" />
+ </ItemGroup>
+
+ <ItemGroup>
<EmbeddedResource Include="Resources/Configuration/*" />
</ItemGroup>
diff --git a/Jellyfin.Server/Jellyfin.Server.ico b/Jellyfin.Server/Jellyfin.Server.ico
new file mode 100644
index 000000000..0872b956a
--- /dev/null
+++ b/Jellyfin.Server/Jellyfin.Server.ico
Binary files differ
diff --git a/Jellyfin.Server/Startup.cs b/Jellyfin.Server/Startup.cs
index 7d5f22545..558ad5b7b 100644
--- a/Jellyfin.Server/Startup.cs
+++ b/Jellyfin.Server/Startup.cs
@@ -4,7 +4,10 @@ using System.Net.Http;
using System.Net.Http.Headers;
using System.Net.Mime;
using System.Text;
+using Emby.Server.Implementations.EntryPoints;
using Jellyfin.Api.Middleware;
+using Jellyfin.LiveTv;
+using Jellyfin.LiveTv.EmbyTV;
using Jellyfin.LiveTv.Extensions;
using Jellyfin.MediaEncoding.Hls.Extensions;
using Jellyfin.Networking;
@@ -17,6 +20,7 @@ using Jellyfin.Server.Infrastructure;
using MediaBrowser.Common.Net;
using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Extensions;
+using MediaBrowser.XbmcMetadata;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
@@ -124,7 +128,13 @@ namespace Jellyfin.Server
services.AddHlsPlaylistGenerator();
services.AddLiveTvServices();
+ services.AddHostedService<LiveTvHost>();
services.AddHostedService<AutoDiscoveryHost>();
+ services.AddHostedService<PortForwardingHost>();
+ services.AddHostedService<NfoUserDataSaver>();
+ services.AddHostedService<LibraryChangedNotifier>();
+ services.AddHostedService<UserDataChangeNotifier>();
+ services.AddHostedService<RecordingNotifier>();
}
/// <summary>
diff --git a/MediaBrowser.Common/Progress/ActionableProgress.cs b/MediaBrowser.Common/Progress/ActionableProgress.cs
deleted file mode 100644
index 0ba46ea3b..000000000
--- a/MediaBrowser.Common/Progress/ActionableProgress.cs
+++ /dev/null
@@ -1,37 +0,0 @@
-#pragma warning disable CS1591
-#pragma warning disable CA1003
-
-using System;
-
-namespace MediaBrowser.Common.Progress
-{
- /// <summary>
- /// Class ActionableProgress.
- /// </summary>
- /// <typeparam name="T">The type for the action parameter.</typeparam>
- public class ActionableProgress<T> : IProgress<T>
- {
- /// <summary>
- /// The _actions.
- /// </summary>
- private Action<T>? _action;
-
- public event EventHandler<T>? ProgressChanged;
-
- /// <summary>
- /// Registers the action.
- /// </summary>
- /// <param name="action">The action.</param>
- public void RegisterAction(Action<T> action)
- {
- _action = action;
- }
-
- public void Report(T value)
- {
- ProgressChanged?.Invoke(this, value);
-
- _action?.Invoke(value);
- }
- }
-}
diff --git a/MediaBrowser.Common/Progress/SimpleProgress.cs b/MediaBrowser.Common/Progress/SimpleProgress.cs
deleted file mode 100644
index 7071f2bc3..000000000
--- a/MediaBrowser.Common/Progress/SimpleProgress.cs
+++ /dev/null
@@ -1,17 +0,0 @@
-#pragma warning disable CS1591
-#pragma warning disable CA1003
-
-using System;
-
-namespace MediaBrowser.Common.Progress
-{
- public class SimpleProgress<T> : IProgress<T>
- {
- public event EventHandler<T>? ProgressChanged;
-
- public void Report(T value)
- {
- ProgressChanged?.Invoke(this, value);
- }
- }
-}
diff --git a/MediaBrowser.Controller/Channels/Channel.cs b/MediaBrowser.Controller/Channels/Channel.cs
index 94418683b..f186523b9 100644
--- a/MediaBrowser.Controller/Channels/Channel.cs
+++ b/MediaBrowser.Controller/Channels/Channel.cs
@@ -9,7 +9,6 @@ using System.Text.Json.Serialization;
using System.Threading;
using Jellyfin.Data.Entities;
using Jellyfin.Data.Enums;
-using MediaBrowser.Common.Progress;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Model.Querying;
@@ -53,7 +52,7 @@ namespace MediaBrowser.Controller.Channels
query.ChannelIds = new Guid[] { Id };
// Don't blow up here because it could cause parent screens with other content to fail
- return ChannelManager.GetChannelItemsInternal(query, new SimpleProgress<double>(), CancellationToken.None).GetAwaiter().GetResult();
+ return ChannelManager.GetChannelItemsInternal(query, new Progress<double>(), CancellationToken.None).GetAwaiter().GetResult();
}
catch
{
diff --git a/MediaBrowser.Controller/Drawing/ImageStream.cs b/MediaBrowser.Controller/Drawing/ImageStream.cs
deleted file mode 100644
index f4c305799..000000000
--- a/MediaBrowser.Controller/Drawing/ImageStream.cs
+++ /dev/null
@@ -1,42 +0,0 @@
-#pragma warning disable CA1711, CS1591
-
-using System;
-using System.IO;
-using MediaBrowser.Model.Drawing;
-
-namespace MediaBrowser.Controller.Drawing
-{
- public class ImageStream : IDisposable
- {
- public ImageStream(Stream stream)
- {
- Stream = stream;
- }
-
- /// <summary>
- /// Gets the stream.
- /// </summary>
- /// <value>The stream.</value>
- public Stream Stream { get; }
-
- /// <summary>
- /// Gets or sets the format.
- /// </summary>
- /// <value>The format.</value>
- public ImageFormat Format { get; set; }
-
- public void Dispose()
- {
- Dispose(true);
- GC.SuppressFinalize(this);
- }
-
- protected virtual void Dispose(bool disposing)
- {
- if (disposing)
- {
- Stream?.Dispose();
- }
- }
- }
-}
diff --git a/MediaBrowser.Controller/Entities/Folder.cs b/MediaBrowser.Controller/Entities/Folder.cs
index 74eb089de..1f13c833b 100644
--- a/MediaBrowser.Controller/Entities/Folder.cs
+++ b/MediaBrowser.Controller/Entities/Folder.cs
@@ -13,7 +13,6 @@ using System.Threading.Tasks.Dataflow;
using Jellyfin.Data.Entities;
using Jellyfin.Data.Enums;
using Jellyfin.Extensions;
-using MediaBrowser.Common.Progress;
using MediaBrowser.Controller.Channels;
using MediaBrowser.Controller.Collections;
using MediaBrowser.Controller.Configuration;
@@ -429,16 +428,22 @@ namespace MediaBrowser.Controller.Entities
if (recursive)
{
- var innerProgress = new ActionableProgress<double>();
-
var folder = this;
- innerProgress.RegisterAction(innerPercent =>
+ var innerProgress = new Progress<double>(innerPercent =>
{
var percent = ProgressHelpers.GetProgress(ProgressHelpers.UpdatedChildItems, ProgressHelpers.ScannedSubfolders, innerPercent);
progress.Report(percent);
- ProviderManager.OnRefreshProgress(folder, percent);
+ // TODO: this is sometimes being called after the refresh has completed.
+ try
+ {
+ ProviderManager.OnRefreshProgress(folder, percent);
+ }
+ catch (InvalidOperationException e)
+ {
+ Logger.LogError(e, "Error refreshing folder");
+ }
});
if (validChildrenNeedGeneration)
@@ -461,10 +466,8 @@ namespace MediaBrowser.Controller.Entities
var container = this as IMetadataContainer;
- var innerProgress = new ActionableProgress<double>();
-
var folder = this;
- innerProgress.RegisterAction(innerPercent =>
+ var innerProgress = new Progress<double>(innerPercent =>
{
var percent = ProgressHelpers.GetProgress(ProgressHelpers.ScannedSubfolders, ProgressHelpers.RefreshedMetadata, innerPercent);
@@ -472,7 +475,15 @@ namespace MediaBrowser.Controller.Entities
if (recursive)
{
- ProviderManager.OnRefreshProgress(folder, percent);
+ // TODO: this is sometimes being called after the refresh has completed.
+ try
+ {
+ ProviderManager.OnRefreshProgress(folder, percent);
+ }
+ catch (InvalidOperationException e)
+ {
+ Logger.LogError(e, "Error refreshing folder");
+ }
}
});
@@ -572,9 +583,7 @@ namespace MediaBrowser.Controller.Entities
var actionBlock = new ActionBlock<int>(
async i =>
{
- var innerProgress = new ActionableProgress<double>();
-
- innerProgress.RegisterAction(innerPercent =>
+ var innerProgress = new Progress<double>(innerPercent =>
{
// round the percent and only update progress if it changed to prevent excessive UpdateProgress calls
var innerPercentRounded = Math.Round(innerPercent);
@@ -922,7 +931,7 @@ namespace MediaBrowser.Controller.Entities
query.ChannelIds = new[] { ChannelId };
// Don't blow up here because it could cause parent screens with other content to fail
- return ChannelManager.GetChannelItemsInternal(query, new SimpleProgress<double>(), CancellationToken.None).GetAwaiter().GetResult();
+ return ChannelManager.GetChannelItemsInternal(query, new Progress<double>(), CancellationToken.None).GetAwaiter().GetResult();
}
catch
{
diff --git a/MediaBrowser.Controller/Library/ILibraryMonitor.cs b/MediaBrowser.Controller/Library/ILibraryMonitor.cs
index de74aa5a1..6d2f5b873 100644
--- a/MediaBrowser.Controller/Library/ILibraryMonitor.cs
+++ b/MediaBrowser.Controller/Library/ILibraryMonitor.cs
@@ -1,10 +1,9 @@
-#pragma warning disable CS1591
-
-using System;
-
namespace MediaBrowser.Controller.Library
{
- public interface ILibraryMonitor : IDisposable
+ /// <summary>
+ /// Service responsible for monitoring library filesystems for changes.
+ /// </summary>
+ public interface ILibraryMonitor
{
/// <summary>
/// Starts this instance.
diff --git a/MediaBrowser.Controller/LiveTv/IGuideManager.cs b/MediaBrowser.Controller/LiveTv/IGuideManager.cs
new file mode 100644
index 000000000..9883b9283
--- /dev/null
+++ b/MediaBrowser.Controller/LiveTv/IGuideManager.cs
@@ -0,0 +1,26 @@
+using System;
+using System.Threading;
+using System.Threading.Tasks;
+using MediaBrowser.Model.LiveTv;
+
+namespace MediaBrowser.Controller.LiveTv;
+
+/// <summary>
+/// Service responsible for managing the Live TV guide.
+/// </summary>
+public interface IGuideManager
+{
+ /// <summary>
+ /// Gets the guide information.
+ /// </summary>
+ /// <returns>The <see cref="GuideInfo"/>.</returns>
+ GuideInfo GetGuideInfo();
+
+ /// <summary>
+ /// Refresh the guide.
+ /// </summary>
+ /// <param name="progress">The <see cref="IProgress{T}"/> to use.</param>
+ /// <param name="cancellationToken">The <see cref="CancellationToken"/> to use.</param>
+ /// <returns>Task representing the refresh operation.</returns>
+ Task RefreshGuide(IProgress<double> progress, CancellationToken cancellationToken);
+}
diff --git a/MediaBrowser.Controller/LiveTv/IListingsManager.cs b/MediaBrowser.Controller/LiveTv/IListingsManager.cs
new file mode 100644
index 000000000..bbf569575
--- /dev/null
+++ b/MediaBrowser.Controller/LiveTv/IListingsManager.cs
@@ -0,0 +1,79 @@
+using System;
+using System.Collections.Generic;
+using System.Threading;
+using System.Threading.Tasks;
+using MediaBrowser.Model.Dto;
+using MediaBrowser.Model.LiveTv;
+
+namespace MediaBrowser.Controller.LiveTv;
+
+/// <summary>
+/// Service responsible for managing <see cref="IListingsProvider"/>s and mapping
+/// their channels to channels provided by <see cref="ITunerHost"/>s.
+/// </summary>
+public interface IListingsManager
+{
+ /// <summary>
+ /// Saves the listing provider.
+ /// </summary>
+ /// <param name="info">The listing provider information.</param>
+ /// <param name="validateLogin">A value indicating whether to validate login.</param>
+ /// <param name="validateListings">A value indicating whether to validate listings..</param>
+ /// <returns>Task.</returns>
+ Task<ListingsProviderInfo> SaveListingProvider(ListingsProviderInfo info, bool validateLogin, bool validateListings);
+
+ /// <summary>
+ /// Deletes the listing provider.
+ /// </summary>
+ /// <param name="id">The listing provider's id.</param>
+ void DeleteListingsProvider(string? id);
+
+ /// <summary>
+ /// Gets the lineups.
+ /// </summary>
+ /// <param name="providerType">Type of the provider.</param>
+ /// <param name="providerId">The provider identifier.</param>
+ /// <param name="country">The country.</param>
+ /// <param name="location">The location.</param>
+ /// <returns>The available lineups.</returns>
+ Task<List<NameIdPair>> GetLineups(string? providerType, string? providerId, string? country, string? location);
+
+ /// <summary>
+ /// Gets the programs for a provided channel.
+ /// </summary>
+ /// <param name="channel">The channel to retrieve programs for.</param>
+ /// <param name="startDateUtc">The earliest date to retrieve programs for.</param>
+ /// <param name="endDateUtc">The latest date to retrieve programs for.</param>
+ /// <param name="cancellationToken">The <see cref="CancellationToken"/> to use.</param>
+ /// <returns>The available programs.</returns>
+ Task<IEnumerable<ProgramInfo>> GetProgramsAsync(
+ ChannelInfo channel,
+ DateTime startDateUtc,
+ DateTime endDateUtc,
+ CancellationToken cancellationToken);
+
+ /// <summary>
+ /// Adds metadata from the <see cref="IListingsProvider"/>s to the provided channels.
+ /// </summary>
+ /// <param name="channels">The channels.</param>
+ /// <param name="enableCache">A value indicating whether to use the EPG channel cache.</param>
+ /// <param name="cancellationToken">The <see cref="CancellationToken"/> to use.</param>
+ /// <returns>A task representing the metadata population.</returns>
+ Task AddProviderMetadata(IList<ChannelInfo> channels, bool enableCache, CancellationToken cancellationToken);
+
+ /// <summary>
+ /// Gets the channel mapping options for a provider.
+ /// </summary>
+ /// <param name="providerId">The id of the provider to use.</param>
+ /// <returns>The channel mapping options.</returns>
+ Task<ChannelMappingOptionsDto> GetChannelMappingOptions(string? providerId);
+
+ /// <summary>
+ /// Sets the channel mapping.
+ /// </summary>
+ /// <param name="providerId">The id of the provider for the mapping.</param>
+ /// <param name="tunerChannelNumber">The tuner channel number.</param>
+ /// <param name="providerChannelNumber">The provider channel number.</param>
+ /// <returns>The updated channel mapping.</returns>
+ Task<TunerChannelMapping> SetChannelMapping(string providerId, string tunerChannelNumber, string providerChannelNumber);
+}
diff --git a/MediaBrowser.Controller/LiveTv/ILiveTvManager.cs b/MediaBrowser.Controller/LiveTv/ILiveTvManager.cs
index 26f9fe42d..0ac0699a3 100644
--- a/MediaBrowser.Controller/LiveTv/ILiveTvManager.cs
+++ b/MediaBrowser.Controller/LiveTv/ILiveTvManager.cs
@@ -36,8 +36,6 @@ namespace MediaBrowser.Controller.LiveTv
/// <value>The services.</value>
IReadOnlyList<ILiveTvService> Services { get; }
- IReadOnlyList<IListingsProvider> ListingProviders { get; }
-
/// <summary>
/// Gets the new timer defaults asynchronous.
/// </summary>
@@ -68,13 +66,6 @@ namespace MediaBrowser.Controller.LiveTv
Task CancelSeriesTimer(string id);
/// <summary>
- /// Adds the parts.
- /// </summary>
- /// <param name="services">The services.</param>
- /// <param name="listingProviders">The listing providers.</param>
- void AddParts(IEnumerable<ILiveTvService> services, IEnumerable<IListingsProvider> listingProviders);
-
- /// <summary>
/// Gets the timer.
/// </summary>
/// <param name="id">The identifier.</param>
@@ -175,12 +166,6 @@ namespace MediaBrowser.Controller.LiveTv
Task CreateSeriesTimer(SeriesTimerInfoDto timer, CancellationToken cancellationToken);
/// <summary>
- /// Gets the guide information.
- /// </summary>
- /// <returns>GuideInfo.</returns>
- GuideInfo GetGuideInfo();
-
- /// <summary>
/// Gets the recommended programs.
/// </summary>
/// <param name="query">The query.</param>
@@ -253,31 +238,6 @@ namespace MediaBrowser.Controller.LiveTv
Task AddInfoToProgramDto(IReadOnlyCollection<(BaseItem Item, BaseItemDto ItemDto)> programs, IReadOnlyList<ItemFields> fields, User user = null);
/// <summary>
- /// Saves the listing provider.
- /// </summary>
- /// <param name="info">The information.</param>
- /// <param name="validateLogin">if set to <c>true</c> [validate login].</param>
- /// <param name="validateListings">if set to <c>true</c> [validate listings].</param>
- /// <returns>Task.</returns>
- Task<ListingsProviderInfo> SaveListingProvider(ListingsProviderInfo info, bool validateLogin, bool validateListings);
-
- void DeleteListingsProvider(string id);
-
- Task<TunerChannelMapping> SetChannelMapping(string providerId, string tunerChannelNumber, string providerChannelNumber);
-
- TunerChannelMapping GetTunerChannelMapping(ChannelInfo tunerChannel, NameValuePair[] mappings, List<ChannelInfo> providerChannels);
-
- /// <summary>
- /// Gets the lineups.
- /// </summary>
- /// <param name="providerType">Type of the provider.</param>
- /// <param name="providerId">The provider identifier.</param>
- /// <param name="country">The country.</param>
- /// <param name="location">The location.</param>
- /// <returns>Task&lt;List&lt;NameIdPair&gt;&gt;.</returns>
- Task<List<NameIdPair>> GetLineups(string providerType, string providerId, string country, string location);
-
- /// <summary>
/// Adds the channel information.
/// </summary>
/// <param name="items">The items.</param>
@@ -285,10 +245,6 @@ namespace MediaBrowser.Controller.LiveTv
/// <param name="user">The user.</param>
void AddChannelInfo(IReadOnlyCollection<(BaseItemDto ItemDto, LiveTvChannel Channel)> items, DtoOptions options, User user);
- Task<List<ChannelInfo>> GetChannelsForListingsProvider(string id, CancellationToken cancellationToken);
-
- Task<List<ChannelInfo>> GetChannelsFromListingsProviderData(string id, CancellationToken cancellationToken);
-
string GetEmbyTvActiveRecordingPath(string id);
ActiveRecordingInfo GetActiveRecordingInfo(string path);
diff --git a/MediaBrowser.Controller/LiveTv/TunerChannelMapping.cs b/MediaBrowser.Controller/LiveTv/TunerChannelMapping.cs
deleted file mode 100644
index 1c1a4417d..000000000
--- a/MediaBrowser.Controller/LiveTv/TunerChannelMapping.cs
+++ /dev/null
@@ -1,17 +0,0 @@
-#nullable disable
-
-#pragma warning disable CS1591
-
-namespace MediaBrowser.Controller.LiveTv
-{
- public class TunerChannelMapping
- {
- public string Name { get; set; }
-
- public string ProviderChannelName { get; set; }
-
- public string ProviderChannelId { get; set; }
-
- public string Id { get; set; }
- }
-}
diff --git a/MediaBrowser.Controller/MediaEncoding/BaseEncodingJobOptions.cs b/MediaBrowser.Controller/MediaEncoding/BaseEncodingJobOptions.cs
index fb4e7bd1f..29dd190ab 100644
--- a/MediaBrowser.Controller/MediaEncoding/BaseEncodingJobOptions.cs
+++ b/MediaBrowser.Controller/MediaEncoding/BaseEncodingJobOptions.cs
@@ -88,6 +88,12 @@ namespace MediaBrowser.Controller.MediaEncoding
public string Level { get; set; }
/// <summary>
+ /// Gets or sets the codec tag.
+ /// </summary>
+ /// <value>The codec tag.</value>
+ public string CodecTag { get; set; }
+
+ /// <summary>
/// Gets or sets the framerate.
/// </summary>
/// <value>The framerate.</value>
diff --git a/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs b/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs
index 2a2614e4d..b6738e7cc 100644
--- a/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs
+++ b/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs
@@ -30,6 +30,7 @@ namespace MediaBrowser.Controller.MediaEncoding
private const string VaapiAlias = "va";
private const string D3d11vaAlias = "dx11";
private const string VideotoolboxAlias = "vt";
+ private const string RkmppAlias = "rk";
private const string OpenclAlias = "ocl";
private const string CudaAlias = "cu";
private const string DrmAlias = "dr";
@@ -161,6 +162,7 @@ namespace MediaBrowser.Controller.MediaEncoding
{ "vaapi", hwEncoder + "_vaapi" },
{ "videotoolbox", hwEncoder + "_videotoolbox" },
{ "v4l2m2m", hwEncoder + "_v4l2m2m" },
+ { "rkmpp", hwEncoder + "_rkmpp" },
};
if (!string.IsNullOrEmpty(hwType)
@@ -217,6 +219,14 @@ namespace MediaBrowser.Controller.MediaEncoding
&& _mediaEncoder.SupportsFilter("hwupload_vaapi");
}
+ private bool IsRkmppFullSupported()
+ {
+ return _mediaEncoder.SupportsHwaccel("rkmpp")
+ && _mediaEncoder.SupportsFilter("scale_rkrga")
+ && _mediaEncoder.SupportsFilter("vpp_rkrga")
+ && _mediaEncoder.SupportsFilter("overlay_rkrga");
+ }
+
private bool IsOpenclFullSupported()
{
return _mediaEncoder.SupportsHwaccel("opencl")
@@ -696,6 +706,14 @@ namespace MediaBrowser.Controller.MediaEncoding
return codec.ToLowerInvariant();
}
+ private string GetRkmppDeviceArgs(string alias)
+ {
+ alias ??= RkmppAlias;
+
+ // device selection in rk is not supported.
+ return " -init_hw_device rkmpp=" + alias;
+ }
+
private string GetVideoToolboxDeviceArgs(string alias)
{
alias ??= VideotoolboxAlias;
@@ -1056,6 +1074,33 @@ namespace MediaBrowser.Controller.MediaEncoding
// no videotoolbox hw filter.
args.Append(GetVideoToolboxDeviceArgs(VideotoolboxAlias));
}
+ else if (string.Equals(optHwaccelType, "rkmpp", StringComparison.OrdinalIgnoreCase))
+ {
+ if (!isLinux || !_mediaEncoder.SupportsHwaccel("rkmpp"))
+ {
+ return string.Empty;
+ }
+
+ var isRkmppDecoder = vidDecoder.Contains("rkmpp", StringComparison.OrdinalIgnoreCase);
+ var isRkmppEncoder = vidEncoder.Contains("rkmpp", StringComparison.OrdinalIgnoreCase);
+ if (!isRkmppDecoder && !isRkmppEncoder)
+ {
+ return string.Empty;
+ }
+
+ args.Append(GetRkmppDeviceArgs(RkmppAlias));
+
+ var filterDevArgs = string.Empty;
+ var doOclTonemap = isHwTonemapAvailable && IsOpenclFullSupported();
+
+ if (doOclTonemap && !isRkmppDecoder)
+ {
+ args.Append(GetOpenclDeviceArgs(0, null, RkmppAlias, OpenclAlias));
+ filterDevArgs = GetFilterHwDeviceArgs(OpenclAlias);
+ }
+
+ args.Append(filterDevArgs);
+ }
if (!string.IsNullOrEmpty(vidDecoder))
{
@@ -1472,8 +1517,10 @@ namespace MediaBrowser.Controller.MediaEncoding
if (string.Equals(codec, "h264_qsv", StringComparison.OrdinalIgnoreCase)
|| string.Equals(codec, "h264_nvenc", StringComparison.OrdinalIgnoreCase)
|| string.Equals(codec, "h264_amf", StringComparison.OrdinalIgnoreCase)
+ || string.Equals(codec, "h264_rkmpp", StringComparison.OrdinalIgnoreCase)
|| string.Equals(codec, "hevc_qsv", StringComparison.OrdinalIgnoreCase)
|| string.Equals(codec, "hevc_nvenc", StringComparison.OrdinalIgnoreCase)
+ || string.Equals(codec, "hevc_rkmpp", StringComparison.OrdinalIgnoreCase)
|| string.Equals(codec, "av1_qsv", StringComparison.OrdinalIgnoreCase)
|| string.Equals(codec, "av1_nvenc", StringComparison.OrdinalIgnoreCase)
|| string.Equals(codec, "av1_amf", StringComparison.OrdinalIgnoreCase)
@@ -1913,20 +1960,22 @@ namespace MediaBrowser.Controller.MediaEncoding
profile = "constrained_baseline";
}
- // libx264, h264_qsv and h264_nvenc does not support Constrained Baseline profile, force Baseline in this case.
+ // libx264, h264_{qsv,nvenc,rkmpp} does not support Constrained Baseline profile, force Baseline in this case.
if ((string.Equals(videoEncoder, "libx264", StringComparison.OrdinalIgnoreCase)
|| string.Equals(videoEncoder, "h264_qsv", StringComparison.OrdinalIgnoreCase)
- || string.Equals(videoEncoder, "h264_nvenc", StringComparison.OrdinalIgnoreCase))
+ || string.Equals(videoEncoder, "h264_nvenc", StringComparison.OrdinalIgnoreCase)
+ || string.Equals(videoEncoder, "h264_rkmpp", StringComparison.OrdinalIgnoreCase))
&& profile.Contains("baseline", StringComparison.OrdinalIgnoreCase))
{
profile = "baseline";
}
- // libx264, h264_qsv, h264_nvenc and h264_vaapi does not support Constrained High profile, force High in this case.
+ // libx264, h264_{qsv,nvenc,vaapi,rkmpp} does not support Constrained High profile, force High in this case.
if ((string.Equals(videoEncoder, "libx264", StringComparison.OrdinalIgnoreCase)
|| string.Equals(videoEncoder, "h264_qsv", StringComparison.OrdinalIgnoreCase)
|| string.Equals(videoEncoder, "h264_nvenc", StringComparison.OrdinalIgnoreCase)
- || string.Equals(videoEncoder, "h264_vaapi", StringComparison.OrdinalIgnoreCase))
+ || string.Equals(videoEncoder, "h264_vaapi", StringComparison.OrdinalIgnoreCase)
+ || string.Equals(videoEncoder, "h264_rkmpp", StringComparison.OrdinalIgnoreCase))
&& profile.Contains("high", StringComparison.OrdinalIgnoreCase))
{
profile = "high";
@@ -2010,6 +2059,11 @@ namespace MediaBrowser.Controller.MediaEncoding
param += " -level " + level;
}
}
+ else if (string.Equals(videoEncoder, "h264_rkmpp", StringComparison.OrdinalIgnoreCase)
+ || string.Equals(videoEncoder, "hevc_rkmpp", StringComparison.OrdinalIgnoreCase))
+ {
+ param += " -level " + level;
+ }
else if (!string.Equals(videoEncoder, "libx265", StringComparison.OrdinalIgnoreCase))
{
param += " -level " + level;
@@ -2828,6 +2882,48 @@ namespace MediaBrowser.Controller.MediaEncoding
return (outputWidth, outputHeight);
}
+ public static bool IsScaleRatioSupported(
+ int? videoWidth,
+ int? videoHeight,
+ int? requestedWidth,
+ int? requestedHeight,
+ int? requestedMaxWidth,
+ int? requestedMaxHeight,
+ double? maxScaleRatio)
+ {
+ var (outWidth, outHeight) = GetFixedOutputSize(
+ videoWidth,
+ videoHeight,
+ requestedWidth,
+ requestedHeight,
+ requestedMaxWidth,
+ requestedMaxHeight);
+
+ if (!videoWidth.HasValue
+ || !videoHeight.HasValue
+ || !outWidth.HasValue
+ || !outHeight.HasValue
+ || !maxScaleRatio.HasValue
+ || (maxScaleRatio.Value < 1.0f))
+ {
+ return false;
+ }
+
+ var minScaleRatio = 1.0f / maxScaleRatio;
+ var scaleRatioW = (double)outWidth / (double)videoWidth;
+ var scaleRatioH = (double)outHeight / (double)videoHeight;
+
+ if (scaleRatioW < minScaleRatio
+ || scaleRatioW > maxScaleRatio
+ || scaleRatioH < minScaleRatio
+ || scaleRatioH > maxScaleRatio)
+ {
+ return false;
+ }
+
+ return true;
+ }
+
public static string GetHwScaleFilter(
string hwScaleSuffix,
string videoFormat,
@@ -2892,7 +2988,7 @@ namespace MediaBrowser.Controller.MediaEncoding
{
return string.Format(
CultureInfo.InvariantCulture,
- @"scale=-1:{1}:fast_bilinear,crop,pad=max({0}\,iw):max({1}\,ih):(ow-iw)/2:(oh-ih)/2:black@0,crop={0}:{1}",
+ @"scale=-1:{1}:fast_bilinear,scale,crop,pad=max({0}\,iw):max({1}\,ih):(ow-iw)/2:(oh-ih)/2:black@0,crop={0}:{1}",
outWidth.Value,
outHeight.Value);
}
@@ -4911,6 +5007,237 @@ namespace MediaBrowser.Controller.MediaEncoding
}
/// <summary>
+ /// Gets the parameter of Rockchip RKMPP/RKRGA filter chain.
+ /// </summary>
+ /// <param name="state">Encoding state.</param>
+ /// <param name="options">Encoding options.</param>
+ /// <param name="vidEncoder">Video encoder to use.</param>
+ /// <returns>The tuple contains three lists: main, sub and overlay filters.</returns>
+ public (List<string> MainFilters, List<string> SubFilters, List<string> OverlayFilters) GetRkmppVidFilterChain(
+ EncodingJobInfo state,
+ EncodingOptions options,
+ string vidEncoder)
+ {
+ if (!string.Equals(options.HardwareAccelerationType, "rkmpp", StringComparison.OrdinalIgnoreCase))
+ {
+ return (null, null, null);
+ }
+
+ var isLinux = OperatingSystem.IsLinux();
+ var vidDecoder = GetHardwareVideoDecoder(state, options) ?? string.Empty;
+ var isSwDecoder = string.IsNullOrEmpty(vidDecoder);
+ var isSwEncoder = !vidEncoder.Contains("rkmpp", StringComparison.OrdinalIgnoreCase);
+ var isRkmppOclSupported = isLinux && IsRkmppFullSupported() && IsOpenclFullSupported();
+
+ if ((isSwDecoder && isSwEncoder)
+ || !isRkmppOclSupported
+ || !_mediaEncoder.SupportsFilter("alphasrc"))
+ {
+ return GetSwVidFilterChain(state, options, vidEncoder);
+ }
+
+ // prefered rkmpp + rkrga + opencl filters pipeline
+ if (isRkmppOclSupported)
+ {
+ return GetRkmppVidFiltersPrefered(state, options, vidDecoder, vidEncoder);
+ }
+
+ return (null, null, null);
+ }
+
+ public (List<string> MainFilters, List<string> SubFilters, List<string> OverlayFilters) GetRkmppVidFiltersPrefered(
+ EncodingJobInfo state,
+ EncodingOptions options,
+ string vidDecoder,
+ string vidEncoder)
+ {
+ var inW = state.VideoStream?.Width;
+ var inH = state.VideoStream?.Height;
+ var reqW = state.BaseRequest.Width;
+ var reqH = state.BaseRequest.Height;
+ var reqMaxW = state.BaseRequest.MaxWidth;
+ var reqMaxH = state.BaseRequest.MaxHeight;
+ var threeDFormat = state.MediaSource.Video3DFormat;
+
+ var isRkmppDecoder = vidDecoder.Contains("rkmpp", StringComparison.OrdinalIgnoreCase);
+ var isRkmppEncoder = vidEncoder.Contains("rkmpp", StringComparison.OrdinalIgnoreCase);
+ var isSwDecoder = !isRkmppDecoder;
+ var isSwEncoder = !isRkmppEncoder;
+ var isDrmInDrmOut = isRkmppDecoder && isRkmppEncoder;
+
+ var doDeintH264 = state.DeInterlace("h264", true) || state.DeInterlace("avc", true);
+ var doDeintHevc = state.DeInterlace("h265", true) || state.DeInterlace("hevc", true);
+ var doDeintH2645 = doDeintH264 || doDeintHevc;
+ var doOclTonemap = IsHwTonemapAvailable(state, options);
+
+ var hasSubs = state.SubtitleStream != null && state.SubtitleDeliveryMethod == SubtitleDeliveryMethod.Encode;
+ var hasTextSubs = hasSubs && state.SubtitleStream.IsTextSubtitleStream;
+ var hasGraphicalSubs = hasSubs && !state.SubtitleStream.IsTextSubtitleStream;
+ var hasAssSubs = hasSubs
+ && (string.Equals(state.SubtitleStream.Codec, "ass", StringComparison.OrdinalIgnoreCase)
+ || string.Equals(state.SubtitleStream.Codec, "ssa", StringComparison.OrdinalIgnoreCase));
+
+ /* Make main filters for video stream */
+ var mainFilters = new List<string>();
+
+ mainFilters.Add(GetOverwriteColorPropertiesParam(state, doOclTonemap));
+
+ if (isSwDecoder)
+ {
+ // INPUT sw surface(memory)
+ // sw deint
+ if (doDeintH2645)
+ {
+ var swDeintFilter = GetSwDeinterlaceFilter(state, options);
+ mainFilters.Add(swDeintFilter);
+ }
+
+ var outFormat = doOclTonemap ? "yuv420p10le" : (hasGraphicalSubs ? "yuv420p" : "nv12");
+ var swScaleFilter = GetSwScaleFilter(state, options, vidEncoder, inW, inH, threeDFormat, reqW, reqH, reqMaxW, reqMaxH);
+ if (!string.IsNullOrEmpty(swScaleFilter))
+ {
+ swScaleFilter += ":flags=fast_bilinear";
+ }
+
+ // sw scale
+ mainFilters.Add(swScaleFilter);
+ mainFilters.Add("format=" + outFormat);
+
+ // keep video at memory except ocl tonemap,
+ // since the overhead caused by hwupload >>> using sw filter.
+ // sw => hw
+ if (doOclTonemap)
+ {
+ mainFilters.Add("hwupload=derive_device=opencl");
+ }
+ }
+ else if (isRkmppDecoder)
+ {
+ // INPUT rkmpp/drm surface(gem/dma-heap)
+
+ var isFullAfbcPipeline = isDrmInDrmOut && !doOclTonemap;
+ var outFormat = doOclTonemap ? "p010" : "nv12";
+ var hwScaleFilter = GetHwScaleFilter("rkrga", outFormat, inW, inH, reqW, reqH, reqMaxW, reqMaxH);
+ var hwScaleFilter2 = GetHwScaleFilter("rkrga", string.Empty, inW, inH, reqW, reqH, reqMaxW, reqMaxH);
+
+ if (!hasSubs
+ || !isFullAfbcPipeline
+ || !string.IsNullOrEmpty(hwScaleFilter2))
+ {
+ // try enabling AFBC to save DDR bandwidth
+ if (!string.IsNullOrEmpty(hwScaleFilter) && isFullAfbcPipeline)
+ {
+ hwScaleFilter += ":afbc=1";
+ }
+
+ // hw scale
+ mainFilters.Add(hwScaleFilter);
+ }
+ }
+
+ if (doOclTonemap && isRkmppDecoder)
+ {
+ // map from rkmpp/drm to opencl via drm-opencl interop.
+ mainFilters.Add("hwmap=derive_device=opencl:mode=read");
+ }
+
+ // ocl tonemap
+ if (doOclTonemap)
+ {
+ var tonemapFilter = GetHwTonemapFilter(options, "opencl", "nv12");
+ // enable tradeoffs for performance
+ if (!string.IsNullOrEmpty(tonemapFilter))
+ {
+ tonemapFilter += ":tradeoff=1";
+ }
+
+ mainFilters.Add(tonemapFilter);
+ }
+
+ var memoryOutput = false;
+ var isUploadForOclTonemap = isSwDecoder && doOclTonemap;
+ if ((isRkmppDecoder && isSwEncoder) || isUploadForOclTonemap)
+ {
+ memoryOutput = true;
+
+ // OUTPUT nv12 surface(memory)
+ mainFilters.Add("hwdownload");
+ mainFilters.Add("format=nv12");
+ }
+
+ // OUTPUT nv12 surface(memory)
+ if (isSwDecoder && isRkmppEncoder)
+ {
+ memoryOutput = true;
+ }
+
+ if (memoryOutput)
+ {
+ // text subtitles
+ if (hasTextSubs)
+ {
+ var textSubtitlesFilter = GetTextSubtitlesFilter(state, false, false);
+ mainFilters.Add(textSubtitlesFilter);
+ }
+ }
+
+ if (isDrmInDrmOut)
+ {
+ if (doOclTonemap)
+ {
+ // OUTPUT drm(nv12) surface(gem/dma-heap)
+ // reverse-mapping via drm-opencl interop.
+ mainFilters.Add("hwmap=derive_device=rkmpp:mode=write:reverse=1");
+ mainFilters.Add("format=drm_prime");
+ }
+ }
+
+ /* Make sub and overlay filters for subtitle stream */
+ var subFilters = new List<string>();
+ var overlayFilters = new List<string>();
+ if (isDrmInDrmOut)
+ {
+ if (hasSubs)
+ {
+ if (hasGraphicalSubs)
+ {
+ var subPreProcFilters = GetGraphicalSubPreProcessFilters(inW, inH, reqW, reqH, reqMaxW, reqMaxH);
+ subFilters.Add(subPreProcFilters);
+ subFilters.Add("format=bgra");
+ }
+ else if (hasTextSubs)
+ {
+ var framerate = state.VideoStream?.RealFrameRate;
+ var subFramerate = hasAssSubs ? Math.Min(framerate ?? 25, 60) : 10;
+
+ // alphasrc=s=1280x720:r=10:start=0,format=bgra,subtitles,hwupload
+ var alphaSrcFilter = GetAlphaSrcFilter(state, inW, inH, reqW, reqH, reqMaxW, reqMaxH, subFramerate);
+ var subTextSubtitlesFilter = GetTextSubtitlesFilter(state, true, true);
+ subFilters.Add(alphaSrcFilter);
+ subFilters.Add("format=bgra");
+ subFilters.Add(subTextSubtitlesFilter);
+ }
+
+ subFilters.Add("hwupload=derive_device=rkmpp");
+
+ // try enabling AFBC to save DDR bandwidth
+ overlayFilters.Add("overlay_rkrga=eof_action=pass:repeatlast=0:format=nv12:afbc=1");
+ }
+ }
+ else if (memoryOutput)
+ {
+ if (hasGraphicalSubs)
+ {
+ var subPreProcFilters = GetGraphicalSubPreProcessFilters(inW, inH, reqW, reqH, reqMaxW, reqMaxH);
+ subFilters.Add(subPreProcFilters);
+ overlayFilters.Add("overlay=eof_action=pass:repeatlast=0");
+ }
+ }
+
+ return (mainFilters, subFilters, overlayFilters);
+ }
+
+ /// <summary>
/// Gets the parameter of video processing filters.
/// </summary>
/// <param name="state">Encoding state.</param>
@@ -4956,6 +5283,10 @@ namespace MediaBrowser.Controller.MediaEncoding
{
(mainFilters, subFilters, overlayFilters) = GetAppleVidFilterChain(state, options, outputVideoCodec);
}
+ else if (string.Equals(options.HardwareAccelerationType, "rkmpp", StringComparison.OrdinalIgnoreCase))
+ {
+ (mainFilters, subFilters, overlayFilters) = GetRkmppVidFilterChain(state, options, outputVideoCodec);
+ }
else
{
(mainFilters, subFilters, overlayFilters) = GetSwVidFilterChain(state, options, outputVideoCodec);
@@ -5087,18 +5418,21 @@ namespace MediaBrowser.Controller.MediaEncoding
if (string.Equals(videoStream.PixelFormat, "yuv420p", StringComparison.OrdinalIgnoreCase)
|| string.Equals(videoStream.PixelFormat, "yuvj420p", StringComparison.OrdinalIgnoreCase)
+ || string.Equals(videoStream.PixelFormat, "yuv422p", StringComparison.OrdinalIgnoreCase)
|| string.Equals(videoStream.PixelFormat, "yuv444p", StringComparison.OrdinalIgnoreCase))
{
return 8;
}
if (string.Equals(videoStream.PixelFormat, "yuv420p10le", StringComparison.OrdinalIgnoreCase)
+ || string.Equals(videoStream.PixelFormat, "yuv422p10le", StringComparison.OrdinalIgnoreCase)
|| string.Equals(videoStream.PixelFormat, "yuv444p10le", StringComparison.OrdinalIgnoreCase))
{
return 10;
}
if (string.Equals(videoStream.PixelFormat, "yuv420p12le", StringComparison.OrdinalIgnoreCase)
+ || string.Equals(videoStream.PixelFormat, "yuv422p12le", StringComparison.OrdinalIgnoreCase)
|| string.Equals(videoStream.PixelFormat, "yuv444p12le", StringComparison.OrdinalIgnoreCase))
{
return 12;
@@ -5151,7 +5485,12 @@ namespace MediaBrowser.Controller.MediaEncoding
|| string.Equals(videoStream.Codec, "vp9", StringComparison.OrdinalIgnoreCase)
|| string.Equals(videoStream.Codec, "av1", StringComparison.OrdinalIgnoreCase)))
{
- return null;
+ // One exception is that RKMPP decoder can handle H.264 High 10.
+ if (!(string.Equals(options.HardwareAccelerationType, "rkmpp", StringComparison.OrdinalIgnoreCase)
+ && string.Equals(videoStream.Codec, "h264", StringComparison.OrdinalIgnoreCase)))
+ {
+ return null;
+ }
}
if (string.Equals(options.HardwareAccelerationType, "qsv", StringComparison.OrdinalIgnoreCase))
@@ -5178,6 +5517,11 @@ namespace MediaBrowser.Controller.MediaEncoding
{
return GetVideotoolboxVidDecoder(state, options, videoStream, bitDepth);
}
+
+ if (string.Equals(options.HardwareAccelerationType, "rkmpp", StringComparison.OrdinalIgnoreCase))
+ {
+ return GetRkmppVidDecoder(state, options, videoStream, bitDepth);
+ }
}
var whichCodec = videoStream.Codec;
@@ -5243,6 +5587,11 @@ namespace MediaBrowser.Controller.MediaEncoding
return null;
}
+ if (string.Equals(decoderSuffix, "rkmpp", StringComparison.OrdinalIgnoreCase))
+ {
+ return null;
+ }
+
return isCodecAvailable ? (" -c:v " + decoderName) : null;
}
@@ -5265,6 +5614,7 @@ namespace MediaBrowser.Controller.MediaEncoding
var isCudaSupported = (isLinux || isWindows) && IsCudaFullSupported();
var isQsvSupported = (isLinux || isWindows) && _mediaEncoder.SupportsHwaccel("qsv");
var isVideotoolboxSupported = isMacOS && _mediaEncoder.SupportsHwaccel("videotoolbox");
+ var isRkmppSupported = isLinux && IsRkmppFullSupported();
var isCodecAvailable = options.HardwareDecodingCodecs.Contains(videoCodec, StringComparison.OrdinalIgnoreCase);
var ffmpegVersion = _mediaEncoder.EncoderVersion;
@@ -5367,6 +5717,14 @@ namespace MediaBrowser.Controller.MediaEncoding
return " -hwaccel videotoolbox" + (outputHwSurface ? " -hwaccel_output_format videotoolbox_vld" : string.Empty);
}
+ // Rockchip rkmpp
+ if (string.Equals(options.HardwareAccelerationType, "rkmpp", StringComparison.OrdinalIgnoreCase)
+ && isRkmppSupported
+ && isCodecAvailable)
+ {
+ return " -hwaccel rkmpp" + (outputHwSurface ? " -hwaccel_output_format drm_prime" : string.Empty);
+ }
+
return null;
}
@@ -5673,6 +6031,102 @@ namespace MediaBrowser.Controller.MediaEncoding
return null;
}
+ public string GetRkmppVidDecoder(EncodingJobInfo state, EncodingOptions options, MediaStream videoStream, int bitDepth)
+ {
+ var isLinux = OperatingSystem.IsLinux();
+
+ if (!isLinux
+ || !string.Equals(options.HardwareAccelerationType, "rkmpp", StringComparison.OrdinalIgnoreCase))
+ {
+ return null;
+ }
+
+ var inW = state.VideoStream?.Width;
+ var inH = state.VideoStream?.Height;
+ var reqW = state.BaseRequest.Width;
+ var reqH = state.BaseRequest.Height;
+ var reqMaxW = state.BaseRequest.MaxWidth;
+ var reqMaxH = state.BaseRequest.MaxHeight;
+
+ // rkrga RGA2e supports range from 1/16 to 16
+ if (!IsScaleRatioSupported(inW, inH, reqW, reqH, reqMaxW, reqMaxH, 16.0f))
+ {
+ return null;
+ }
+
+ var isRkmppOclSupported = IsRkmppFullSupported() && IsOpenclFullSupported();
+ var hwSurface = isRkmppOclSupported
+ && _mediaEncoder.SupportsFilter("alphasrc");
+
+ // rkrga RGA3 supports range from 1/8 to 8
+ var isAfbcSupported = hwSurface && IsScaleRatioSupported(inW, inH, reqW, reqH, reqMaxW, reqMaxH, 8.0f);
+
+ // TODO: add more 8/10bit and 4:2:2 formats for Rkmpp after finishing the ffcheck tool
+ var is8bitSwFormatsRkmpp = string.Equals("yuv420p", videoStream.PixelFormat, StringComparison.OrdinalIgnoreCase)
+ || string.Equals("yuvj420p", videoStream.PixelFormat, StringComparison.OrdinalIgnoreCase);
+ var is10bitSwFormatsRkmpp = string.Equals("yuv420p10le", videoStream.PixelFormat, StringComparison.OrdinalIgnoreCase);
+ var is8_10bitSwFormatsRkmpp = is8bitSwFormatsRkmpp || is10bitSwFormatsRkmpp;
+
+ // nv15 and nv20 are bit-stream only formats
+ if (is10bitSwFormatsRkmpp && !hwSurface)
+ {
+ return null;
+ }
+
+ if (is8bitSwFormatsRkmpp)
+ {
+ if (string.Equals(videoStream.Codec, "mpeg1video", StringComparison.OrdinalIgnoreCase))
+ {
+ return GetHwaccelType(state, options, "mpeg1video", bitDepth, hwSurface);
+ }
+
+ if (string.Equals(videoStream.Codec, "mpeg2video", StringComparison.OrdinalIgnoreCase))
+ {
+ return GetHwaccelType(state, options, "mpeg2video", bitDepth, hwSurface);
+ }
+
+ if (string.Equals(videoStream.Codec, "mpeg4", StringComparison.OrdinalIgnoreCase))
+ {
+ return GetHwaccelType(state, options, "mpeg4", bitDepth, hwSurface);
+ }
+
+ if (string.Equals(videoStream.Codec, "vp8", StringComparison.OrdinalIgnoreCase))
+ {
+ return GetHwaccelType(state, options, "vp8", bitDepth, hwSurface);
+ }
+ }
+
+ if (is8_10bitSwFormatsRkmpp)
+ {
+ if (string.Equals(videoStream.Codec, "avc", StringComparison.OrdinalIgnoreCase)
+ || string.Equals(videoStream.Codec, "h264", StringComparison.OrdinalIgnoreCase))
+ {
+ var accelType = GetHwaccelType(state, options, "h264", bitDepth, hwSurface);
+ return accelType + ((!string.IsNullOrEmpty(accelType) && isAfbcSupported) ? " -afbc rga" : string.Empty);
+ }
+
+ if (string.Equals(videoStream.Codec, "hevc", StringComparison.OrdinalIgnoreCase)
+ || string.Equals(videoStream.Codec, "h265", StringComparison.OrdinalIgnoreCase))
+ {
+ var accelType = GetHwaccelType(state, options, "hevc", bitDepth, hwSurface);
+ return accelType + ((!string.IsNullOrEmpty(accelType) && isAfbcSupported) ? " -afbc rga" : string.Empty);
+ }
+
+ if (string.Equals(videoStream.Codec, "vp9", StringComparison.OrdinalIgnoreCase))
+ {
+ var accelType = GetHwaccelType(state, options, "vp9", bitDepth, hwSurface);
+ return accelType + ((!string.IsNullOrEmpty(accelType) && isAfbcSupported) ? " -afbc rga" : string.Empty);
+ }
+
+ if (string.Equals(videoStream.Codec, "av1", StringComparison.OrdinalIgnoreCase))
+ {
+ return GetHwaccelType(state, options, "av1", bitDepth, hwSurface);
+ }
+ }
+
+ return null;
+ }
+
/// <summary>
/// Gets the number of threads.
/// </summary>
@@ -6087,13 +6541,14 @@ namespace MediaBrowser.Controller.MediaEncoding
return " -codec:s:0 " + codec + " -disposition:s:0 default";
}
- public string GetProgressiveVideoFullCommandLine(EncodingJobInfo state, EncodingOptions encodingOptions, string outputPath, string defaultPreset)
+ public string GetProgressiveVideoFullCommandLine(EncodingJobInfo state, EncodingOptions encodingOptions, string defaultPreset)
{
// Get the output codec name
var videoCodec = GetVideoEncoder(state, encodingOptions);
var format = string.Empty;
var keyFrame = string.Empty;
+ var outputPath = state.OutputFilePath;
if (Path.GetExtension(outputPath.AsSpan()).Equals(".mp4", StringComparison.OrdinalIgnoreCase)
&& state.BaseRequest.Context == EncodingContext.Streaming)
diff --git a/MediaBrowser.Controller/MediaEncoding/EncodingJobInfo.cs b/MediaBrowser.Controller/MediaEncoding/EncodingJobInfo.cs
index 17813559a..f2a0b906d 100644
--- a/MediaBrowser.Controller/MediaEncoding/EncodingJobInfo.cs
+++ b/MediaBrowser.Controller/MediaEncoding/EncodingJobInfo.cs
@@ -619,6 +619,26 @@ namespace MediaBrowser.Controller.MediaEncoding
return Array.Empty<string>();
}
+ public string[] GetRequestedCodecTags(string codec)
+ {
+ if (!string.IsNullOrEmpty(BaseRequest.CodecTag))
+ {
+ return BaseRequest.CodecTag.Split(new[] { '|', ',' }, StringSplitOptions.RemoveEmptyEntries);
+ }
+
+ if (!string.IsNullOrEmpty(codec))
+ {
+ var codectag = BaseRequest.GetOption(codec, "codectag");
+
+ if (!string.IsNullOrEmpty(codectag))
+ {
+ return codectag.Split(new[] { '|', ',' }, StringSplitOptions.RemoveEmptyEntries);
+ }
+ }
+
+ return Array.Empty<string>();
+ }
+
public string GetRequestedLevel(string codec)
{
if (!string.IsNullOrEmpty(BaseRequest.Level))
diff --git a/MediaBrowser.Controller/MediaEncoding/ITranscodeManager.cs b/MediaBrowser.Controller/MediaEncoding/ITranscodeManager.cs
index c19a12ae7..09bc01f74 100644
--- a/MediaBrowser.Controller/MediaEncoding/ITranscodeManager.cs
+++ b/MediaBrowser.Controller/MediaEncoding/ITranscodeManager.cs
@@ -96,9 +96,10 @@ public interface ITranscodeManager
public void OnTranscodeEndRequest(TranscodingJob job);
/// <summary>
- /// Gets the transcoding lock.
+ /// Transcoding lock.
/// </summary>
/// <param name="outputPath">The output path of the transcoded file.</param>
- /// <returns>A <see cref="SemaphoreSlim"/>.</returns>
- public SemaphoreSlim GetTranscodingLock(string outputPath);
+ /// <param name="cancellationToken">The cancellation token.</param>
+ /// <returns>An <see cref="IDisposable"/>.</returns>
+ ValueTask<IDisposable> LockAsync(string outputPath, CancellationToken cancellationToken);
}
diff --git a/MediaBrowser.Controller/MediaEncoding/ImageEncodingOptions.cs b/MediaBrowser.Controller/MediaEncoding/ImageEncodingOptions.cs
deleted file mode 100644
index 044ba6d33..000000000
--- a/MediaBrowser.Controller/MediaEncoding/ImageEncodingOptions.cs
+++ /dev/null
@@ -1,23 +0,0 @@
-#nullable disable
-
-#pragma warning disable CS1591
-
-namespace MediaBrowser.Controller.MediaEncoding
-{
- public class ImageEncodingOptions
- {
- public string InputPath { get; set; }
-
- public int? Width { get; set; }
-
- public int? Height { get; set; }
-
- public int? MaxWidth { get; set; }
-
- public int? MaxHeight { get; set; }
-
- public int? Quality { get; set; }
-
- public string Format { get; set; }
- }
-}
diff --git a/MediaBrowser.Controller/MediaEncoding/MediaEncoderHelpers.cs b/MediaBrowser.Controller/MediaEncoding/MediaEncoderHelpers.cs
deleted file mode 100644
index 841e7b287..000000000
--- a/MediaBrowser.Controller/MediaEncoding/MediaEncoderHelpers.cs
+++ /dev/null
@@ -1,11 +0,0 @@
-#pragma warning disable CS1591
-
-namespace MediaBrowser.Controller.MediaEncoding
-{
- /// <summary>
- /// Class MediaEncoderHelpers.
- /// </summary>
- public static class MediaEncoderHelpers
- {
- }
-}
diff --git a/MediaBrowser.Controller/Plugins/IRunBeforeStartup.cs b/MediaBrowser.Controller/Plugins/IRunBeforeStartup.cs
deleted file mode 100644
index 2b831103a..000000000
--- a/MediaBrowser.Controller/Plugins/IRunBeforeStartup.cs
+++ /dev/null
@@ -1,9 +0,0 @@
-namespace MediaBrowser.Controller.Plugins
-{
- /// <summary>
- /// Indicates that a <see cref="IServerEntryPoint"/> should be invoked as a pre-startup task.
- /// </summary>
- public interface IRunBeforeStartup
- {
- }
-}
diff --git a/MediaBrowser.Controller/Plugins/IServerEntryPoint.cs b/MediaBrowser.Controller/Plugins/IServerEntryPoint.cs
deleted file mode 100644
index 6024661e1..000000000
--- a/MediaBrowser.Controller/Plugins/IServerEntryPoint.cs
+++ /dev/null
@@ -1,20 +0,0 @@
-using System;
-using System.Threading.Tasks;
-
-namespace MediaBrowser.Controller.Plugins
-{
- /// <summary>
- /// Represents an entry point for a module in the application. This interface is scanned for automatically and
- /// provides a hook to initialize the module at application start.
- /// The entry point can additionally be flagged as a pre-startup task by implementing the
- /// <see cref="IRunBeforeStartup"/> interface.
- /// </summary>
- public interface IServerEntryPoint : IDisposable
- {
- /// <summary>
- /// Run the initialization for this module. This method is invoked at application start.
- /// </summary>
- /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>
- Task RunAsync();
- }
-}
diff --git a/MediaBrowser.MediaEncoding/Attachments/AttachmentExtractor.cs b/MediaBrowser.MediaEncoding/Attachments/AttachmentExtractor.cs
index 299f294b2..ff91a60a7 100644
--- a/MediaBrowser.MediaEncoding/Attachments/AttachmentExtractor.cs
+++ b/MediaBrowser.MediaEncoding/Attachments/AttachmentExtractor.cs
@@ -8,6 +8,7 @@ using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
+using AsyncKeyedLock;
using MediaBrowser.Common.Configuration;
using MediaBrowser.Common.Extensions;
using MediaBrowser.Controller.Entities;
@@ -22,7 +23,7 @@ using Microsoft.Extensions.Logging;
namespace MediaBrowser.MediaEncoding.Attachments
{
- public sealed class AttachmentExtractor : IAttachmentExtractor
+ public sealed class AttachmentExtractor : IAttachmentExtractor, IDisposable
{
private readonly ILogger<AttachmentExtractor> _logger;
private readonly IApplicationPaths _appPaths;
@@ -30,8 +31,11 @@ namespace MediaBrowser.MediaEncoding.Attachments
private readonly IMediaEncoder _mediaEncoder;
private readonly IMediaSourceManager _mediaSourceManager;
- private readonly ConcurrentDictionary<string, SemaphoreSlim> _semaphoreLocks =
- new ConcurrentDictionary<string, SemaphoreSlim>();
+ private readonly AsyncKeyedLocker<string> _semaphoreLocks = new(o =>
+ {
+ o.PoolSize = 20;
+ o.PoolInitialFill = 1;
+ });
public AttachmentExtractor(
ILogger<AttachmentExtractor> logger,
@@ -84,11 +88,7 @@ namespace MediaBrowser.MediaEncoding.Attachments
string outputPath,
CancellationToken cancellationToken)
{
- var semaphore = _semaphoreLocks.GetOrAdd(outputPath, key => new SemaphoreSlim(1, 1));
-
- await semaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
-
- try
+ using (await _semaphoreLocks.LockAsync(outputPath, cancellationToken).ConfigureAwait(false))
{
if (!Directory.Exists(outputPath))
{
@@ -99,10 +99,6 @@ namespace MediaBrowser.MediaEncoding.Attachments
cancellationToken).ConfigureAwait(false);
}
}
- finally
- {
- semaphore.Release();
- }
}
public async Task ExtractAllAttachmentsExternal(
@@ -111,11 +107,7 @@ namespace MediaBrowser.MediaEncoding.Attachments
string outputPath,
CancellationToken cancellationToken)
{
- var semaphore = _semaphoreLocks.GetOrAdd(outputPath, key => new SemaphoreSlim(1, 1));
-
- await semaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
-
- try
+ using (await _semaphoreLocks.LockAsync(outputPath, cancellationToken).ConfigureAwait(false))
{
if (!File.Exists(Path.Join(outputPath, id)))
{
@@ -131,10 +123,6 @@ namespace MediaBrowser.MediaEncoding.Attachments
}
}
}
- finally
- {
- semaphore.Release();
- }
}
private async Task ExtractAllAttachmentsInternal(
@@ -256,11 +244,7 @@ namespace MediaBrowser.MediaEncoding.Attachments
string outputPath,
CancellationToken cancellationToken)
{
- var semaphore = _semaphoreLocks.GetOrAdd(outputPath, key => new SemaphoreSlim(1, 1));
-
- await semaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
-
- try
+ using (await _semaphoreLocks.LockAsync(outputPath, cancellationToken).ConfigureAwait(false))
{
if (!File.Exists(outputPath))
{
@@ -271,10 +255,6 @@ namespace MediaBrowser.MediaEncoding.Attachments
cancellationToken).ConfigureAwait(false);
}
}
- finally
- {
- semaphore.Release();
- }
}
private async Task ExtractAttachmentInternal(
@@ -379,5 +359,11 @@ namespace MediaBrowser.MediaEncoding.Attachments
var prefix = filename.AsSpan(0, 1);
return Path.Join(_appPaths.DataPath, "attachments", prefix, filename);
}
+
+ /// <inheritdoc />
+ public void Dispose()
+ {
+ _semaphoreLocks.Dispose();
+ }
}
}
diff --git a/MediaBrowser.MediaEncoding/Encoder/EncoderValidator.cs b/MediaBrowser.MediaEncoding/Encoder/EncoderValidator.cs
index 0d1d27ae8..fdca28390 100644
--- a/MediaBrowser.MediaEncoding/Encoder/EncoderValidator.cs
+++ b/MediaBrowser.MediaEncoding/Encoder/EncoderValidator.cs
@@ -45,7 +45,15 @@ namespace MediaBrowser.MediaEncoding.Encoder
"mpeg4_cuvid",
"vp8_cuvid",
"vp9_cuvid",
- "av1_cuvid"
+ "av1_cuvid",
+ "h264_rkmpp",
+ "hevc_rkmpp",
+ "mpeg1_rkmpp",
+ "mpeg2_rkmpp",
+ "mpeg4_rkmpp",
+ "vp8_rkmpp",
+ "vp9_rkmpp",
+ "av1_rkmpp"
};
private static readonly string[] _requiredEncoders = new[]
@@ -82,7 +90,9 @@ namespace MediaBrowser.MediaEncoding.Encoder
"av1_vaapi",
"h264_v4l2m2m",
"h264_videotoolbox",
- "hevc_videotoolbox"
+ "hevc_videotoolbox",
+ "h264_rkmpp",
+ "hevc_rkmpp"
};
private static readonly string[] _requiredFilters = new[]
@@ -116,9 +126,12 @@ namespace MediaBrowser.MediaEncoding.Encoder
"libplacebo",
"scale_vulkan",
"overlay_vulkan",
- "hwupload_vaapi",
// videotoolbox
- "yadif_videotoolbox"
+ "yadif_videotoolbox",
+ // rkrga
+ "scale_rkrga",
+ "vpp_rkrga",
+ "overlay_rkrga"
};
private static readonly Dictionary<int, string[]> _filterOptionsDict = new Dictionary<int, string[]>
diff --git a/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs b/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs
index 4dbefca4b..cc6971c1b 100644
--- a/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs
+++ b/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs
@@ -11,6 +11,7 @@ using System.Text.Json;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
+using AsyncKeyedLock;
using Jellyfin.Extensions;
using Jellyfin.Extensions.Json;
using Jellyfin.Extensions.Json.Converters;
@@ -60,7 +61,7 @@ namespace MediaBrowser.MediaEncoding.Encoder
private readonly IServerConfigurationManager _serverConfig;
private readonly string _startupOptionFFmpegPath;
- private readonly SemaphoreSlim _thumbnailResourcePool;
+ private readonly AsyncNonKeyedLocker _thumbnailResourcePool;
private readonly object _runningProcessesLock = new object();
private readonly List<ProcessWrapper> _runningProcesses = new List<ProcessWrapper>();
@@ -116,7 +117,7 @@ namespace MediaBrowser.MediaEncoding.Encoder
_jsonSerializerOptions.Converters.Add(new JsonBoolStringConverter());
var semaphoreCount = 2 * Environment.ProcessorCount;
- _thumbnailResourcePool = new SemaphoreSlim(semaphoreCount, semaphoreCount);
+ _thumbnailResourcePool = new(semaphoreCount);
}
/// <inheritdoc />
@@ -754,8 +755,7 @@ namespace MediaBrowser.MediaEncoding.Encoder
{
bool ranToCompletion;
- await _thumbnailResourcePool.WaitAsync(cancellationToken).ConfigureAwait(false);
- try
+ using (await _thumbnailResourcePool.LockAsync(cancellationToken).ConfigureAwait(false))
{
StartProcess(processWrapper);
@@ -776,10 +776,6 @@ namespace MediaBrowser.MediaEncoding.Encoder
ranToCompletion = false;
}
}
- finally
- {
- _thumbnailResourcePool.Release();
- }
var exitCode = ranToCompletion ? processWrapper.ExitCode ?? 0 : -1;
var file = _fileSystem.GetFileInfo(tempExtractPath);
@@ -908,8 +904,7 @@ namespace MediaBrowser.MediaEncoding.Encoder
{
bool ranToCompletion = false;
- await _thumbnailResourcePool.WaitAsync(cancellationToken).ConfigureAwait(false);
- try
+ using (await _thumbnailResourcePool.LockAsync(cancellationToken).ConfigureAwait(false))
{
StartProcess(processWrapper);
@@ -963,10 +958,6 @@ namespace MediaBrowser.MediaEncoding.Encoder
StopProcess(processWrapper, 1000);
}
}
- finally
- {
- _thumbnailResourcePool.Release();
- }
var exitCode = ranToCompletion ? processWrapper.ExitCode ?? 0 : -1;
@@ -1120,6 +1111,7 @@ namespace MediaBrowser.MediaEncoding.Encoder
return allVobs
.Where(vob => titles.Contains(_fileSystem.GetFileNameWithoutExtension(vob).AsSpan().RightPart('_').ToString()))
.Select(i => i.FullName)
+ .Order()
.ToList();
}
@@ -1136,6 +1128,7 @@ namespace MediaBrowser.MediaEncoding.Encoder
return directoryFiles
.Where(f => validPlaybackFiles.Contains(f.Name, StringComparer.OrdinalIgnoreCase))
.Select(f => f.FullName)
+ .Order()
.ToList();
}
@@ -1159,31 +1152,29 @@ namespace MediaBrowser.MediaEncoding.Encoder
}
// Generate concat configuration entries for each file and write to file
- using (StreamWriter sw = new StreamWriter(concatFilePath))
+ using StreamWriter sw = new StreamWriter(concatFilePath);
+ foreach (var path in files)
{
- foreach (var path in files)
- {
- var mediaInfoResult = GetMediaInfo(
- new MediaInfoRequest
+ var mediaInfoResult = GetMediaInfo(
+ new MediaInfoRequest
+ {
+ MediaType = DlnaProfileType.Video,
+ MediaSource = new MediaSourceInfo
{
- MediaType = DlnaProfileType.Video,
- MediaSource = new MediaSourceInfo
- {
- Path = path,
- Protocol = MediaProtocol.File,
- VideoType = videoType
- }
- },
- CancellationToken.None).GetAwaiter().GetResult();
-
- var duration = TimeSpan.FromTicks(mediaInfoResult.RunTimeTicks.Value).TotalSeconds;
-
- // Add file path stanza to concat configuration
- sw.WriteLine("file '{0}'", path);
-
- // Add duration stanza to concat configuration
- sw.WriteLine("duration {0}", duration);
- }
+ Path = path,
+ Protocol = MediaProtocol.File,
+ VideoType = videoType
+ }
+ },
+ CancellationToken.None).GetAwaiter().GetResult();
+
+ var duration = TimeSpan.FromTicks(mediaInfoResult.RunTimeTicks.Value).TotalSeconds;
+
+ // Add file path stanza to concat configuration
+ sw.WriteLine("file '{0}'", path);
+
+ // Add duration stanza to concat configuration
+ sw.WriteLine("duration {0}", duration);
}
}
diff --git a/MediaBrowser.MediaEncoding/MediaBrowser.MediaEncoding.csproj b/MediaBrowser.MediaEncoding/MediaBrowser.MediaEncoding.csproj
index a4e8194c1..be63513a7 100644
--- a/MediaBrowser.MediaEncoding/MediaBrowser.MediaEncoding.csproj
+++ b/MediaBrowser.MediaEncoding/MediaBrowser.MediaEncoding.csproj
@@ -1,4 +1,4 @@
-<Project Sdk="Microsoft.NET.Sdk">
+<Project Sdk="Microsoft.NET.Sdk">
<!-- ProjectGuid is only included as a requirement for SonarQube analysis -->
<PropertyGroup>
@@ -22,6 +22,7 @@
</ItemGroup>
<ItemGroup>
+ <PackageReference Include="AsyncKeyedLock" />
<PackageReference Include="BDInfo" />
<PackageReference Include="libse" />
<PackageReference Include="Microsoft.Extensions.Http" />
diff --git a/MediaBrowser.MediaEncoding/Probing/ProbeResultNormalizer.cs b/MediaBrowser.MediaEncoding/Probing/ProbeResultNormalizer.cs
index b532f9a7e..317aba418 100644
--- a/MediaBrowser.MediaEncoding/Probing/ProbeResultNormalizer.cs
+++ b/MediaBrowser.MediaEncoding/Probing/ProbeResultNormalizer.cs
@@ -30,6 +30,8 @@ namespace MediaBrowser.MediaEncoding.Probing
private const string ArtistReplaceValue = " | ";
private readonly char[] _nameDelimiters = { '/', '|', ';', '\\' };
+ private readonly string[] _webmVideoCodecs = { "av1", "vp8", "vp9" };
+ private readonly string[] _webmAudioCodecs = { "opus", "vorbis" };
private readonly ILogger _logger;
private readonly ILocalizationManager _localization;
@@ -114,7 +116,7 @@ namespace MediaBrowser.MediaEncoding.Probing
if (data.Format is not null)
{
- info.Container = NormalizeFormat(data.Format.FormatName);
+ info.Container = NormalizeFormat(data.Format.FormatName, info.MediaStreams);
if (int.TryParse(data.Format.BitRate, CultureInfo.InvariantCulture, out var value))
{
@@ -260,7 +262,7 @@ namespace MediaBrowser.MediaEncoding.Probing
return info;
}
- private string NormalizeFormat(string format)
+ private string NormalizeFormat(string format, IReadOnlyList<MediaStream> mediaStreams)
{
if (string.IsNullOrWhiteSpace(format))
{
@@ -288,9 +290,20 @@ namespace MediaBrowser.MediaEncoding.Probing
{
splitFormat[i] = "mkv";
}
+
+ // Handle WebM
+ else if (string.Equals(splitFormat[i], "webm", StringComparison.OrdinalIgnoreCase))
+ {
+ // Limit WebM to supported codecs
+ if (mediaStreams.Any(stream => (stream.Type == MediaStreamType.Video && !_webmVideoCodecs.Contains(stream.Codec, StringComparison.OrdinalIgnoreCase))
+ || (stream.Type == MediaStreamType.Audio && !_webmAudioCodecs.Contains(stream.Codec, StringComparison.OrdinalIgnoreCase))))
+ {
+ splitFormat[i] = string.Empty;
+ }
+ }
}
- return string.Join(',', splitFormat);
+ return string.Join(',', splitFormat.Where(s => !string.IsNullOrEmpty(s)));
}
private int? GetEstimatedAudioBitrate(string codec, int? channels)
diff --git a/MediaBrowser.MediaEncoding/Subtitles/SubtitleEncoder.cs b/MediaBrowser.MediaEncoding/Subtitles/SubtitleEncoder.cs
index 459d854bf..4b1b1bbc6 100644
--- a/MediaBrowser.MediaEncoding/Subtitles/SubtitleEncoder.cs
+++ b/MediaBrowser.MediaEncoding/Subtitles/SubtitleEncoder.cs
@@ -1,7 +1,7 @@
#pragma warning disable CS1591
using System;
-using System.Collections.Concurrent;
+using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
@@ -11,6 +11,7 @@ using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
+using AsyncKeyedLock;
using MediaBrowser.Common;
using MediaBrowser.Common.Configuration;
using MediaBrowser.Common.Extensions;
@@ -27,7 +28,7 @@ using UtfUnknown;
namespace MediaBrowser.MediaEncoding.Subtitles
{
- public sealed class SubtitleEncoder : ISubtitleEncoder
+ public sealed class SubtitleEncoder : ISubtitleEncoder, IDisposable
{
private readonly ILogger<SubtitleEncoder> _logger;
private readonly IApplicationPaths _appPaths;
@@ -40,8 +41,11 @@ namespace MediaBrowser.MediaEncoding.Subtitles
/// <summary>
/// The _semaphoreLocks.
/// </summary>
- private readonly ConcurrentDictionary<string, SemaphoreSlim> _semaphoreLocks =
- new ConcurrentDictionary<string, SemaphoreSlim>();
+ private readonly AsyncKeyedLocker<string> _semaphoreLocks = new(o =>
+ {
+ o.PoolSize = 20;
+ o.PoolInitialFill = 1;
+ });
public SubtitleEncoder(
ILogger<SubtitleEncoder> logger,
@@ -194,36 +198,11 @@ namespace MediaBrowser.MediaEncoding.Subtitles
{
if (!subtitleStream.IsExternal || subtitleStream.Path.EndsWith(".mks", StringComparison.OrdinalIgnoreCase))
{
- string outputFormat;
- string outputCodec;
+ await ExtractAllTextSubtitles(mediaSource, cancellationToken).ConfigureAwait(false);
- if (string.Equals(subtitleStream.Codec, "ass", StringComparison.OrdinalIgnoreCase)
- || string.Equals(subtitleStream.Codec, "ssa", StringComparison.OrdinalIgnoreCase)
- || string.Equals(subtitleStream.Codec, "srt", StringComparison.OrdinalIgnoreCase))
- {
- // Extract
- outputCodec = "copy";
- outputFormat = subtitleStream.Codec;
- }
- else if (string.Equals(subtitleStream.Codec, "subrip", StringComparison.OrdinalIgnoreCase))
- {
- // Extract
- outputCodec = "copy";
- outputFormat = "srt";
- }
- else
- {
- // Extract
- outputCodec = "srt";
- outputFormat = "srt";
- }
-
- // Extract
+ var outputFormat = GetTextSubtitleFormat(subtitleStream);
var outputPath = GetSubtitleCachePath(mediaSource, subtitleStream.Index, "." + outputFormat);
- await ExtractTextSubtitle(mediaSource, subtitleStream, outputCodec, outputPath, cancellationToken)
- .ConfigureAwait(false);
-
return new SubtitleInfo()
{
Path = outputPath,
@@ -318,16 +297,6 @@ namespace MediaBrowser.MediaEncoding.Subtitles
}
/// <summary>
- /// Gets the lock.
- /// </summary>
- /// <param name="filename">The filename.</param>
- /// <returns>System.Object.</returns>
- private SemaphoreSlim GetLock(string filename)
- {
- return _semaphoreLocks.GetOrAdd(filename, _ => new SemaphoreSlim(1, 1));
- }
-
- /// <summary>
/// Converts the text subtitle to SRT.
/// </summary>
/// <param name="subtitleStream">The subtitle stream.</param>
@@ -337,21 +306,13 @@ namespace MediaBrowser.MediaEncoding.Subtitles
/// <returns>Task.</returns>
private async Task ConvertTextSubtitleToSrt(MediaStream subtitleStream, MediaSourceInfo mediaSource, string outputPath, CancellationToken cancellationToken)
{
- var semaphore = GetLock(outputPath);
-
- await semaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
-
- try
+ using (await _semaphoreLocks.LockAsync(outputPath, cancellationToken).ConfigureAwait(false))
{
if (!File.Exists(outputPath))
{
await ConvertTextSubtitleToSrtInternal(subtitleStream, mediaSource, outputPath, cancellationToken).ConfigureAwait(false);
}
}
- finally
- {
- semaphore.Release();
- }
}
/// <summary>
@@ -467,6 +428,203 @@ namespace MediaBrowser.MediaEncoding.Subtitles
_logger.LogInformation("ffmpeg subtitle conversion succeeded for {Path}", inputPath);
}
+ private string GetTextSubtitleFormat(MediaStream subtitleStream)
+ {
+ if (string.Equals(subtitleStream.Codec, "ass", StringComparison.OrdinalIgnoreCase)
+ || string.Equals(subtitleStream.Codec, "ssa", StringComparison.OrdinalIgnoreCase))
+ {
+ return subtitleStream.Codec;
+ }
+ else
+ {
+ return "srt";
+ }
+ }
+
+ private bool IsCodecCopyable(string codec)
+ {
+ return string.Equals(codec, "ass", StringComparison.OrdinalIgnoreCase)
+ || string.Equals(codec, "ssa", StringComparison.OrdinalIgnoreCase)
+ || string.Equals(codec, "srt", StringComparison.OrdinalIgnoreCase)
+ || string.Equals(codec, "subrip", StringComparison.OrdinalIgnoreCase);
+ }
+
+ /// <summary>
+ /// Extracts all text subtitles.
+ /// </summary>
+ /// <param name="mediaSource">The mediaSource.</param>
+ /// <param name="cancellationToken">The cancellation token.</param>
+ /// <returns>Task.</returns>
+ private async Task ExtractAllTextSubtitles(MediaSourceInfo mediaSource, CancellationToken cancellationToken)
+ {
+ var locks = new List<AsyncKeyedLockReleaser<string>>();
+ var extractableStreams = new List<MediaStream>();
+
+ try
+ {
+ var subtitleStreams = mediaSource.MediaStreams
+ .Where(stream => stream.IsTextSubtitleStream && stream.SupportsExternalStream);
+
+ foreach (var subtitleStream in subtitleStreams)
+ {
+ var outputPath = GetSubtitleCachePath(mediaSource, subtitleStream.Index, "." + GetTextSubtitleFormat(subtitleStream));
+
+ var @lock = _semaphoreLocks.GetOrAdd(outputPath);
+ await @lock.SemaphoreSlim.WaitAsync(cancellationToken).ConfigureAwait(false);
+
+ if (File.Exists(outputPath))
+ {
+ @lock.Dispose();
+ continue;
+ }
+
+ locks.Add(@lock);
+ extractableStreams.Add(subtitleStream);
+ }
+
+ if (extractableStreams.Count > 0)
+ {
+ await ExtractAllTextSubtitlesInternal(mediaSource, extractableStreams, cancellationToken).ConfigureAwait(false);
+ }
+ }
+ catch (Exception ex)
+ {
+ _logger.LogWarning(ex, "Unable to get streams for File:{File}", mediaSource.Path);
+ }
+ finally
+ {
+ foreach (var @lock in locks)
+ {
+ @lock.Dispose();
+ }
+ }
+ }
+
+ private async Task ExtractAllTextSubtitlesInternal(
+ MediaSourceInfo mediaSource,
+ List<MediaStream> subtitleStreams,
+ CancellationToken cancellationToken)
+ {
+ var inputPath = mediaSource.Path;
+ var outputPaths = new List<string>();
+ var args = string.Format(
+ CultureInfo.InvariantCulture,
+ "-i \"{0}\" -copyts",
+ inputPath);
+
+ foreach (var subtitleStream in subtitleStreams)
+ {
+ var outputPath = GetSubtitleCachePath(mediaSource, subtitleStream.Index, "." + GetTextSubtitleFormat(subtitleStream));
+ var outputCodec = IsCodecCopyable(subtitleStream.Codec) ? "copy" : "srt";
+ var streamIndex = EncodingHelper.FindIndex(mediaSource.MediaStreams, subtitleStream);
+
+ if (streamIndex == -1)
+ {
+ _logger.LogError("Cannot find subtitle stream index for {InputPath} ({Index}), skipping this stream", inputPath, subtitleStream.Index);
+ continue;
+ }
+
+ Directory.CreateDirectory(Path.GetDirectoryName(outputPath) ?? throw new FileNotFoundException($"Calculated path ({outputPath}) is not valid."));
+
+ outputPaths.Add(outputPath);
+ args += string.Format(
+ CultureInfo.InvariantCulture,
+ " -map 0:{0} -an -vn -c:s {1} \"{2}\"",
+ streamIndex,
+ outputCodec,
+ outputPath);
+ }
+
+ int exitCode;
+
+ using (var process = new Process
+ {
+ StartInfo = new ProcessStartInfo
+ {
+ CreateNoWindow = true,
+ UseShellExecute = false,
+ FileName = _mediaEncoder.EncoderPath,
+ Arguments = args,
+ WindowStyle = ProcessWindowStyle.Hidden,
+ ErrorDialog = false
+ },
+ EnableRaisingEvents = true
+ })
+ {
+ _logger.LogInformation("{File} {Arguments}", process.StartInfo.FileName, process.StartInfo.Arguments);
+
+ try
+ {
+ process.Start();
+ }
+ catch (Exception ex)
+ {
+ _logger.LogError(ex, "Error starting ffmpeg");
+
+ throw;
+ }
+
+ try
+ {
+ await process.WaitForExitAsync(TimeSpan.FromMinutes(30)).ConfigureAwait(false);
+ exitCode = process.ExitCode;
+ }
+ catch (OperationCanceledException)
+ {
+ process.Kill(true);
+ exitCode = -1;
+ }
+ }
+
+ var failed = false;
+
+ if (exitCode == -1)
+ {
+ failed = true;
+
+ foreach (var outputPath in outputPaths)
+ {
+ try
+ {
+ _logger.LogWarning("Deleting extracted subtitle due to failure: {Path}", outputPath);
+ _fileSystem.DeleteFile(outputPath);
+ }
+ catch (FileNotFoundException)
+ {
+ }
+ catch (IOException ex)
+ {
+ _logger.LogError(ex, "Error deleting extracted subtitle {Path}", outputPath);
+ }
+ }
+ }
+ else
+ {
+ foreach (var outputPath in outputPaths)
+ {
+ if (!File.Exists(outputPath))
+ {
+ _logger.LogError("ffmpeg subtitle extraction failed for {InputPath} to {OutputPath}", inputPath, outputPath);
+ failed = true;
+ continue;
+ }
+
+ if (outputPath.EndsWith("ass", StringComparison.OrdinalIgnoreCase))
+ {
+ await SetAssFont(outputPath, cancellationToken).ConfigureAwait(false);
+ }
+
+ _logger.LogInformation("ffmpeg subtitle extraction completed for {InputPath} to {OutputPath}", inputPath, outputPath);
+ }
+ }
+
+ if (failed)
+ {
+ throw new FfmpegException(
+ string.Format(CultureInfo.InvariantCulture, "ffmpeg subtitle extraction failed for {0}", inputPath));
+ }
+ }
+
/// <summary>
/// Extracts the text subtitle.
/// </summary>
@@ -484,16 +642,12 @@ namespace MediaBrowser.MediaEncoding.Subtitles
string outputPath,
CancellationToken cancellationToken)
{
- var semaphore = GetLock(outputPath);
-
- await semaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
-
- var subtitleStreamIndex = EncodingHelper.FindIndex(mediaSource.MediaStreams, subtitleStream);
-
- try
+ using (await _semaphoreLocks.LockAsync(outputPath, cancellationToken).ConfigureAwait(false))
{
if (!File.Exists(outputPath))
{
+ var subtitleStreamIndex = EncodingHelper.FindIndex(mediaSource.MediaStreams, subtitleStream);
+
var args = _mediaEncoder.GetInputArgument(mediaSource.Path, mediaSource);
if (subtitleStream.IsExternal)
@@ -509,10 +663,6 @@ namespace MediaBrowser.MediaEncoding.Subtitles
cancellationToken).ConfigureAwait(false);
}
}
- finally
- {
- semaphore.Release();
- }
}
private async Task ExtractTextSubtitleInternal(
@@ -530,7 +680,7 @@ namespace MediaBrowser.MediaEncoding.Subtitles
var processArgs = string.Format(
CultureInfo.InvariantCulture,
- "-i {0} -copyts -map 0:{1} -an -vn -c:s {2} \"{3}\"",
+ "-i \"{0}\" -copyts -map 0:{1} -an -vn -c:s {2} \"{3}\"",
inputPath,
subtitleStreamIndex,
outputCodec,
@@ -728,6 +878,12 @@ namespace MediaBrowser.MediaEncoding.Subtitles
}
}
+ /// <inheritdoc />
+ public void Dispose()
+ {
+ _semaphoreLocks.Dispose();
+ }
+
#pragma warning disable CA1034 // Nested types should not be visible
// Only public for the unit tests
public readonly record struct SubtitleInfo
diff --git a/MediaBrowser.MediaEncoding/Transcoding/TranscodeManager.cs b/MediaBrowser.MediaEncoding/Transcoding/TranscodeManager.cs
index d79e4441a..146b30643 100644
--- a/MediaBrowser.MediaEncoding/Transcoding/TranscodeManager.cs
+++ b/MediaBrowser.MediaEncoding/Transcoding/TranscodeManager.cs
@@ -4,10 +4,12 @@ using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
+using System.Runtime.CompilerServices;
using System.Text;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
+using AsyncKeyedLock;
using Jellyfin.Data.Enums;
using Jellyfin.Extensions;
using MediaBrowser.Common;
@@ -43,7 +45,11 @@ public sealed class TranscodeManager : ITranscodeManager, IDisposable
private readonly IAttachmentExtractor _attachmentExtractor;
private readonly List<TranscodingJob> _activeTranscodingJobs = new();
- private readonly Dictionary<string, SemaphoreSlim> _transcodingLocks = new();
+ private readonly AsyncKeyedLocker<string> _transcodingLocks = new(o =>
+ {
+ o.PoolSize = 20;
+ o.PoolInitialFill = 1;
+ });
/// <summary>
/// Initializes a new instance of the <see cref="TranscodeManager"/> class.
@@ -224,11 +230,6 @@ public sealed class TranscodeManager : ITranscodeManager, IDisposable
}
}
- lock (_transcodingLocks)
- {
- _transcodingLocks.Remove(job.Path!);
- }
-
job.Stop();
if (delete(job.Path!))
@@ -404,7 +405,7 @@ public sealed class TranscodeManager : ITranscodeManager, IDisposable
var user = userId.IsEmpty() ? null : _userManager.GetUserById(userId);
if (user is not null && !user.HasPermission(PermissionKind.EnableVideoPlaybackTranscoding))
{
- this.OnTranscodeFailedToStart(outputPath, transcodingJobType, state);
+ OnTranscodeFailedToStart(outputPath, transcodingJobType, state);
throw new ArgumentException("User does not have access to video transcoding.");
}
@@ -416,7 +417,12 @@ public sealed class TranscodeManager : ITranscodeManager, IDisposable
if (state.SubtitleStream is not null && state.SubtitleDeliveryMethod == SubtitleDeliveryMethod.Encode)
{
var attachmentPath = Path.Combine(_appPaths.CachePath, "attachments", state.MediaSource.Id);
- if (state.VideoType != VideoType.Dvd)
+ if (state.MediaSource.VideoType == VideoType.Dvd || state.MediaSource.VideoType == VideoType.BluRay)
+ {
+ var concatPath = Path.Join(_serverConfigurationManager.GetTranscodePath(), state.MediaSource.Id + ".concat");
+ await _attachmentExtractor.ExtractAllAttachments(concatPath, state.MediaSource, attachmentPath, cancellationTokenSource.Token).ConfigureAwait(false);
+ }
+ else
{
await _attachmentExtractor.ExtractAllAttachments(state.MediaPath, state.MediaSource, attachmentPath, cancellationTokenSource.Token).ConfigureAwait(false);
}
@@ -431,7 +437,7 @@ public sealed class TranscodeManager : ITranscodeManager, IDisposable
}
}
- var process = new Process
+ using var process = new Process
{
StartInfo = new ProcessStartInfo
{
@@ -451,7 +457,7 @@ public sealed class TranscodeManager : ITranscodeManager, IDisposable
EnableRaisingEvents = true
};
- var transcodingJob = this.OnTranscodeBeginning(
+ var transcodingJob = OnTranscodeBeginning(
outputPath,
state.Request.PlaySessionId,
state.MediaSource.LiveStreamId,
@@ -506,7 +512,7 @@ public sealed class TranscodeManager : ITranscodeManager, IDisposable
catch (Exception ex)
{
_logger.LogError(ex, "Error starting FFmpeg");
- this.OnTranscodeFailedToStart(outputPath, transcodingJobType, state);
+ OnTranscodeFailedToStart(outputPath, transcodingJobType, state);
throw;
}
@@ -625,11 +631,6 @@ public sealed class TranscodeManager : ITranscodeManager, IDisposable
}
}
- lock (_transcodingLocks)
- {
- _transcodingLocks.Remove(path);
- }
-
if (!string.IsNullOrWhiteSpace(state.Request.DeviceId))
{
_sessionManager.ClearTranscodingInfo(state.Request.DeviceId);
@@ -705,21 +706,6 @@ public sealed class TranscodeManager : ITranscodeManager, IDisposable
}
}
- /// <inheritdoc />
- public SemaphoreSlim GetTranscodingLock(string outputPath)
- {
- lock (_transcodingLocks)
- {
- if (!_transcodingLocks.TryGetValue(outputPath, out SemaphoreSlim? result))
- {
- result = new SemaphoreSlim(1, 1);
- _transcodingLocks[outputPath] = result;
- }
-
- return result;
- }
- }
-
private void OnPlaybackProgress(object? sender, PlaybackProgressEventArgs e)
{
if (!string.IsNullOrWhiteSpace(e.PlaySessionId))
@@ -742,10 +728,23 @@ public sealed class TranscodeManager : ITranscodeManager, IDisposable
}
}
+ /// <summary>
+ /// Transcoding lock.
+ /// </summary>
+ /// <param name="outputPath">The output path of the transcoded file.</param>
+ /// <param name="cancellationToken">The cancellation token.</param>
+ /// <returns>An <see cref="IDisposable"/>.</returns>
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public ValueTask<IDisposable> LockAsync(string outputPath, CancellationToken cancellationToken)
+ {
+ return _transcodingLocks.LockAsync(outputPath, cancellationToken);
+ }
+
/// <inheritdoc />
public void Dispose()
{
_sessionManager.PlaybackProgress -= OnPlaybackProgress;
_sessionManager.PlaybackStart -= OnPlaybackProgress;
+ _transcodingLocks.Dispose();
}
}
diff --git a/MediaBrowser.Model/ClientLog/ClientLogEvent.cs b/MediaBrowser.Model/ClientLog/ClientLogEvent.cs
deleted file mode 100644
index 21087b564..000000000
--- a/MediaBrowser.Model/ClientLog/ClientLogEvent.cs
+++ /dev/null
@@ -1,75 +0,0 @@
-using System;
-using Microsoft.Extensions.Logging;
-
-namespace MediaBrowser.Model.ClientLog
-{
- /// <summary>
- /// The client log event.
- /// </summary>
- public class ClientLogEvent
- {
- /// <summary>
- /// Initializes a new instance of the <see cref="ClientLogEvent"/> class.
- /// </summary>
- /// <param name="timestamp">The log timestamp.</param>
- /// <param name="level">The log level.</param>
- /// <param name="userId">The user id.</param>
- /// <param name="clientName">The client name.</param>
- /// <param name="clientVersion">The client version.</param>
- /// <param name="deviceId">The device id.</param>
- /// <param name="message">The message.</param>
- public ClientLogEvent(
- DateTime timestamp,
- LogLevel level,
- Guid? userId,
- string clientName,
- string clientVersion,
- string deviceId,
- string message)
- {
- Timestamp = timestamp;
- UserId = userId;
- ClientName = clientName;
- ClientVersion = clientVersion;
- DeviceId = deviceId;
- Message = message;
- Level = level;
- }
-
- /// <summary>
- /// Gets the event timestamp.
- /// </summary>
- public DateTime Timestamp { get; }
-
- /// <summary>
- /// Gets the log level.
- /// </summary>
- public LogLevel Level { get; }
-
- /// <summary>
- /// Gets the user id.
- /// </summary>
- public Guid? UserId { get; }
-
- /// <summary>
- /// Gets the client name.
- /// </summary>
- public string ClientName { get; }
-
- /// <summary>
- /// Gets the client version.
- /// </summary>
- public string ClientVersion { get; }
-
- ///
- /// <summary>
- /// Gets the device id.
- /// </summary>
- public string DeviceId { get; }
-
- /// <summary>
- /// Gets the log message.
- /// </summary>
- public string Message { get; }
- }
-}
diff --git a/MediaBrowser.Model/Dlna/StreamBuilder.cs b/MediaBrowser.Model/Dlna/StreamBuilder.cs
index da683a17e..e6b7f4d9b 100644
--- a/MediaBrowser.Model/Dlna/StreamBuilder.cs
+++ b/MediaBrowser.Model/Dlna/StreamBuilder.cs
@@ -1944,6 +1944,38 @@ namespace MediaBrowser.Model.Dlna
break;
}
+ case ProfileConditionValue.VideoCodecTag:
+ {
+ if (string.IsNullOrEmpty(qualifier))
+ {
+ continue;
+ }
+
+ // change from split by | to comma
+ // strip spaces to avoid having to encode
+ var values = value
+ .Split('|', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
+
+ if (condition.Condition == ProfileConditionType.Equals)
+ {
+ item.SetOption(qualifier, "codectag", string.Join(',', values));
+ }
+ else if (condition.Condition == ProfileConditionType.EqualsAny)
+ {
+ var currentValue = item.GetOption(qualifier, "codectag");
+ if (!string.IsNullOrEmpty(currentValue) && values.Any(v => string.Equals(v, currentValue, StringComparison.OrdinalIgnoreCase)))
+ {
+ item.SetOption(qualifier, "codectag", currentValue);
+ }
+ else
+ {
+ item.SetOption(qualifier, "codectag", string.Join(',', values));
+ }
+ }
+
+ break;
+ }
+
case ProfileConditionValue.Height:
{
if (!enableNonQualifiedConditions)
diff --git a/MediaBrowser.Model/Dto/ImageByNameInfo.cs b/MediaBrowser.Model/Dto/ImageByNameInfo.cs
deleted file mode 100644
index 06cc3e73c..000000000
--- a/MediaBrowser.Model/Dto/ImageByNameInfo.cs
+++ /dev/null
@@ -1,38 +0,0 @@
-#nullable disable
-#pragma warning disable CS1591
-
-namespace MediaBrowser.Model.Dto
-{
- public class ImageByNameInfo
- {
- /// <summary>
- /// Gets or sets the name.
- /// </summary>
- /// <value>The name.</value>
- public string Name { get; set; }
-
- /// <summary>
- /// Gets or sets the theme.
- /// </summary>
- /// <value>The theme.</value>
- public string Theme { get; set; }
-
- /// <summary>
- /// Gets or sets the context.
- /// </summary>
- /// <value>The context.</value>
- public string Context { get; set; }
-
- /// <summary>
- /// Gets or sets the length of the file.
- /// </summary>
- /// <value>The length of the file.</value>
- public long FileLength { get; set; }
-
- /// <summary>
- /// Gets or sets the format.
- /// </summary>
- /// <value>The format.</value>
- public string Format { get; set; }
- }
-}
diff --git a/MediaBrowser.Model/Entities/SpecialFolder.cs b/MediaBrowser.Model/Entities/SpecialFolder.cs
deleted file mode 100644
index 2250c5dff..000000000
--- a/MediaBrowser.Model/Entities/SpecialFolder.cs
+++ /dev/null
@@ -1,36 +0,0 @@
-#pragma warning disable CS1591
-
-namespace MediaBrowser.Model.Entities
-{
- public static class SpecialFolder
- {
- public const string TvShowSeries = "TvShowSeries";
- public const string TvGenres = "TvGenres";
- public const string TvGenre = "TvGenre";
- public const string TvLatest = "TvLatest";
- public const string TvNextUp = "TvNextUp";
- public const string TvResume = "TvResume";
- public const string TvFavoriteSeries = "TvFavoriteSeries";
- public const string TvFavoriteEpisodes = "TvFavoriteEpisodes";
-
- public const string MovieLatest = "MovieLatest";
- public const string MovieResume = "MovieResume";
- public const string MovieMovies = "MovieMovies";
- public const string MovieCollections = "MovieCollections";
- public const string MovieFavorites = "MovieFavorites";
- public const string MovieGenres = "MovieGenres";
- public const string MovieGenre = "MovieGenre";
-
- public const string MusicArtists = "MusicArtists";
- public const string MusicAlbumArtists = "MusicAlbumArtists";
- public const string MusicAlbums = "MusicAlbums";
- public const string MusicGenres = "MusicGenres";
- public const string MusicLatest = "MusicLatest";
- public const string MusicPlaylists = "MusicPlaylists";
- public const string MusicSongs = "MusicSongs";
- public const string MusicFavorites = "MusicFavorites";
- public const string MusicFavoriteArtists = "MusicFavoriteArtists";
- public const string MusicFavoriteAlbums = "MusicFavoriteAlbums";
- public const string MusicFavoriteSongs = "MusicFavoriteSongs";
- }
-}
diff --git a/Jellyfin.Api/Models/LiveTvDtos/ChannelMappingOptionsDto.cs b/MediaBrowser.Model/LiveTv/ChannelMappingOptionsDto.cs
index cbc3548b1..3f9ecc8c8 100644
--- a/Jellyfin.Api/Models/LiveTvDtos/ChannelMappingOptionsDto.cs
+++ b/MediaBrowser.Model/LiveTv/ChannelMappingOptionsDto.cs
@@ -1,9 +1,8 @@
using System;
using System.Collections.Generic;
-using MediaBrowser.Controller.LiveTv;
using MediaBrowser.Model.Dto;
-namespace Jellyfin.Api.Models.LiveTvDtos;
+namespace MediaBrowser.Model.LiveTv;
/// <summary>
/// Channel mapping options dto.
diff --git a/MediaBrowser.Model/LiveTv/TunerChannelMapping.cs b/MediaBrowser.Model/LiveTv/TunerChannelMapping.cs
new file mode 100644
index 000000000..647e24a91
--- /dev/null
+++ b/MediaBrowser.Model/LiveTv/TunerChannelMapping.cs
@@ -0,0 +1,16 @@
+#nullable disable
+
+#pragma warning disable CS1591
+
+namespace MediaBrowser.Model.LiveTv;
+
+public class TunerChannelMapping
+{
+ public string Name { get; set; }
+
+ public string ProviderChannelName { get; set; }
+
+ public string ProviderChannelId { get; set; }
+
+ public string Id { get; set; }
+}
diff --git a/MediaBrowser.Model/Net/MimeTypes.cs b/MediaBrowser.Model/Net/MimeTypes.cs
index 5a1871070..90035f18f 100644
--- a/MediaBrowser.Model/Net/MimeTypes.cs
+++ b/MediaBrowser.Model/Net/MimeTypes.cs
@@ -66,6 +66,11 @@ namespace MediaBrowser.Model.Net
{
// Type application
{ ".azw3", "application/vnd.amazon.ebook" },
+ { ".cb7", "application/x-cb7" },
+ { ".cba", "application/x-cba" },
+ { ".cbr", "application/vnd.comicbook-rar" },
+ { ".cbt", "application/x-cbt" },
+ { ".cbz", "application/vnd.comicbook+zip" },
// Type image
{ ".tbn", "image/jpeg" },
@@ -87,7 +92,7 @@ namespace MediaBrowser.Model.Net
{ ".dsf", "audio/dsf" },
{ ".dsp", "audio/dsp" },
{ ".flac", "audio/flac" },
- { ".m4b", "audio/m4b" },
+ { ".m4b", "audio/mp4" },
{ ".mp3", "audio/mpeg" },
{ ".vorbis", "audio/vorbis" },
{ ".webma", "audio/webm" },
@@ -98,6 +103,12 @@ namespace MediaBrowser.Model.Net
private static readonly Dictionary<string, string> _extensionLookup = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
{
// Type application
+ { "application/vnd.comicbook-rar", ".cbr" },
+ { "application/vnd.comicbook+zip", ".cbz" },
+ { "application/x-cb7", ".cb7" },
+ { "application/x-cba", ".cba" },
+ { "application/x-cbr", ".cbr" },
+ { "application/x-cbt", ".cbt" },
{ "application/x-cbz", ".cbz" },
{ "application/x-javascript", ".js" },
{ "application/xml", ".xml" },
diff --git a/MediaBrowser.Model/Net/SocketReceiveResult.cs b/MediaBrowser.Model/Net/SocketReceiveResult.cs
deleted file mode 100644
index 1524786ea..000000000
--- a/MediaBrowser.Model/Net/SocketReceiveResult.cs
+++ /dev/null
@@ -1,32 +0,0 @@
-#nullable disable
-
-using System.Net;
-
-namespace MediaBrowser.Model.Net
-{
- /// <summary>
- /// Used by the sockets wrapper to hold raw data received from a UDP socket.
- /// </summary>
- public sealed class SocketReceiveResult
- {
- /// <summary>
- /// Gets or sets the buffer to place received data into.
- /// </summary>
- public byte[] Buffer { get; set; }
-
- /// <summary>
- /// Gets or sets the number of bytes received.
- /// </summary>
- public int ReceivedBytes { get; set; }
-
- /// <summary>
- /// Gets or sets the <see cref="IPEndPoint"/> the data was received from.
- /// </summary>
- public IPEndPoint RemoteEndPoint { get; set; }
-
- /// <summary>
- /// Gets or sets the local <see cref="IPAddress"/>.
- /// </summary>
- public IPAddress LocalIPAddress { get; set; }
- }
-}
diff --git a/MediaBrowser.Model/Session/ClientCapabilities.cs b/MediaBrowser.Model/Session/ClientCapabilities.cs
index 597845fc1..5f51fb21c 100644
--- a/MediaBrowser.Model/Session/ClientCapabilities.cs
+++ b/MediaBrowser.Model/Session/ClientCapabilities.cs
@@ -3,6 +3,7 @@
using System;
using System.Collections.Generic;
+using System.ComponentModel;
using Jellyfin.Data.Enums;
using MediaBrowser.Model.Dlna;
@@ -30,5 +31,15 @@ namespace MediaBrowser.Model.Session
public string AppStoreUrl { get; set; }
public string IconUrl { get; set; }
+
+ // TODO: Remove after 10.9
+ [Obsolete("Unused")]
+ [DefaultValue(false)]
+ public bool? SupportsContentUploading { get; set; }
+
+ // TODO: Remove after 10.9
+ [Obsolete("Unused")]
+ [DefaultValue(false)]
+ public bool? SupportsSync { get; set; }
}
}
diff --git a/MediaBrowser.Model/Session/HardwareEncodingType.cs b/MediaBrowser.Model/Session/HardwareEncodingType.cs
index f5753467a..058875cd3 100644
--- a/MediaBrowser.Model/Session/HardwareEncodingType.cs
+++ b/MediaBrowser.Model/Session/HardwareEncodingType.cs
@@ -33,6 +33,11 @@
/// <summary>
/// Video ToolBox.
/// </summary>
- VideoToolBox = 5
+ VideoToolBox = 5,
+
+ /// <summary>
+ /// Rockchip Media Process Platform (RKMPP).
+ /// </summary>
+ RKMPP = 6
}
}
diff --git a/MediaBrowser.Model/System/SystemInfo.cs b/MediaBrowser.Model/System/SystemInfo.cs
index aa7c03ebd..f37ac6a14 100644
--- a/MediaBrowser.Model/System/SystemInfo.cs
+++ b/MediaBrowser.Model/System/SystemInfo.cs
@@ -3,30 +3,12 @@
using System;
using System.Collections.Generic;
-using System.Runtime.InteropServices;
+using System.ComponentModel;
using MediaBrowser.Model.Updates;
namespace MediaBrowser.Model.System
{
/// <summary>
- /// Enum describing the location of the FFmpeg tool.
- /// </summary>
- public enum FFmpegLocation
- {
- /// <summary>No path to FFmpeg found.</summary>
- NotFound,
-
- /// <summary>Path supplied via command line using switch --ffmpeg.</summary>
- SetByArgument,
-
- /// <summary>User has supplied path via Transcoding UI page.</summary>
- Custom,
-
- /// <summary>FFmpeg tool found on system $PATH.</summary>
- System
- }
-
- /// <summary>
/// Class SystemInfo.
/// </summary>
public class SystemInfo : PublicSystemInfo
@@ -83,9 +65,11 @@ namespace MediaBrowser.Model.System
/// </summary>
/// <value><c>true</c>.</value>
[Obsolete("This is always true")]
+ [DefaultValue(true)]
public bool CanSelfRestart { get; set; } = true;
[Obsolete("This is always false")]
+ [DefaultValue(false)]
public bool CanLaunchWebBrowser { get; set; } = false;
/// <summary>
@@ -140,12 +124,15 @@ namespace MediaBrowser.Model.System
/// </summary>
/// <value><c>true</c> if this instance has update available; otherwise, <c>false</c>.</value>
[Obsolete("This should be handled by the package manager")]
+ [DefaultValue(false)]
public bool HasUpdateAvailable { get; set; }
[Obsolete("This isn't set correctly anymore")]
- public FFmpegLocation EncoderLocation { get; set; }
+ [DefaultValue("System")]
+ public string EncoderLocation { get; set; } = "System";
[Obsolete("This is no longer set")]
- public Architecture SystemArchitecture { get; set; } = Architecture.X64;
+ [DefaultValue("X64")]
+ public string SystemArchitecture { get; set; } = "X64";
}
}
diff --git a/MediaBrowser.Providers/Manager/ProviderManager.cs b/MediaBrowser.Providers/Manager/ProviderManager.cs
index b530b9de3..2e9547bf3 100644
--- a/MediaBrowser.Providers/Manager/ProviderManager.cs
+++ b/MediaBrowser.Providers/Manager/ProviderManager.cs
@@ -13,7 +13,6 @@ using Jellyfin.Data.Enums;
using Jellyfin.Data.Events;
using Jellyfin.Extensions;
using MediaBrowser.Common.Net;
-using MediaBrowser.Common.Progress;
using MediaBrowser.Controller;
using MediaBrowser.Controller.BaseItemManager;
using MediaBrowser.Controller.Configuration;
@@ -1025,7 +1024,7 @@ namespace MediaBrowser.Providers.Manager
await RefreshCollectionFolderChildren(options, collectionFolder, cancellationToken).ConfigureAwait(false);
break;
case Folder folder:
- await folder.ValidateChildren(new SimpleProgress<double>(), options, cancellationToken: cancellationToken).ConfigureAwait(false);
+ await folder.ValidateChildren(new Progress<double>(), options, cancellationToken: cancellationToken).ConfigureAwait(false);
break;
}
}
@@ -1036,7 +1035,7 @@ namespace MediaBrowser.Providers.Manager
{
await child.RefreshMetadata(options, cancellationToken).ConfigureAwait(false);
- await child.ValidateChildren(new SimpleProgress<double>(), options, cancellationToken: cancellationToken).ConfigureAwait(false);
+ await child.ValidateChildren(new Progress<double>(), options, cancellationToken: cancellationToken).ConfigureAwait(false);
}
}
@@ -1058,7 +1057,7 @@ namespace MediaBrowser.Providers.Manager
.Select(i => i.MusicArtist)
.Where(i => i is not null);
- var musicArtistRefreshTasks = musicArtists.Select(i => i.ValidateChildren(new SimpleProgress<double>(), options, true, cancellationToken));
+ var musicArtistRefreshTasks = musicArtists.Select(i => i.ValidateChildren(new Progress<double>(), options, true, cancellationToken));
await Task.WhenAll(musicArtistRefreshTasks).ConfigureAwait(false);
diff --git a/MediaBrowser.XbmcMetadata/EntryPoint.cs b/MediaBrowser.XbmcMetadata/EntryPoint.cs
deleted file mode 100644
index a6216ef30..000000000
--- a/MediaBrowser.XbmcMetadata/EntryPoint.cs
+++ /dev/null
@@ -1,78 +0,0 @@
-#pragma warning disable CS1591
-
-using System;
-using System.Threading.Tasks;
-using MediaBrowser.Common.Configuration;
-using MediaBrowser.Controller.Entities;
-using MediaBrowser.Controller.Library;
-using MediaBrowser.Controller.Plugins;
-using MediaBrowser.Controller.Providers;
-using MediaBrowser.Model.Entities;
-using MediaBrowser.XbmcMetadata.Configuration;
-using MediaBrowser.XbmcMetadata.Savers;
-using Microsoft.Extensions.Logging;
-
-namespace MediaBrowser.XbmcMetadata
-{
- public sealed class EntryPoint : IServerEntryPoint
- {
- private readonly IUserDataManager _userDataManager;
- private readonly ILogger<EntryPoint> _logger;
- private readonly IProviderManager _providerManager;
- private readonly IConfigurationManager _config;
-
- public EntryPoint(
- IUserDataManager userDataManager,
- ILogger<EntryPoint> logger,
- IProviderManager providerManager,
- IConfigurationManager config)
- {
- _userDataManager = userDataManager;
- _logger = logger;
- _providerManager = providerManager;
- _config = config;
- }
-
- /// <inheritdoc />
- public Task RunAsync()
- {
- _userDataManager.UserDataSaved += OnUserDataSaved;
-
- return Task.CompletedTask;
- }
-
- private void OnUserDataSaved(object? sender, UserDataSaveEventArgs e)
- {
- if (e.SaveReason == UserDataSaveReason.PlaybackFinished || e.SaveReason == UserDataSaveReason.TogglePlayed || e.SaveReason == UserDataSaveReason.UpdateUserRating)
- {
- if (!string.IsNullOrWhiteSpace(_config.GetNfoConfiguration().UserId))
- {
- _ = SaveMetadataForItemAsync(e.Item, ItemUpdateType.MetadataDownload);
- }
- }
- }
-
- /// <inheritdoc />
- public void Dispose()
- {
- _userDataManager.UserDataSaved -= OnUserDataSaved;
- }
-
- private async Task SaveMetadataForItemAsync(BaseItem item, ItemUpdateType updateReason)
- {
- if (!item.IsFileProtocol || !item.SupportsLocalMetadata)
- {
- return;
- }
-
- try
- {
- await _providerManager.SaveMetadataAsync(item, updateReason, new[] { BaseNfoSaver.SaverName }).ConfigureAwait(false);
- }
- catch (Exception ex)
- {
- _logger.LogError(ex, "Error saving metadata for {Path}", item.Path ?? item.Name);
- }
- }
- }
-}
diff --git a/MediaBrowser.XbmcMetadata/NfoUserDataSaver.cs b/MediaBrowser.XbmcMetadata/NfoUserDataSaver.cs
new file mode 100644
index 000000000..b2882194d
--- /dev/null
+++ b/MediaBrowser.XbmcMetadata/NfoUserDataSaver.cs
@@ -0,0 +1,87 @@
+using System;
+using System.Threading;
+using System.Threading.Tasks;
+using MediaBrowser.Common.Configuration;
+using MediaBrowser.Controller.Library;
+using MediaBrowser.Controller.Providers;
+using MediaBrowser.Model.Entities;
+using MediaBrowser.XbmcMetadata.Configuration;
+using MediaBrowser.XbmcMetadata.Savers;
+using Microsoft.Extensions.Hosting;
+using Microsoft.Extensions.Logging;
+
+namespace MediaBrowser.XbmcMetadata;
+
+/// <summary>
+/// <see cref="IHostedService"/> responsible for updating NFO files' user data.
+/// </summary>
+public sealed class NfoUserDataSaver : IHostedService
+{
+ private readonly ILogger<NfoUserDataSaver> _logger;
+ private readonly IConfigurationManager _config;
+ private readonly IUserDataManager _userDataManager;
+ private readonly IProviderManager _providerManager;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="NfoUserDataSaver"/> class.
+ /// </summary>
+ /// <param name="logger">The <see cref="ILogger"/>.</param>
+ /// <param name="config">The <see cref="IConfigurationManager"/>.</param>
+ /// <param name="userDataManager">The <see cref="IUserDataManager"/>.</param>
+ /// <param name="providerManager">The <see cref="IProviderManager"/>.</param>
+ public NfoUserDataSaver(
+ ILogger<NfoUserDataSaver> logger,
+ IConfigurationManager config,
+ IUserDataManager userDataManager,
+ IProviderManager providerManager)
+ {
+ _logger = logger;
+ _config = config;
+ _userDataManager = userDataManager;
+ _providerManager = providerManager;
+ }
+
+ /// <inheritdoc />
+ public Task StartAsync(CancellationToken cancellationToken)
+ {
+ _userDataManager.UserDataSaved += OnUserDataSaved;
+ return Task.CompletedTask;
+ }
+
+ /// <inheritdoc />
+ public Task StopAsync(CancellationToken cancellationToken)
+ {
+ _userDataManager.UserDataSaved -= OnUserDataSaved;
+ return Task.CompletedTask;
+ }
+
+ private async void OnUserDataSaved(object? sender, UserDataSaveEventArgs e)
+ {
+ if (e.SaveReason is not (UserDataSaveReason.PlaybackFinished
+ or UserDataSaveReason.TogglePlayed or UserDataSaveReason.UpdateUserRating))
+ {
+ return;
+ }
+
+ if (string.IsNullOrWhiteSpace(_config.GetNfoConfiguration().UserId))
+ {
+ return;
+ }
+
+ var item = e.Item;
+ if (!item.IsFileProtocol || !item.SupportsLocalMetadata)
+ {
+ return;
+ }
+
+ try
+ {
+ await _providerManager.SaveMetadataAsync(item, ItemUpdateType.MetadataDownload, [BaseNfoSaver.SaverName])
+ .ConfigureAwait(false);
+ }
+ catch (Exception ex)
+ {
+ _logger.LogError(ex, "Error saving metadata for {Path}", item.Path ?? item.Name);
+ }
+ }
+}
diff --git a/MediaBrowser.XbmcMetadata/Parsers/BaseNfoParser.cs b/MediaBrowser.XbmcMetadata/Parsers/BaseNfoParser.cs
index 70e5b66c1..97cdc6854 100644
--- a/MediaBrowser.XbmcMetadata/Parsers/BaseNfoParser.cs
+++ b/MediaBrowser.XbmcMetadata/Parsers/BaseNfoParser.cs
@@ -460,10 +460,28 @@ namespace MediaBrowser.XbmcMetadata.Parsers
var trailer = reader.ReadNormalizedString();
if (!string.IsNullOrEmpty(trailer))
{
- item.AddTrailerUrl(trailer.Replace(
- "plugin://plugin.video.youtube/?action=play_video&videoid=",
- BaseNfoSaver.YouTubeWatchUrl,
- StringComparison.OrdinalIgnoreCase));
+ if (trailer.StartsWith("plugin://plugin.video.youtube/?action=play_video&videoid=", StringComparison.OrdinalIgnoreCase))
+ {
+ // Deprecated format
+ item.AddTrailerUrl(trailer.Replace(
+ "plugin://plugin.video.youtube/?action=play_video&videoid=",
+ BaseNfoSaver.YouTubeWatchUrl,
+ StringComparison.OrdinalIgnoreCase));
+
+ var suggestedUrl = trailer.Replace(
+ "plugin://plugin.video.youtube/?action=play_video&videoid=",
+ "plugin://plugin.video.youtube/play/?video_id=",
+ StringComparison.OrdinalIgnoreCase);
+ Logger.LogWarning("Trailer URL uses a deprecated format : {Url}. Using {NewUrl} instead is advised.", trailer, suggestedUrl);
+ }
+ else if (trailer.StartsWith("plugin://plugin.video.youtube/play/?video_id=", StringComparison.OrdinalIgnoreCase))
+ {
+ // Proper format
+ item.AddTrailerUrl(trailer.Replace(
+ "plugin://plugin.video.youtube/play/?video_id=",
+ BaseNfoSaver.YouTubeWatchUrl,
+ StringComparison.OrdinalIgnoreCase));
+ }
}
break;
diff --git a/README.md b/README.md
index 62ef21334..ec065f260 100644
--- a/README.md
+++ b/README.md
@@ -142,17 +142,36 @@ cd Jellyfin.Server/bin/Debug/net8.0 # Change into the build output directory
2. Execute the build output. On Linux, Mac, etc. use `./jellyfin` and on Windows use `jellyfin.exe`.
+#### Accessing the Hosted Web Client
+
+If the Server is configured to host the Web Client, and the Server is running, the Web Client can be accessed at `http://localhost:8096` by default.
+
+API documentation can be viewed at `http://localhost:8096/api-docs/swagger/index.html`
+
+
### Running from GH-Codespaces
As Jellyfin will run on a container on a github hosted server, JF needs to handle some things differently.
-**NOTE:** If you want to access the JF instance from outside, like with a WebClient on another PC, remember to set the "ports" in the lower VsCode window to public.
-#### FFmpeg installation.
-Because sometimes you need FFMPEG to test certain cases, follow the instructions from the wiki on the dev enviorment:
-https://jellyfin.org/docs/general/installation/linux/#ffmpeg-installation
+**NOTE:** Depending on the selected configuration (if you just click 'create codespace' it will create a default configuration one) it might take 20-30 secounds to load all extensions and prepare the enviorment while vscode is already open. Just give it some time and wait until you see `Downloading .NET version(s) 7.0.15~x64 ...... Done!` in the output tab.
+
+**NOTE:** If you want to access the JF instance from outside, like with a WebClient on another PC, remember to set the "ports" in the lower VsCode window to public.
**NOTE:** When first opening the server instance with any WebUI, you will be send to the login instead of the setup page. Refresh the login page once and you should be redirected to the Setup.
+There are two configurations for you to chose from.
+#### Default - Development Jellyfin Server
+This creates a container that has everything to run and debug the Jellyfin Media server but does not setup anything else. Each time you create a new container you have to run though the whole setup again. There is also no ffmpeg, webclient or media preloaded. Use the `.NET Launch (nowebclient)` lunch config to start the server.
+
+> Keep in mind that as this has no web client you have to connect to it via an extenal client. This can be just another codespace container running the WebUI. vuejs does not work from the getgo as it does not support the setup steps.
+
+#### Development Jellyfin Server ffmpeg
+this extens the default server with an default installation of ffmpeg6 though the means described here: https://jellyfin.org/docs/general/installation/linux#repository-manual
+If you want to install a specific ffmpeg version, follow the comments embedded in the `.devcontainer/Dev - Server Ffmpeg/install.ffmpeg.sh` file.
+
+Use the `ghcs .NET Launch (nowebclient, ffmpeg)` launch config to run with the jellyfin-ffmpeg enabled.
+
+
### Running The Tests
This repository also includes unit tests that are used to validate functionality as part of a CI pipeline on Azure. There are several ways to run these tests.
diff --git a/deployment/Dockerfile.centos.amd64 b/deployment/Dockerfile.centos.amd64
index af309b083..6bd7d312c 100644
--- a/deployment/Dockerfile.centos.amd64
+++ b/deployment/Dockerfile.centos.amd64
@@ -20,7 +20,7 @@ RUN dnf update -yq \
&& rm -rf /var/cache/dnf
# Install DotNET SDK
-RUN wget -q https://download.visualstudio.microsoft.com/download/pr/5226a5fa-8c0b-474f-b79a-8984ad7c5beb/3113ccbf789c9fd29972835f0f334b7a/dotnet-sdk-8.0.100-linux-x64.tar.gz -O dotnet-sdk.tar.gz \
+RUN wget -q https://download.visualstudio.microsoft.com/download/pr/85bcc525-4e9c-471e-9c1d-96259aa1a315/930833ef34f66fe9ee2643b0ba21621a/dotnet-sdk-8.0.201-linux-x64.tar.gz -O dotnet-sdk.tar.gz \
&& mkdir -p dotnet-sdk \
&& tar -xzf dotnet-sdk.tar.gz -C dotnet-sdk \
&& ln -s $( pwd )/dotnet-sdk/dotnet /usr/bin/dotnet
diff --git a/deployment/Dockerfile.fedora.amd64 b/deployment/Dockerfile.fedora.amd64
index 75a6d1e64..f1dc492de 100644
--- a/deployment/Dockerfile.fedora.amd64
+++ b/deployment/Dockerfile.fedora.amd64
@@ -20,7 +20,7 @@ RUN dnf update -yq \
&& rm -rf /var/cache/dnf
# Install DotNET SDK
-RUN wget -q https://download.visualstudio.microsoft.com/download/pr/5226a5fa-8c0b-474f-b79a-8984ad7c5beb/3113ccbf789c9fd29972835f0f334b7a/dotnet-sdk-8.0.100-linux-x64.tar.gz -O dotnet-sdk.tar.gz \
+RUN wget -q https://download.visualstudio.microsoft.com/download/pr/85bcc525-4e9c-471e-9c1d-96259aa1a315/930833ef34f66fe9ee2643b0ba21621a/dotnet-sdk-8.0.201-linux-x64.tar.gz -O dotnet-sdk.tar.gz \
&& mkdir -p dotnet-sdk \
&& tar -xzf dotnet-sdk.tar.gz -C dotnet-sdk \
&& ln -s $( pwd )/dotnet-sdk/dotnet /usr/bin/dotnet
diff --git a/src/Jellyfin.Drawing.Skia/SkiaCodecException.cs b/src/Jellyfin.Drawing.Skia/SkiaCodecException.cs
deleted file mode 100644
index 581fa000d..000000000
--- a/src/Jellyfin.Drawing.Skia/SkiaCodecException.cs
+++ /dev/null
@@ -1,44 +0,0 @@
-using System.Globalization;
-using SkiaSharp;
-
-namespace Jellyfin.Drawing.Skia;
-
-/// <summary>
-/// Represents errors that occur during interaction with Skia codecs.
-/// </summary>
-public class SkiaCodecException : SkiaException
-{
- /// <summary>
- /// Initializes a new instance of the <see cref="SkiaCodecException" /> class.
- /// </summary>
- /// <param name="result">The non-successful codec result returned by Skia.</param>
- public SkiaCodecException(SKCodecResult result)
- {
- CodecResult = result;
- }
-
- /// <summary>
- /// Initializes a new instance of the <see cref="SkiaCodecException" /> class
- /// with a specified error message.
- /// </summary>
- /// <param name="result">The non-successful codec result returned by Skia.</param>
- /// <param name="message">The message that describes the error.</param>
- public SkiaCodecException(SKCodecResult result, string message)
- : base(message)
- {
- CodecResult = result;
- }
-
- /// <summary>
- /// Gets the non-successful codec result returned by Skia.
- /// </summary>
- public SKCodecResult CodecResult { get; }
-
- /// <inheritdoc />
- public override string ToString()
- => string.Format(
- CultureInfo.InvariantCulture,
- "Non-success codec result: {0}\n{1}",
- CodecResult,
- base.ToString());
-}
diff --git a/src/Jellyfin.Drawing.Skia/SkiaEncoder.cs b/src/Jellyfin.Drawing.Skia/SkiaEncoder.cs
index 5721e2882..4ae5a9a48 100644
--- a/src/Jellyfin.Drawing.Skia/SkiaEncoder.cs
+++ b/src/Jellyfin.Drawing.Skia/SkiaEncoder.cs
@@ -182,7 +182,6 @@ public class SkiaEncoder : IImageEncoder
/// <inheritdoc />
/// <exception cref="ArgumentNullException">The path is null.</exception>
/// <exception cref="FileNotFoundException">The path is not valid.</exception>
- /// <exception cref="SkiaCodecException">The file at the specified path could not be used to generate a codec.</exception>
public string GetImageBlurHash(int xComp, int yComp, string path)
{
ArgumentException.ThrowIfNullOrEmpty(path);
diff --git a/src/Jellyfin.Drawing.Skia/SkiaException.cs b/src/Jellyfin.Drawing.Skia/SkiaException.cs
deleted file mode 100644
index d0e69d42c..000000000
--- a/src/Jellyfin.Drawing.Skia/SkiaException.cs
+++ /dev/null
@@ -1,38 +0,0 @@
-using System;
-
-namespace Jellyfin.Drawing.Skia;
-
-/// <summary>
-/// Represents errors that occur during interaction with Skia.
-/// </summary>
-public class SkiaException : Exception
-{
- /// <summary>
- /// Initializes a new instance of the <see cref="SkiaException"/> class.
- /// </summary>
- public SkiaException()
- {
- }
-
- /// <summary>
- /// Initializes a new instance of the <see cref="SkiaException"/> class with a specified error message.
- /// </summary>
- /// <param name="message">The message that describes the error.</param>
- public SkiaException(string message) : base(message)
- {
- }
-
- /// <summary>
- /// Initializes a new instance of the <see cref="SkiaException"/> class with a specified error message and a
- /// reference to the inner exception that is the cause of this exception.
- /// </summary>
- /// <param name="message">The error message that explains the reason for the exception.</param>
- /// <param name="innerException">
- /// The exception that is the cause of the current exception, or a null reference (Nothing in Visual Basic) if
- /// no inner exception is specified.
- /// </param>
- public SkiaException(string message, Exception innerException)
- : base(message, innerException)
- {
- }
-}
diff --git a/src/Jellyfin.Drawing/ImageProcessor.cs b/src/Jellyfin.Drawing/ImageProcessor.cs
index 65a8f4e83..213328a39 100644
--- a/src/Jellyfin.Drawing/ImageProcessor.cs
+++ b/src/Jellyfin.Drawing/ImageProcessor.cs
@@ -7,6 +7,7 @@ using System.Net.Mime;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
+using AsyncKeyedLock;
using Jellyfin.Data.Entities;
using MediaBrowser.Common.Extensions;
using MediaBrowser.Controller;
@@ -38,7 +39,7 @@ public sealed class ImageProcessor : IImageProcessor, IDisposable
private readonly IServerApplicationPaths _appPaths;
private readonly IImageEncoder _imageEncoder;
- private readonly SemaphoreSlim _parallelEncodingLimit;
+ private readonly AsyncNonKeyedLocker _parallelEncodingLimit;
private bool _disposed;
@@ -68,7 +69,7 @@ public sealed class ImageProcessor : IImageProcessor, IDisposable
semaphoreCount = 2 * Environment.ProcessorCount;
}
- _parallelEncodingLimit = new(semaphoreCount, semaphoreCount);
+ _parallelEncodingLimit = new(semaphoreCount);
}
private string ResizedImageCachePath => Path.Combine(_appPaths.ImageCachePath, "resized-images");
@@ -193,18 +194,13 @@ public sealed class ImageProcessor : IImageProcessor, IDisposable
{
if (!File.Exists(cacheFilePath))
{
- // Limit number of parallel (more precisely: concurrent) image encodings to prevent a high memory usage
- await _parallelEncodingLimit.WaitAsync().ConfigureAwait(false);
-
string resultPath;
- try
+
+ // Limit number of parallel (more precisely: concurrent) image encodings to prevent a high memory usage
+ using (await _parallelEncodingLimit.LockAsync().ConfigureAwait(false))
{
resultPath = _imageEncoder.EncodeImage(originalImagePath, dateModified, cacheFilePath, autoOrient, orientation, quality, options, outputFormat);
}
- finally
- {
- _parallelEncodingLimit.Release();
- }
if (string.Equals(resultPath, originalImagePath, StringComparison.OrdinalIgnoreCase))
{
diff --git a/src/Jellyfin.Drawing/Jellyfin.Drawing.csproj b/src/Jellyfin.Drawing/Jellyfin.Drawing.csproj
index 23c4c0a9a..4a02f90f9 100644
--- a/src/Jellyfin.Drawing/Jellyfin.Drawing.csproj
+++ b/src/Jellyfin.Drawing/Jellyfin.Drawing.csproj
@@ -21,4 +21,8 @@
<Compile Include="..\..\SharedVersion.cs" />
</ItemGroup>
+ <ItemGroup>
+ <PackageReference Include="AsyncKeyedLock" />
+ </ItemGroup>
+
</Project>
diff --git a/src/Jellyfin.LiveTv/Channels/ChannelManager.cs b/src/Jellyfin.LiveTv/Channels/ChannelManager.cs
index bc968f8ee..1948a9ab9 100644
--- a/src/Jellyfin.LiveTv/Channels/ChannelManager.cs
+++ b/src/Jellyfin.LiveTv/Channels/ChannelManager.cs
@@ -8,12 +8,12 @@ using System.Linq;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
+using AsyncKeyedLock;
using Jellyfin.Data.Entities;
using Jellyfin.Data.Enums;
using Jellyfin.Extensions;
using Jellyfin.Extensions.Json;
using MediaBrowser.Common.Extensions;
-using MediaBrowser.Common.Progress;
using MediaBrowser.Controller.Channels;
using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Dto;
@@ -50,7 +50,7 @@ namespace Jellyfin.LiveTv.Channels
private readonly IFileSystem _fileSystem;
private readonly IProviderManager _providerManager;
private readonly IMemoryCache _memoryCache;
- private readonly SemaphoreSlim _resourcePool = new SemaphoreSlim(1, 1);
+ private readonly AsyncNonKeyedLocker _resourcePool = new(1);
private readonly JsonSerializerOptions _jsonOptions = JsonDefaults.Options;
private bool _disposed = false;
@@ -667,7 +667,7 @@ namespace Jellyfin.LiveTv.Channels
ChannelIds = new Guid[] { internalChannel.Id }
};
- var result = await GetChannelItemsInternal(query, new SimpleProgress<double>(), cancellationToken).ConfigureAwait(false);
+ var result = await GetChannelItemsInternal(query, new Progress<double>(), cancellationToken).ConfigureAwait(false);
foreach (var item in result.Items)
{
@@ -680,7 +680,7 @@ namespace Jellyfin.LiveTv.Channels
EnableTotalRecordCount = false,
ChannelIds = new Guid[] { internalChannel.Id }
},
- new SimpleProgress<double>(),
+ new Progress<double>(),
cancellationToken).ConfigureAwait(false);
}
}
@@ -762,7 +762,7 @@ namespace Jellyfin.LiveTv.Channels
/// <inheritdoc />
public async Task<QueryResult<BaseItemDto>> GetChannelItems(InternalItemsQuery query, CancellationToken cancellationToken)
{
- var internalResult = await GetChannelItemsInternal(query, new SimpleProgress<double>(), cancellationToken).ConfigureAwait(false);
+ var internalResult = await GetChannelItemsInternal(query, new Progress<double>(), cancellationToken).ConfigureAwait(false);
var returnItems = _dtoService.GetBaseItemDtos(internalResult.Items, query.DtoOptions, query.User);
@@ -811,9 +811,7 @@ namespace Jellyfin.LiveTv.Channels
{
}
- await _resourcePool.WaitAsync(cancellationToken).ConfigureAwait(false);
-
- try
+ using (await _resourcePool.LockAsync(cancellationToken).ConfigureAwait(false))
{
try
{
@@ -860,10 +858,6 @@ namespace Jellyfin.LiveTv.Channels
return result;
}
- finally
- {
- _resourcePool.Release();
- }
}
private async Task CacheResponse(ChannelItemResult result, string path)
diff --git a/src/Jellyfin.LiveTv/Channels/RefreshChannelsScheduledTask.cs b/src/Jellyfin.LiveTv/Channels/RefreshChannelsScheduledTask.cs
index 556e052d4..79c5873d5 100644
--- a/src/Jellyfin.LiveTv/Channels/RefreshChannelsScheduledTask.cs
+++ b/src/Jellyfin.LiveTv/Channels/RefreshChannelsScheduledTask.cs
@@ -2,7 +2,6 @@ using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
-using MediaBrowser.Common.Progress;
using MediaBrowser.Controller.Channels;
using MediaBrowser.Controller.Library;
using MediaBrowser.Model.Globalization;
@@ -66,7 +65,7 @@ namespace Jellyfin.LiveTv.Channels
{
var manager = (ChannelManager)_channelManager;
- await manager.RefreshChannels(new SimpleProgress<double>(), cancellationToken).ConfigureAwait(false);
+ await manager.RefreshChannels(new Progress<double>(), cancellationToken).ConfigureAwait(false);
await new ChannelPostScanTask(_channelManager, _logger, _libraryManager).Run(progress, cancellationToken)
.ConfigureAwait(false);
diff --git a/src/Jellyfin.LiveTv/EmbyTV/EmbyTV.cs b/src/Jellyfin.LiveTv/EmbyTV/EmbyTV.cs
index e7e927b2d..e19d2c591 100644
--- a/src/Jellyfin.LiveTv/EmbyTV/EmbyTV.cs
+++ b/src/Jellyfin.LiveTv/EmbyTV/EmbyTV.cs
@@ -14,13 +14,13 @@ using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Xml;
+using AsyncKeyedLock;
using Jellyfin.Data.Enums;
using Jellyfin.Data.Events;
using Jellyfin.Extensions;
using Jellyfin.LiveTv.Configuration;
using MediaBrowser.Common.Configuration;
using MediaBrowser.Common.Extensions;
-using MediaBrowser.Common.Progress;
using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Dto;
using MediaBrowser.Controller.Entities;
@@ -51,7 +51,6 @@ namespace Jellyfin.LiveTv.EmbyTV
private readonly ItemDataProvider<SeriesTimerInfo> _seriesTimerProvider;
private readonly TimerManager _timerProvider;
- private readonly LiveTvManager _liveTvManager;
private readonly ITunerHostManager _tunerHostManager;
private readonly IFileSystem _fileSystem;
@@ -61,14 +60,13 @@ namespace Jellyfin.LiveTv.EmbyTV
private readonly IMediaEncoder _mediaEncoder;
private readonly IMediaSourceManager _mediaSourceManager;
private readonly IStreamHelper _streamHelper;
+ private readonly LiveTvDtoService _tvDtoService;
+ private readonly IListingsManager _listingsManager;
private readonly ConcurrentDictionary<string, ActiveRecordingInfo> _activeRecordings =
new ConcurrentDictionary<string, ActiveRecordingInfo>(StringComparer.OrdinalIgnoreCase);
- private readonly ConcurrentDictionary<string, EpgChannelData> _epgChannels =
- new ConcurrentDictionary<string, EpgChannelData>(StringComparer.OrdinalIgnoreCase);
-
- private readonly SemaphoreSlim _recordingDeleteSemaphore = new SemaphoreSlim(1, 1);
+ private readonly AsyncNonKeyedLocker _recordingDeleteSemaphore = new(1);
private bool _disposed;
@@ -78,13 +76,14 @@ namespace Jellyfin.LiveTv.EmbyTV
ILogger<EmbyTV> logger,
IHttpClientFactory httpClientFactory,
IServerConfigurationManager config,
- ILiveTvManager liveTvManager,
ITunerHostManager tunerHostManager,
IFileSystem fileSystem,
ILibraryManager libraryManager,
ILibraryMonitor libraryMonitor,
IProviderManager providerManager,
- IMediaEncoder mediaEncoder)
+ IMediaEncoder mediaEncoder,
+ LiveTvDtoService tvDtoService,
+ IListingsManager listingsManager)
{
Current = this;
@@ -96,10 +95,11 @@ namespace Jellyfin.LiveTv.EmbyTV
_libraryMonitor = libraryMonitor;
_providerManager = providerManager;
_mediaEncoder = mediaEncoder;
- _liveTvManager = (LiveTvManager)liveTvManager;
+ _tvDtoService = tvDtoService;
_tunerHostManager = tunerHostManager;
_mediaSourceManager = mediaSourceManager;
_streamHelper = streamHelper;
+ _listingsManager = listingsManager;
_seriesTimerProvider = new SeriesTimerManager(_logger, Path.Combine(DataPath, "seriestimers.json"));
_timerProvider = new TimerManager(_logger, Path.Combine(DataPath, "timers.json"));
@@ -257,7 +257,7 @@ namespace Jellyfin.LiveTv.EmbyTV
if (requiresRefresh)
{
- await _libraryManager.ValidateMediaLibrary(new SimpleProgress<double>(), CancellationToken.None).ConfigureAwait(false);
+ await _libraryManager.ValidateMediaLibrary(new Progress<double>(), CancellationToken.None).ConfigureAwait(false);
}
}
@@ -309,15 +309,15 @@ namespace Jellyfin.LiveTv.EmbyTV
private async Task<IEnumerable<ChannelInfo>> GetChannelsAsync(bool enableCache, CancellationToken cancellationToken)
{
- var list = new List<ChannelInfo>();
+ var channels = new List<ChannelInfo>();
foreach (var hostInstance in _tunerHostManager.TunerHosts)
{
try
{
- var channels = await hostInstance.GetChannels(enableCache, cancellationToken).ConfigureAwait(false);
+ var tunerChannels = await hostInstance.GetChannels(enableCache, cancellationToken).ConfigureAwait(false);
- list.AddRange(channels);
+ channels.AddRange(tunerChannels);
}
catch (Exception ex)
{
@@ -325,209 +325,9 @@ namespace Jellyfin.LiveTv.EmbyTV
}
}
- foreach (var provider in GetListingProviders())
- {
- var enabledChannels = list
- .Where(i => IsListingProviderEnabledForTuner(provider.Item2, i.TunerHostId))
- .ToList();
-
- if (enabledChannels.Count > 0)
- {
- try
- {
- await AddMetadata(provider.Item1, provider.Item2, enabledChannels, enableCache, cancellationToken).ConfigureAwait(false);
- }
- catch (NotSupportedException)
- {
- }
- catch (Exception ex)
- {
- _logger.LogError(ex, "Error adding metadata");
- }
- }
- }
-
- return list;
- }
-
- private async Task AddMetadata(
- IListingsProvider provider,
- ListingsProviderInfo info,
- IEnumerable<ChannelInfo> tunerChannels,
- bool enableCache,
- CancellationToken cancellationToken)
- {
- var epgChannels = await GetEpgChannels(provider, info, enableCache, cancellationToken).ConfigureAwait(false);
-
- foreach (var tunerChannel in tunerChannels)
- {
- var epgChannel = GetEpgChannelFromTunerChannel(info, tunerChannel, epgChannels);
-
- if (epgChannel is not null)
- {
- if (!string.IsNullOrWhiteSpace(epgChannel.Name))
- {
- // tunerChannel.Name = epgChannel.Name;
- }
-
- if (!string.IsNullOrWhiteSpace(epgChannel.ImageUrl))
- {
- tunerChannel.ImageUrl = epgChannel.ImageUrl;
- }
- }
- }
- }
-
- private async Task<EpgChannelData> GetEpgChannels(
- IListingsProvider provider,
- ListingsProviderInfo info,
- bool enableCache,
- CancellationToken cancellationToken)
- {
- if (!enableCache || !_epgChannels.TryGetValue(info.Id, out var result))
- {
- var channels = await provider.GetChannels(info, cancellationToken).ConfigureAwait(false);
-
- foreach (var channel in channels)
- {
- _logger.LogInformation("Found epg channel in {0} {1} {2} {3}", provider.Name, info.ListingsId, channel.Name, channel.Id);
- }
-
- result = new EpgChannelData(channels);
- _epgChannels.AddOrUpdate(info.Id, result, (_, _) => result);
- }
-
- return result;
- }
-
- private async Task<ChannelInfo> GetEpgChannelFromTunerChannel(IListingsProvider provider, ListingsProviderInfo info, ChannelInfo tunerChannel, CancellationToken cancellationToken)
- {
- var epgChannels = await GetEpgChannels(provider, info, true, cancellationToken).ConfigureAwait(false);
-
- return GetEpgChannelFromTunerChannel(info, tunerChannel, epgChannels);
- }
-
- private static string GetMappedChannel(string channelId, NameValuePair[] mappings)
- {
- foreach (NameValuePair mapping in mappings)
- {
- if (string.Equals(mapping.Name, channelId, StringComparison.OrdinalIgnoreCase))
- {
- return mapping.Value;
- }
- }
-
- return channelId;
- }
-
- internal ChannelInfo GetEpgChannelFromTunerChannel(NameValuePair[] mappings, ChannelInfo tunerChannel, List<ChannelInfo> epgChannels)
- {
- return GetEpgChannelFromTunerChannel(mappings, tunerChannel, new EpgChannelData(epgChannels));
- }
-
- private ChannelInfo GetEpgChannelFromTunerChannel(ListingsProviderInfo info, ChannelInfo tunerChannel, EpgChannelData epgChannels)
- {
- return GetEpgChannelFromTunerChannel(info.ChannelMappings, tunerChannel, epgChannels);
- }
-
- private ChannelInfo GetEpgChannelFromTunerChannel(
- NameValuePair[] mappings,
- ChannelInfo tunerChannel,
- EpgChannelData epgChannelData)
- {
- if (!string.IsNullOrWhiteSpace(tunerChannel.Id))
- {
- var mappedTunerChannelId = GetMappedChannel(tunerChannel.Id, mappings);
-
- if (string.IsNullOrWhiteSpace(mappedTunerChannelId))
- {
- mappedTunerChannelId = tunerChannel.Id;
- }
-
- var channel = epgChannelData.GetChannelById(mappedTunerChannelId);
-
- if (channel is not null)
- {
- return channel;
- }
- }
-
- if (!string.IsNullOrWhiteSpace(tunerChannel.TunerChannelId))
- {
- var tunerChannelId = tunerChannel.TunerChannelId;
- if (tunerChannelId.Contains(".json.schedulesdirect.org", StringComparison.OrdinalIgnoreCase))
- {
- tunerChannelId = tunerChannelId.Replace(".json.schedulesdirect.org", string.Empty, StringComparison.OrdinalIgnoreCase).TrimStart('I');
- }
-
- var mappedTunerChannelId = GetMappedChannel(tunerChannelId, mappings);
-
- if (string.IsNullOrWhiteSpace(mappedTunerChannelId))
- {
- mappedTunerChannelId = tunerChannelId;
- }
-
- var channel = epgChannelData.GetChannelById(mappedTunerChannelId);
-
- if (channel is not null)
- {
- return channel;
- }
- }
-
- if (!string.IsNullOrWhiteSpace(tunerChannel.Number))
- {
- var tunerChannelNumber = GetMappedChannel(tunerChannel.Number, mappings);
+ await _listingsManager.AddProviderMetadata(channels, enableCache, cancellationToken).ConfigureAwait(false);
- if (string.IsNullOrWhiteSpace(tunerChannelNumber))
- {
- tunerChannelNumber = tunerChannel.Number;
- }
-
- var channel = epgChannelData.GetChannelByNumber(tunerChannelNumber);
-
- if (channel is not null)
- {
- return channel;
- }
- }
-
- if (!string.IsNullOrWhiteSpace(tunerChannel.Name))
- {
- var normalizedName = EpgChannelData.NormalizeName(tunerChannel.Name);
-
- var channel = epgChannelData.GetChannelByName(normalizedName);
-
- if (channel is not null)
- {
- return channel;
- }
- }
-
- return null;
- }
-
- public async Task<List<ChannelInfo>> GetChannelsForListingsProvider(ListingsProviderInfo listingsProvider, CancellationToken cancellationToken)
- {
- var list = new List<ChannelInfo>();
-
- foreach (var hostInstance in _tunerHostManager.TunerHosts)
- {
- try
- {
- var channels = await hostInstance.GetChannels(false, cancellationToken).ConfigureAwait(false);
-
- list.AddRange(channels);
- }
- catch (Exception ex)
- {
- _logger.LogError(ex, "Error getting channels");
- }
- }
-
- return list
- .Where(i => IsListingProviderEnabledForTuner(listingsProvider, i.TunerHostId))
- .ToList();
+ return channels;
}
public Task<IEnumerable<ChannelInfo>> GetChannelsAsync(CancellationToken cancellationToken)
@@ -874,75 +674,13 @@ namespace Jellyfin.LiveTv.EmbyTV
return Task.FromResult((IEnumerable<SeriesTimerInfo>)_seriesTimerProvider.GetAll());
}
- private bool IsListingProviderEnabledForTuner(ListingsProviderInfo info, string tunerHostId)
- {
- if (info.EnableAllTuners)
- {
- return true;
- }
-
- if (string.IsNullOrWhiteSpace(tunerHostId))
- {
- throw new ArgumentNullException(nameof(tunerHostId));
- }
-
- return info.EnabledTuners.Contains(tunerHostId, StringComparison.OrdinalIgnoreCase);
- }
-
public async Task<IEnumerable<ProgramInfo>> GetProgramsAsync(string channelId, DateTime startDateUtc, DateTime endDateUtc, CancellationToken cancellationToken)
{
var channels = await GetChannelsAsync(true, cancellationToken).ConfigureAwait(false);
var channel = channels.First(i => string.Equals(i.Id, channelId, StringComparison.OrdinalIgnoreCase));
- foreach (var provider in GetListingProviders())
- {
- if (!IsListingProviderEnabledForTuner(provider.Item2, channel.TunerHostId))
- {
- _logger.LogDebug("Skipping getting programs for channel {0}-{1} from {2}-{3}, because it's not enabled for this tuner.", channel.Number, channel.Name, provider.Item1.Name, provider.Item2.ListingsId ?? string.Empty);
- continue;
- }
-
- _logger.LogDebug("Getting programs for channel {0}-{1} from {2}-{3}", channel.Number, channel.Name, provider.Item1.Name, provider.Item2.ListingsId ?? string.Empty);
-
- var epgChannel = await GetEpgChannelFromTunerChannel(provider.Item1, provider.Item2, channel, cancellationToken).ConfigureAwait(false);
-
- if (epgChannel is null)
- {
- _logger.LogDebug("EPG channel not found for tuner channel {0}-{1} from {2}-{3}", channel.Number, channel.Name, provider.Item1.Name, provider.Item2.ListingsId ?? string.Empty);
- continue;
- }
-
- List<ProgramInfo> programs = (await provider.Item1.GetProgramsAsync(provider.Item2, epgChannel.Id, startDateUtc, endDateUtc, cancellationToken)
- .ConfigureAwait(false)).ToList();
-
- // Replace the value that came from the provider with a normalized value
- foreach (var program in programs)
- {
- program.ChannelId = channelId;
-
- program.Id += "_" + channelId;
- }
-
- if (programs.Count > 0)
- {
- return programs;
- }
- }
-
- return Enumerable.Empty<ProgramInfo>();
- }
-
- private List<Tuple<IListingsProvider, ListingsProviderInfo>> GetListingProviders()
- {
- return _config.GetLiveTvConfiguration().ListingProviders
- .Select(i =>
- {
- var provider = _liveTvManager.ListingProviders.FirstOrDefault(l => string.Equals(l.Type, i.Type, StringComparison.OrdinalIgnoreCase));
-
- return provider is null ? null : new Tuple<IListingsProvider, ListingsProviderInfo>(provider, i);
- })
- .Where(i => i is not null)
- .ToList();
+ return await _listingsManager.GetProgramsAsync(channel, startDateUtc, endDateUtc, cancellationToken)
+ .ConfigureAwait(false);
}
public Task<MediaSourceInfo> GetChannelStream(string channelId, string streamId, CancellationToken cancellationToken)
@@ -1181,6 +919,12 @@ namespace Jellyfin.LiveTv.EmbyTV
return Path.Combine(recordPath, recordingFileName);
}
+ private BaseItem GetLiveTvChannel(TimerInfo timer)
+ {
+ var internalChannelId = _tvDtoService.GetInternalChannelId(Name, timer.ChannelId);
+ return _libraryManager.GetItemById(internalChannelId);
+ }
+
private async Task RecordStream(TimerInfo timer, DateTime recordingEndDate, ActiveRecordingInfo activeRecordingInfo)
{
ArgumentNullException.ThrowIfNull(timer);
@@ -1206,7 +950,7 @@ namespace Jellyfin.LiveTv.EmbyTV
var remoteMetadata = await FetchInternetMetadata(timer, CancellationToken.None).ConfigureAwait(false);
var recordPath = GetRecordingPath(timer, remoteMetadata, out string seriesPath);
- var channelItem = _liveTvManager.GetLiveTvChannel(timer, this);
+ var channelItem = GetLiveTvChannel(timer);
string liveStreamId = null;
RecordingStatus recordingStatus;
@@ -1444,9 +1188,7 @@ namespace Jellyfin.LiveTv.EmbyTV
return;
}
- await _recordingDeleteSemaphore.WaitAsync().ConfigureAwait(false);
-
- try
+ using (await _recordingDeleteSemaphore.LockAsync().ConfigureAwait(false))
{
if (_disposed)
{
@@ -1499,10 +1241,6 @@ namespace Jellyfin.LiveTv.EmbyTV
}
}
}
- finally
- {
- _recordingDeleteSemaphore.Release();
- }
}
private void DeleteLibraryItemsForTimers(List<TimerInfo> timers)
@@ -2089,7 +1827,7 @@ namespace Jellyfin.LiveTv.EmbyTV
{
var query = new InternalItemsQuery
{
- ItemIds = new[] { _liveTvManager.GetInternalProgramId(programId) },
+ ItemIds = [_tvDtoService.GetInternalProgramId(programId)],
Limit = 1,
DtoOptions = new DtoOptions()
};
@@ -2119,7 +1857,7 @@ namespace Jellyfin.LiveTv.EmbyTV
if (!string.IsNullOrWhiteSpace(channelId))
{
- query.ChannelIds = new[] { _liveTvManager.GetInternalChannelId(Name, channelId) };
+ query.ChannelIds = [_tvDtoService.GetInternalChannelId(Name, channelId)];
}
return _libraryManager.GetItemList(query).Cast<LiveTvProgram>().FirstOrDefault();
@@ -2155,7 +1893,7 @@ namespace Jellyfin.LiveTv.EmbyTV
private void HandleDuplicateShowIds(List<TimerInfo> timers)
{
// sort showings by HD channels first, then by startDate, record earliest showing possible
- foreach (var timer in timers.OrderByDescending(t => _liveTvManager.GetLiveTvChannel(t, this).IsHD).ThenBy(t => t.StartDate).Skip(1))
+ foreach (var timer in timers.OrderByDescending(t => GetLiveTvChannel(t).IsHD).ThenBy(t => t.StartDate).Skip(1))
{
timer.Status = RecordingStatus.Cancelled;
_timerProvider.Update(timer);
@@ -2305,7 +2043,7 @@ namespace Jellyfin.LiveTv.EmbyTV
if (!seriesTimer.RecordAnyChannel)
{
- query.ChannelIds = new[] { _liveTvManager.GetInternalChannelId(Name, seriesTimer.ChannelId) };
+ query.ChannelIds = [_tvDtoService.GetInternalChannelId(Name, seriesTimer.ChannelId)];
}
var tempChannelCache = new Dictionary<Guid, LiveTvChannel>();
diff --git a/src/Jellyfin.LiveTv/EmbyTV/EntryPoint.cs b/src/Jellyfin.LiveTv/EmbyTV/EntryPoint.cs
deleted file mode 100644
index e750c05ac..000000000
--- a/src/Jellyfin.LiveTv/EmbyTV/EntryPoint.cs
+++ /dev/null
@@ -1,21 +0,0 @@
-#pragma warning disable CS1591
-
-using System.Threading.Tasks;
-using MediaBrowser.Controller.Plugins;
-
-namespace Jellyfin.LiveTv.EmbyTV
-{
- public sealed class EntryPoint : IServerEntryPoint
- {
- /// <inheritdoc />
- public Task RunAsync()
- {
- return EmbyTV.Current.Start();
- }
-
- /// <inheritdoc />
- public void Dispose()
- {
- }
- }
-}
diff --git a/src/Jellyfin.LiveTv/EmbyTV/LiveTvHost.cs b/src/Jellyfin.LiveTv/EmbyTV/LiveTvHost.cs
new file mode 100644
index 000000000..dc15d53ff
--- /dev/null
+++ b/src/Jellyfin.LiveTv/EmbyTV/LiveTvHost.cs
@@ -0,0 +1,31 @@
+using System.Collections.Generic;
+using System.Linq;
+using System.Threading;
+using System.Threading.Tasks;
+using MediaBrowser.Controller.LiveTv;
+using Microsoft.Extensions.Hosting;
+
+namespace Jellyfin.LiveTv.EmbyTV;
+
+/// <summary>
+/// <see cref="IHostedService"/> responsible for initializing Live TV.
+/// </summary>
+public sealed class LiveTvHost : IHostedService
+{
+ private readonly EmbyTV _service;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="LiveTvHost"/> class.
+ /// </summary>
+ /// <param name="services">The available <see cref="ILiveTvService"/>s.</param>
+ public LiveTvHost(IEnumerable<ILiveTvService> services)
+ {
+ _service = services.OfType<EmbyTV>().First();
+ }
+
+ /// <inheritdoc />
+ public Task StartAsync(CancellationToken cancellationToken) => _service.Start();
+
+ /// <inheritdoc />
+ public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask;
+}
diff --git a/src/Jellyfin.LiveTv/Extensions/LiveTvServiceCollectionExtensions.cs b/src/Jellyfin.LiveTv/Extensions/LiveTvServiceCollectionExtensions.cs
index 5490547ec..e4800a031 100644
--- a/src/Jellyfin.LiveTv/Extensions/LiveTvServiceCollectionExtensions.cs
+++ b/src/Jellyfin.LiveTv/Extensions/LiveTvServiceCollectionExtensions.cs
@@ -1,4 +1,6 @@
using Jellyfin.LiveTv.Channels;
+using Jellyfin.LiveTv.Guide;
+using Jellyfin.LiveTv.Listings;
using Jellyfin.LiveTv.TunerHosts;
using Jellyfin.LiveTv.TunerHosts.HdHomerun;
using MediaBrowser.Controller.Channels;
@@ -24,8 +26,13 @@ public static class LiveTvServiceCollectionExtensions
services.AddSingleton<IChannelManager, ChannelManager>();
services.AddSingleton<IStreamHelper, StreamHelper>();
services.AddSingleton<ITunerHostManager, TunerHostManager>();
+ services.AddSingleton<IListingsManager, ListingsManager>();
+ services.AddSingleton<IGuideManager, GuideManager>();
+ services.AddSingleton<ILiveTvService, EmbyTV.EmbyTV>();
services.AddSingleton<ITunerHost, HdHomerunHost>();
services.AddSingleton<ITunerHost, M3UTunerHost>();
+ services.AddSingleton<IListingsProvider, SchedulesDirect>();
+ services.AddSingleton<IListingsProvider, XmlTvListingsProvider>();
}
}
diff --git a/src/Jellyfin.LiveTv/Guide/GuideManager.cs b/src/Jellyfin.LiveTv/Guide/GuideManager.cs
new file mode 100644
index 000000000..394fbbaea
--- /dev/null
+++ b/src/Jellyfin.LiveTv/Guide/GuideManager.cs
@@ -0,0 +1,707 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Threading;
+using System.Threading.Tasks;
+using Jellyfin.Data.Enums;
+using Jellyfin.Extensions;
+using Jellyfin.LiveTv.Configuration;
+using MediaBrowser.Common.Configuration;
+using MediaBrowser.Controller.Dto;
+using MediaBrowser.Controller.Entities;
+using MediaBrowser.Controller.Library;
+using MediaBrowser.Controller.LiveTv;
+using MediaBrowser.Controller.Persistence;
+using MediaBrowser.Controller.Providers;
+using MediaBrowser.Model.Entities;
+using MediaBrowser.Model.IO;
+using MediaBrowser.Model.LiveTv;
+using Microsoft.Extensions.Logging;
+
+namespace Jellyfin.LiveTv.Guide;
+
+/// <inheritdoc />
+public class GuideManager : IGuideManager
+{
+ private const int MaxGuideDays = 14;
+ private const string EtagKey = "ProgramEtag";
+ private const string ExternalServiceTag = "ExternalServiceId";
+
+ private readonly ILogger<GuideManager> _logger;
+ private readonly IConfigurationManager _config;
+ private readonly IFileSystem _fileSystem;
+ private readonly IItemRepository _itemRepo;
+ private readonly ILibraryManager _libraryManager;
+ private readonly ILiveTvManager _liveTvManager;
+ private readonly ITunerHostManager _tunerHostManager;
+ private readonly LiveTvDtoService _tvDtoService;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="GuideManager"/> class.
+ /// </summary>
+ /// <param name="logger">The <see cref="ILogger{TCategoryName}"/>.</param>
+ /// <param name="config">The <see cref="IConfigurationManager"/>.</param>
+ /// <param name="fileSystem">The <see cref="IFileSystem"/>.</param>
+ /// <param name="itemRepo">The <see cref="IItemRepository"/>.</param>
+ /// <param name="libraryManager">The <see cref="ILibraryManager"/>.</param>
+ /// <param name="liveTvManager">The <see cref="ILiveTvManager"/>.</param>
+ /// <param name="tunerHostManager">The <see cref="ITunerHostManager"/>.</param>
+ /// <param name="tvDtoService">The <see cref="LiveTvDtoService"/>.</param>
+ public GuideManager(
+ ILogger<GuideManager> logger,
+ IConfigurationManager config,
+ IFileSystem fileSystem,
+ IItemRepository itemRepo,
+ ILibraryManager libraryManager,
+ ILiveTvManager liveTvManager,
+ ITunerHostManager tunerHostManager,
+ LiveTvDtoService tvDtoService)
+ {
+ _logger = logger;
+ _config = config;
+ _fileSystem = fileSystem;
+ _itemRepo = itemRepo;
+ _libraryManager = libraryManager;
+ _liveTvManager = liveTvManager;
+ _tunerHostManager = tunerHostManager;
+ _tvDtoService = tvDtoService;
+ }
+
+ /// <inheritdoc />
+ public GuideInfo GetGuideInfo()
+ {
+ var startDate = DateTime.UtcNow;
+ var endDate = startDate.AddDays(GetGuideDays());
+
+ return new GuideInfo
+ {
+ StartDate = startDate,
+ EndDate = endDate
+ };
+ }
+
+ /// <inheritdoc />
+ public async Task RefreshGuide(IProgress<double> progress, CancellationToken cancellationToken)
+ {
+ ArgumentNullException.ThrowIfNull(progress);
+
+ await EmbyTV.EmbyTV.Current.CreateRecordingFolders().ConfigureAwait(false);
+
+ await _tunerHostManager.ScanForTunerDeviceChanges(cancellationToken).ConfigureAwait(false);
+
+ var numComplete = 0;
+ double progressPerService = _liveTvManager.Services.Count == 0
+ ? 0
+ : 1.0 / _liveTvManager.Services.Count;
+
+ var newChannelIdList = new List<Guid>();
+ var newProgramIdList = new List<Guid>();
+
+ var cleanDatabase = true;
+
+ foreach (var service in _liveTvManager.Services)
+ {
+ cancellationToken.ThrowIfCancellationRequested();
+
+ _logger.LogDebug("Refreshing guide from {Name}", service.Name);
+
+ try
+ {
+ var innerProgress = new Progress<double>(p => progress.Report(p * progressPerService));
+
+ var idList = await RefreshChannelsInternal(service, innerProgress, cancellationToken).ConfigureAwait(false);
+
+ newChannelIdList.AddRange(idList.Item1);
+ newProgramIdList.AddRange(idList.Item2);
+ }
+ catch (OperationCanceledException)
+ {
+ throw;
+ }
+ catch (Exception ex)
+ {
+ cleanDatabase = false;
+ _logger.LogError(ex, "Error refreshing channels for service");
+ }
+
+ numComplete++;
+ double percent = numComplete;
+ percent /= _liveTvManager.Services.Count;
+
+ progress.Report(100 * percent);
+ }
+
+ if (cleanDatabase)
+ {
+ CleanDatabase(newChannelIdList.ToArray(), [BaseItemKind.LiveTvChannel], progress, cancellationToken);
+ CleanDatabase(newProgramIdList.ToArray(), [BaseItemKind.LiveTvProgram], progress, cancellationToken);
+ }
+
+ var coreService = _liveTvManager.Services.OfType<EmbyTV.EmbyTV>().FirstOrDefault();
+ if (coreService is not null)
+ {
+ await coreService.RefreshSeriesTimers(cancellationToken).ConfigureAwait(false);
+ await coreService.RefreshTimers(cancellationToken).ConfigureAwait(false);
+ }
+
+ progress.Report(100);
+ }
+
+ private double GetGuideDays()
+ {
+ var config = _config.GetLiveTvConfiguration();
+
+ return config.GuideDays.HasValue
+ ? Math.Clamp(config.GuideDays.Value, 1, MaxGuideDays)
+ : 7;
+ }
+
+ private async Task<Tuple<List<Guid>, List<Guid>>> RefreshChannelsInternal(ILiveTvService service, IProgress<double> progress, CancellationToken cancellationToken)
+ {
+ progress.Report(10);
+
+ var allChannelsList = (await service.GetChannelsAsync(cancellationToken).ConfigureAwait(false))
+ .Select(i => new Tuple<string, ChannelInfo>(service.Name, i))
+ .ToList();
+
+ var list = new List<LiveTvChannel>();
+
+ var numComplete = 0;
+ var parentFolder = _liveTvManager.GetInternalLiveTvFolder(cancellationToken);
+
+ foreach (var channelInfo in allChannelsList)
+ {
+ cancellationToken.ThrowIfCancellationRequested();
+
+ try
+ {
+ var item = await GetChannel(channelInfo.Item2, channelInfo.Item1, parentFolder, cancellationToken).ConfigureAwait(false);
+
+ list.Add(item);
+ }
+ catch (OperationCanceledException)
+ {
+ throw;
+ }
+ catch (Exception ex)
+ {
+ _logger.LogError(ex, "Error getting channel information for {Name}", channelInfo.Item2.Name);
+ }
+
+ numComplete++;
+ double percent = numComplete;
+ percent /= allChannelsList.Count;
+
+ progress.Report((5 * percent) + 10);
+ }
+
+ progress.Report(15);
+
+ numComplete = 0;
+ var programs = new List<Guid>();
+ var channels = new List<Guid>();
+
+ var guideDays = GetGuideDays();
+
+ _logger.LogInformation("Refreshing guide with {0} days of guide data", guideDays);
+
+ foreach (var currentChannel in list)
+ {
+ cancellationToken.ThrowIfCancellationRequested();
+ channels.Add(currentChannel.Id);
+
+ try
+ {
+ var start = DateTime.UtcNow.AddHours(-1);
+ var end = start.AddDays(guideDays);
+
+ var isMovie = false;
+ var isSports = false;
+ var isNews = false;
+ var isKids = false;
+ var isSeries = false;
+
+ var channelPrograms = (await service.GetProgramsAsync(currentChannel.ExternalId, start, end, cancellationToken).ConfigureAwait(false)).ToList();
+
+ var existingPrograms = _libraryManager.GetItemList(new InternalItemsQuery
+ {
+ IncludeItemTypes = [BaseItemKind.LiveTvProgram],
+ ChannelIds = [currentChannel.Id],
+ DtoOptions = new DtoOptions(true)
+ }).Cast<LiveTvProgram>().ToDictionary(i => i.Id);
+
+ var newPrograms = new List<LiveTvProgram>();
+ var updatedPrograms = new List<BaseItem>();
+
+ foreach (var program in channelPrograms)
+ {
+ var (programItem, isNew, isUpdated) = GetProgram(program, existingPrograms, currentChannel);
+ if (isNew)
+ {
+ newPrograms.Add(programItem);
+ }
+ else if (isUpdated)
+ {
+ updatedPrograms.Add(programItem);
+ }
+
+ programs.Add(programItem.Id);
+
+ isMovie |= program.IsMovie;
+ isSeries |= program.IsSeries;
+ isSports |= program.IsSports;
+ isNews |= program.IsNews;
+ isKids |= program.IsKids;
+ }
+
+ _logger.LogDebug("Channel {0} has {1} new programs and {2} updated programs", currentChannel.Name, newPrograms.Count, updatedPrograms.Count);
+
+ if (newPrograms.Count > 0)
+ {
+ _libraryManager.CreateItems(newPrograms, null, cancellationToken);
+ }
+
+ if (updatedPrograms.Count > 0)
+ {
+ await _libraryManager.UpdateItemsAsync(
+ updatedPrograms,
+ currentChannel,
+ ItemUpdateType.MetadataImport,
+ cancellationToken).ConfigureAwait(false);
+ }
+
+ currentChannel.IsMovie = isMovie;
+ currentChannel.IsNews = isNews;
+ currentChannel.IsSports = isSports;
+ currentChannel.IsSeries = isSeries;
+
+ if (isKids)
+ {
+ currentChannel.AddTag("Kids");
+ }
+
+ await currentChannel.UpdateToRepositoryAsync(ItemUpdateType.MetadataImport, cancellationToken).ConfigureAwait(false);
+ await currentChannel.RefreshMetadata(
+ new MetadataRefreshOptions(new DirectoryService(_fileSystem))
+ {
+ ForceSave = true
+ },
+ cancellationToken).ConfigureAwait(false);
+ }
+ catch (OperationCanceledException)
+ {
+ throw;
+ }
+ catch (Exception ex)
+ {
+ _logger.LogError(ex, "Error getting programs for channel {Name}", currentChannel.Name);
+ }
+
+ numComplete++;
+ double percent = numComplete / (double)allChannelsList.Count;
+
+ progress.Report((85 * percent) + 15);
+ }
+
+ progress.Report(100);
+ return new Tuple<List<Guid>, List<Guid>>(channels, programs);
+ }
+
+ private void CleanDatabase(Guid[] currentIdList, BaseItemKind[] validTypes, IProgress<double> progress, CancellationToken cancellationToken)
+ {
+ var list = _itemRepo.GetItemIdsList(new InternalItemsQuery
+ {
+ IncludeItemTypes = validTypes,
+ DtoOptions = new DtoOptions(false)
+ });
+
+ var numComplete = 0;
+
+ foreach (var itemId in list)
+ {
+ cancellationToken.ThrowIfCancellationRequested();
+
+ if (itemId.IsEmpty())
+ {
+ // Somehow some invalid data got into the db. It probably predates the boundary checking
+ continue;
+ }
+
+ if (!currentIdList.Contains(itemId))
+ {
+ var item = _libraryManager.GetItemById(itemId);
+
+ if (item is not null)
+ {
+ _libraryManager.DeleteItem(
+ item,
+ new DeleteOptions
+ {
+ DeleteFileLocation = false,
+ DeleteFromExternalProvider = false
+ },
+ false);
+ }
+ }
+
+ numComplete++;
+ double percent = numComplete / (double)list.Count;
+
+ progress.Report(100 * percent);
+ }
+ }
+
+ private async Task<LiveTvChannel> GetChannel(
+ ChannelInfo channelInfo,
+ string serviceName,
+ BaseItem parentFolder,
+ CancellationToken cancellationToken)
+ {
+ var parentFolderId = parentFolder.Id;
+ var isNew = false;
+ var forceUpdate = false;
+
+ var id = _tvDtoService.GetInternalChannelId(serviceName, channelInfo.Id);
+
+ if (_libraryManager.GetItemById(id) is not LiveTvChannel item)
+ {
+ item = new LiveTvChannel
+ {
+ Name = channelInfo.Name,
+ Id = id,
+ DateCreated = DateTime.UtcNow
+ };
+
+ isNew = true;
+ }
+
+ if (channelInfo.Tags is not null)
+ {
+ if (!channelInfo.Tags.SequenceEqual(item.Tags, StringComparer.OrdinalIgnoreCase))
+ {
+ isNew = true;
+ }
+
+ item.Tags = channelInfo.Tags;
+ }
+
+ if (!item.ParentId.Equals(parentFolderId))
+ {
+ isNew = true;
+ }
+
+ item.ParentId = parentFolderId;
+
+ item.ChannelType = channelInfo.ChannelType;
+ item.ServiceName = serviceName;
+
+ if (!string.Equals(item.GetProviderId(ExternalServiceTag), serviceName, StringComparison.OrdinalIgnoreCase))
+ {
+ forceUpdate = true;
+ }
+
+ item.SetProviderId(ExternalServiceTag, serviceName);
+
+ if (!string.Equals(channelInfo.Id, item.ExternalId, StringComparison.Ordinal))
+ {
+ forceUpdate = true;
+ }
+
+ item.ExternalId = channelInfo.Id;
+
+ if (!string.Equals(channelInfo.Number, item.Number, StringComparison.Ordinal))
+ {
+ forceUpdate = true;
+ }
+
+ item.Number = channelInfo.Number;
+
+ if (!string.Equals(channelInfo.Name, item.Name, StringComparison.Ordinal))
+ {
+ forceUpdate = true;
+ }
+
+ item.Name = channelInfo.Name;
+
+ if (!item.HasImage(ImageType.Primary))
+ {
+ if (!string.IsNullOrWhiteSpace(channelInfo.ImagePath))
+ {
+ item.SetImagePath(ImageType.Primary, channelInfo.ImagePath);
+ forceUpdate = true;
+ }
+ else if (!string.IsNullOrWhiteSpace(channelInfo.ImageUrl))
+ {
+ item.SetImagePath(ImageType.Primary, channelInfo.ImageUrl);
+ forceUpdate = true;
+ }
+ }
+
+ if (isNew)
+ {
+ _libraryManager.CreateItem(item, parentFolder);
+ }
+ else if (forceUpdate)
+ {
+ await _libraryManager.UpdateItemAsync(item, parentFolder, ItemUpdateType.MetadataImport, cancellationToken).ConfigureAwait(false);
+ }
+
+ return item;
+ }
+
+ private (LiveTvProgram Item, bool IsNew, bool IsUpdated) GetProgram(
+ ProgramInfo info,
+ Dictionary<Guid, LiveTvProgram> allExistingPrograms,
+ LiveTvChannel channel)
+ {
+ var id = _tvDtoService.GetInternalProgramId(info.Id);
+
+ var isNew = false;
+ var forceUpdate = false;
+
+ if (!allExistingPrograms.TryGetValue(id, out var item))
+ {
+ isNew = true;
+ item = new LiveTvProgram
+ {
+ Name = info.Name,
+ Id = id,
+ DateCreated = DateTime.UtcNow,
+ DateModified = DateTime.UtcNow
+ };
+
+ if (!string.IsNullOrEmpty(info.Etag))
+ {
+ item.SetProviderId(EtagKey, info.Etag);
+ }
+ }
+
+ if (!string.Equals(info.ShowId, item.ShowId, StringComparison.OrdinalIgnoreCase))
+ {
+ item.ShowId = info.ShowId;
+ forceUpdate = true;
+ }
+
+ var seriesId = info.SeriesId;
+
+ if (!item.ParentId.Equals(channel.Id))
+ {
+ forceUpdate = true;
+ }
+
+ item.ParentId = channel.Id;
+
+ item.Audio = info.Audio;
+ item.ChannelId = channel.Id;
+ item.CommunityRating ??= info.CommunityRating;
+ if ((item.CommunityRating ?? 0).Equals(0))
+ {
+ item.CommunityRating = null;
+ }
+
+ item.EpisodeTitle = info.EpisodeTitle;
+ item.ExternalId = info.Id;
+
+ if (!string.IsNullOrWhiteSpace(seriesId) && !string.Equals(item.ExternalSeriesId, seriesId, StringComparison.Ordinal))
+ {
+ forceUpdate = true;
+ }
+
+ item.ExternalSeriesId = seriesId;
+
+ var isSeries = info.IsSeries || !string.IsNullOrEmpty(info.EpisodeTitle);
+
+ if (isSeries || !string.IsNullOrEmpty(info.EpisodeTitle))
+ {
+ item.SeriesName = info.Name;
+ }
+
+ var tags = new List<string>();
+ if (info.IsLive)
+ {
+ tags.Add("Live");
+ }
+
+ if (info.IsPremiere)
+ {
+ tags.Add("Premiere");
+ }
+
+ if (info.IsNews)
+ {
+ tags.Add("News");
+ }
+
+ if (info.IsSports)
+ {
+ tags.Add("Sports");
+ }
+
+ if (info.IsKids)
+ {
+ tags.Add("Kids");
+ }
+
+ if (info.IsRepeat)
+ {
+ tags.Add("Repeat");
+ }
+
+ if (info.IsMovie)
+ {
+ tags.Add("Movie");
+ }
+
+ if (isSeries)
+ {
+ tags.Add("Series");
+ }
+
+ item.Tags = tags.ToArray();
+
+ item.Genres = info.Genres.ToArray();
+
+ if (info.IsHD ?? false)
+ {
+ item.Width = 1280;
+ item.Height = 720;
+ }
+
+ item.IsMovie = info.IsMovie;
+ item.IsRepeat = info.IsRepeat;
+
+ if (item.IsSeries != isSeries)
+ {
+ forceUpdate = true;
+ }
+
+ item.IsSeries = isSeries;
+
+ item.Name = info.Name;
+ item.OfficialRating ??= info.OfficialRating;
+ item.Overview ??= info.Overview;
+ item.RunTimeTicks = (info.EndDate - info.StartDate).Ticks;
+ item.ProviderIds = info.ProviderIds;
+
+ foreach (var providerId in info.SeriesProviderIds)
+ {
+ info.ProviderIds["Series" + providerId.Key] = providerId.Value;
+ }
+
+ if (item.StartDate != info.StartDate)
+ {
+ forceUpdate = true;
+ }
+
+ item.StartDate = info.StartDate;
+
+ if (item.EndDate != info.EndDate)
+ {
+ forceUpdate = true;
+ }
+
+ item.EndDate = info.EndDate;
+
+ item.ProductionYear = info.ProductionYear;
+
+ if (!isSeries || info.IsRepeat)
+ {
+ item.PremiereDate = info.OriginalAirDate;
+ }
+
+ item.IndexNumber = info.EpisodeNumber;
+ item.ParentIndexNumber = info.SeasonNumber;
+
+ if (!item.HasImage(ImageType.Primary))
+ {
+ if (!string.IsNullOrWhiteSpace(info.ImagePath))
+ {
+ item.SetImage(
+ new ItemImageInfo
+ {
+ Path = info.ImagePath,
+ Type = ImageType.Primary
+ },
+ 0);
+ }
+ else if (!string.IsNullOrWhiteSpace(info.ImageUrl))
+ {
+ item.SetImage(
+ new ItemImageInfo
+ {
+ Path = info.ImageUrl,
+ Type = ImageType.Primary
+ },
+ 0);
+ }
+ }
+
+ if (!item.HasImage(ImageType.Thumb))
+ {
+ if (!string.IsNullOrWhiteSpace(info.ThumbImageUrl))
+ {
+ item.SetImage(
+ new ItemImageInfo
+ {
+ Path = info.ThumbImageUrl,
+ Type = ImageType.Thumb
+ },
+ 0);
+ }
+ }
+
+ if (!item.HasImage(ImageType.Logo))
+ {
+ if (!string.IsNullOrWhiteSpace(info.LogoImageUrl))
+ {
+ item.SetImage(
+ new ItemImageInfo
+ {
+ Path = info.LogoImageUrl,
+ Type = ImageType.Logo
+ },
+ 0);
+ }
+ }
+
+ if (!item.HasImage(ImageType.Backdrop))
+ {
+ if (!string.IsNullOrWhiteSpace(info.BackdropImageUrl))
+ {
+ item.SetImage(
+ new ItemImageInfo
+ {
+ Path = info.BackdropImageUrl,
+ Type = ImageType.Backdrop
+ },
+ 0);
+ }
+ }
+
+ var isUpdated = false;
+ if (isNew)
+ {
+ }
+ else if (forceUpdate || string.IsNullOrWhiteSpace(info.Etag))
+ {
+ isUpdated = true;
+ }
+ else
+ {
+ var etag = info.Etag;
+
+ if (!string.Equals(etag, item.GetProviderId(EtagKey), StringComparison.OrdinalIgnoreCase))
+ {
+ item.SetProviderId(EtagKey, etag);
+ isUpdated = true;
+ }
+ }
+
+ if (isNew || isUpdated)
+ {
+ item.OnMetadataChanged();
+ }
+
+ return (item, isNew, isUpdated);
+ }
+}
diff --git a/src/Jellyfin.LiveTv/Guide/RefreshGuideScheduledTask.cs b/src/Jellyfin.LiveTv/Guide/RefreshGuideScheduledTask.cs
new file mode 100644
index 000000000..a9fde0850
--- /dev/null
+++ b/src/Jellyfin.LiveTv/Guide/RefreshGuideScheduledTask.cs
@@ -0,0 +1,74 @@
+using System;
+using System.Collections.Generic;
+using System.Threading;
+using System.Threading.Tasks;
+using Jellyfin.LiveTv.Configuration;
+using MediaBrowser.Common.Configuration;
+using MediaBrowser.Controller.LiveTv;
+using MediaBrowser.Model.Tasks;
+
+namespace Jellyfin.LiveTv.Guide;
+
+/// <summary>
+/// The "Refresh Guide" scheduled task.
+/// </summary>
+public class RefreshGuideScheduledTask : IScheduledTask, IConfigurableScheduledTask
+{
+ private readonly ILiveTvManager _liveTvManager;
+ private readonly IGuideManager _guideManager;
+ private readonly IConfigurationManager _config;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="RefreshGuideScheduledTask"/> class.
+ /// </summary>
+ /// <param name="liveTvManager">The live tv manager.</param>
+ /// <param name="guideManager">The guide manager.</param>
+ /// <param name="config">The configuration manager.</param>
+ public RefreshGuideScheduledTask(
+ ILiveTvManager liveTvManager,
+ IGuideManager guideManager,
+ IConfigurationManager config)
+ {
+ _liveTvManager = liveTvManager;
+ _guideManager = guideManager;
+ _config = config;
+ }
+
+ /// <inheritdoc />
+ public string Name => "Refresh Guide";
+
+ /// <inheritdoc />
+ public string Description => "Downloads channel information from live tv services.";
+
+ /// <inheritdoc />
+ public string Category => "Live TV";
+
+ /// <inheritdoc />
+ public bool IsHidden => _liveTvManager.Services.Count == 1 && _config.GetLiveTvConfiguration().TunerHosts.Length == 0;
+
+ /// <inheritdoc />
+ public bool IsEnabled => true;
+
+ /// <inheritdoc />
+ public bool IsLogged => true;
+
+ /// <inheritdoc />
+ public string Key => "RefreshGuide";
+
+ /// <inheritdoc />
+ public Task ExecuteAsync(IProgress<double> progress, CancellationToken cancellationToken)
+ => _guideManager.RefreshGuide(progress, cancellationToken);
+
+ /// <inheritdoc />
+ public IEnumerable<TaskTriggerInfo> GetDefaultTriggers()
+ {
+ return new[]
+ {
+ new TaskTriggerInfo
+ {
+ Type = TaskTriggerInfo.TriggerInterval,
+ IntervalTicks = TimeSpan.FromHours(24).Ticks
+ }
+ };
+ }
+}
diff --git a/src/Jellyfin.LiveTv/Jellyfin.LiveTv.csproj b/src/Jellyfin.LiveTv/Jellyfin.LiveTv.csproj
index 5a826a1da..c58889740 100644
--- a/src/Jellyfin.LiveTv/Jellyfin.LiveTv.csproj
+++ b/src/Jellyfin.LiveTv/Jellyfin.LiveTv.csproj
@@ -1,4 +1,4 @@
-<Project Sdk="Microsoft.NET.Sdk">
+<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
@@ -11,6 +11,7 @@
</ItemGroup>
<ItemGroup>
+ <PackageReference Include="AsyncKeyedLock" />
<PackageReference Include="Jellyfin.XmlTv" />
<PackageReference Include="System.Linq.Async" />
</ItemGroup>
diff --git a/src/Jellyfin.LiveTv/EmbyTV/EpgChannelData.cs b/src/Jellyfin.LiveTv/Listings/EpgChannelData.cs
index 43d308c43..81437f791 100644
--- a/src/Jellyfin.LiveTv/EmbyTV/EpgChannelData.cs
+++ b/src/Jellyfin.LiveTv/Listings/EpgChannelData.cs
@@ -4,7 +4,7 @@ using System;
using System.Collections.Generic;
using MediaBrowser.Controller.LiveTv;
-namespace Jellyfin.LiveTv.EmbyTV
+namespace Jellyfin.LiveTv.Listings
{
internal class EpgChannelData
{
diff --git a/src/Jellyfin.LiveTv/Listings/ListingsManager.cs b/src/Jellyfin.LiveTv/Listings/ListingsManager.cs
new file mode 100644
index 000000000..87f47611e
--- /dev/null
+++ b/src/Jellyfin.LiveTv/Listings/ListingsManager.cs
@@ -0,0 +1,461 @@
+using System;
+using System.Collections.Concurrent;
+using System.Collections.Generic;
+using System.Globalization;
+using System.Linq;
+using System.Threading;
+using System.Threading.Tasks;
+using Jellyfin.LiveTv.Configuration;
+using Jellyfin.LiveTv.Guide;
+using MediaBrowser.Common.Configuration;
+using MediaBrowser.Common.Extensions;
+using MediaBrowser.Controller.LiveTv;
+using MediaBrowser.Model.Dto;
+using MediaBrowser.Model.LiveTv;
+using MediaBrowser.Model.Tasks;
+using Microsoft.Extensions.Logging;
+
+namespace Jellyfin.LiveTv.Listings;
+
+/// <inheritdoc />
+public class ListingsManager : IListingsManager
+{
+ private readonly ILogger<ListingsManager> _logger;
+ private readonly IConfigurationManager _config;
+ private readonly ITaskManager _taskManager;
+ private readonly ITunerHostManager _tunerHostManager;
+ private readonly IListingsProvider[] _listingsProviders;
+
+ private readonly ConcurrentDictionary<string, EpgChannelData> _epgChannels = new(StringComparer.OrdinalIgnoreCase);
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="ListingsManager"/> class.
+ /// </summary>
+ /// <param name="logger">The <see cref="ILogger{TCategoryName}"/>.</param>
+ /// <param name="config">The <see cref="IConfigurationManager"/>.</param>
+ /// <param name="taskManager">The <see cref="ITaskManager"/>.</param>
+ /// <param name="tunerHostManager">The <see cref="ITunerHostManager"/>.</param>
+ /// <param name="listingsProviders">The <see cref="IListingsProvider"/>.</param>
+ public ListingsManager(
+ ILogger<ListingsManager> logger,
+ IConfigurationManager config,
+ ITaskManager taskManager,
+ ITunerHostManager tunerHostManager,
+ IEnumerable<IListingsProvider> listingsProviders)
+ {
+ _logger = logger;
+ _config = config;
+ _taskManager = taskManager;
+ _tunerHostManager = tunerHostManager;
+ _listingsProviders = listingsProviders.ToArray();
+ }
+
+ /// <inheritdoc />
+ public async Task<ListingsProviderInfo> SaveListingProvider(ListingsProviderInfo info, bool validateLogin, bool validateListings)
+ {
+ ArgumentNullException.ThrowIfNull(info);
+
+ var provider = GetProvider(info.Type);
+ await provider.Validate(info, validateLogin, validateListings).ConfigureAwait(false);
+
+ var config = _config.GetLiveTvConfiguration();
+
+ var list = config.ListingProviders.ToList();
+ int index = list.FindIndex(i => string.Equals(i.Id, info.Id, StringComparison.OrdinalIgnoreCase));
+
+ if (index == -1 || string.IsNullOrWhiteSpace(info.Id))
+ {
+ info.Id = Guid.NewGuid().ToString("N", CultureInfo.InvariantCulture);
+ list.Add(info);
+ config.ListingProviders = list.ToArray();
+ }
+ else
+ {
+ config.ListingProviders[index] = info;
+ }
+
+ _config.SaveConfiguration("livetv", config);
+ _taskManager.CancelIfRunningAndQueue<RefreshGuideScheduledTask>();
+
+ return info;
+ }
+
+ /// <inheritdoc />
+ public void DeleteListingsProvider(string? id)
+ {
+ var config = _config.GetLiveTvConfiguration();
+
+ config.ListingProviders = config.ListingProviders.Where(i => !string.Equals(id, i.Id, StringComparison.OrdinalIgnoreCase)).ToArray();
+
+ _config.SaveConfiguration("livetv", config);
+ _taskManager.CancelIfRunningAndQueue<RefreshGuideScheduledTask>();
+ }
+
+ /// <inheritdoc />
+ public Task<List<NameIdPair>> GetLineups(string? providerType, string? providerId, string? country, string? location)
+ {
+ if (string.IsNullOrWhiteSpace(providerId))
+ {
+ return GetProvider(providerType).GetLineups(null, country, location);
+ }
+
+ var info = _config.GetLiveTvConfiguration().ListingProviders
+ .FirstOrDefault(i => string.Equals(i.Id, providerId, StringComparison.OrdinalIgnoreCase))
+ ?? throw new ResourceNotFoundException();
+
+ return GetProvider(info.Type).GetLineups(info, country, location);
+ }
+
+ /// <inheritdoc />
+ public async Task<IEnumerable<ProgramInfo>> GetProgramsAsync(
+ ChannelInfo channel,
+ DateTime startDateUtc,
+ DateTime endDateUtc,
+ CancellationToken cancellationToken)
+ {
+ ArgumentNullException.ThrowIfNull(channel);
+
+ foreach (var (provider, providerInfo) in GetListingProviders())
+ {
+ if (!IsListingProviderEnabledForTuner(providerInfo, channel.TunerHostId))
+ {
+ _logger.LogDebug(
+ "Skipping getting programs for channel {0}-{1} from {2}-{3}, because it's not enabled for this tuner.",
+ channel.Number,
+ channel.Name,
+ provider.Name,
+ providerInfo.ListingsId ?? string.Empty);
+ continue;
+ }
+
+ _logger.LogDebug(
+ "Getting programs for channel {0}-{1} from {2}-{3}",
+ channel.Number,
+ channel.Name,
+ provider.Name,
+ providerInfo.ListingsId ?? string.Empty);
+
+ var epgChannels = await GetEpgChannels(provider, providerInfo, true, cancellationToken).ConfigureAwait(false);
+
+ var epgChannel = GetEpgChannelFromTunerChannel(providerInfo.ChannelMappings, channel, epgChannels);
+ if (epgChannel is null)
+ {
+ _logger.LogDebug("EPG channel not found for tuner channel {0}-{1} from {2}-{3}", channel.Number, channel.Name, provider.Name, providerInfo.ListingsId ?? string.Empty);
+ continue;
+ }
+
+ var programs = (await provider
+ .GetProgramsAsync(providerInfo, epgChannel.Id, startDateUtc, endDateUtc, cancellationToken).ConfigureAwait(false))
+ .ToList();
+
+ // Replace the value that came from the provider with a normalized value
+ foreach (var program in programs)
+ {
+ program.ChannelId = channel.Id;
+ program.Id += "_" + channel.Id;
+ }
+
+ if (programs.Count > 0)
+ {
+ return programs;
+ }
+ }
+
+ return Enumerable.Empty<ProgramInfo>();
+ }
+
+ /// <inheritdoc />
+ public async Task AddProviderMetadata(IList<ChannelInfo> channels, bool enableCache, CancellationToken cancellationToken)
+ {
+ ArgumentNullException.ThrowIfNull(channels);
+
+ foreach (var (provider, providerInfo) in GetListingProviders())
+ {
+ var enabledChannels = channels
+ .Where(i => IsListingProviderEnabledForTuner(providerInfo, i.TunerHostId))
+ .ToList();
+
+ if (enabledChannels.Count == 0)
+ {
+ continue;
+ }
+
+ try
+ {
+ await AddMetadata(provider, providerInfo, enabledChannels, enableCache, cancellationToken).ConfigureAwait(false);
+ }
+ catch (NotSupportedException)
+ {
+ }
+ catch (Exception ex)
+ {
+ _logger.LogError(ex, "Error adding metadata");
+ }
+ }
+ }
+
+ /// <inheritdoc />
+ public async Task<ChannelMappingOptionsDto> GetChannelMappingOptions(string? providerId)
+ {
+ var listingsProviderInfo = _config.GetLiveTvConfiguration().ListingProviders
+ .First(info => string.Equals(providerId, info.Id, StringComparison.OrdinalIgnoreCase));
+
+ var provider = GetProvider(listingsProviderInfo.Type);
+
+ var tunerChannels = await GetChannelsForListingsProvider(listingsProviderInfo, CancellationToken.None)
+ .ConfigureAwait(false);
+
+ var providerChannels = await provider.GetChannels(listingsProviderInfo, default)
+ .ConfigureAwait(false);
+
+ var mappings = listingsProviderInfo.ChannelMappings;
+
+ return new ChannelMappingOptionsDto
+ {
+ TunerChannels = tunerChannels.Select(i => GetTunerChannelMapping(i, mappings, providerChannels)).ToList(),
+ ProviderChannels = providerChannels.Select(i => new NameIdPair
+ {
+ Name = i.Name,
+ Id = i.Id
+ }).ToList(),
+ Mappings = mappings,
+ ProviderName = provider.Name
+ };
+ }
+
+ /// <inheritdoc />
+ public async Task<TunerChannelMapping> SetChannelMapping(string providerId, string tunerChannelNumber, string providerChannelNumber)
+ {
+ var config = _config.GetLiveTvConfiguration();
+
+ var listingsProviderInfo = config.ListingProviders
+ .First(info => string.Equals(providerId, info.Id, StringComparison.OrdinalIgnoreCase));
+
+ listingsProviderInfo.ChannelMappings = listingsProviderInfo.ChannelMappings
+ .Where(pair => !string.Equals(pair.Name, tunerChannelNumber, StringComparison.OrdinalIgnoreCase)).ToArray();
+
+ if (!string.Equals(tunerChannelNumber, providerChannelNumber, StringComparison.OrdinalIgnoreCase))
+ {
+ var list = listingsProviderInfo.ChannelMappings.ToList();
+ list.Add(new NameValuePair
+ {
+ Name = tunerChannelNumber,
+ Value = providerChannelNumber
+ });
+ listingsProviderInfo.ChannelMappings = list.ToArray();
+ }
+
+ _config.SaveConfiguration("livetv", config);
+
+ var tunerChannels = await GetChannelsForListingsProvider(listingsProviderInfo, CancellationToken.None)
+ .ConfigureAwait(false);
+
+ var providerChannels = await GetProvider(listingsProviderInfo.Type).GetChannels(listingsProviderInfo, default)
+ .ConfigureAwait(false);
+
+ var tunerChannelMappings = tunerChannels
+ .Select(i => GetTunerChannelMapping(i, listingsProviderInfo.ChannelMappings, providerChannels)).ToList();
+
+ _taskManager.CancelIfRunningAndQueue<RefreshGuideScheduledTask>();
+
+ return tunerChannelMappings.First(i => string.Equals(i.Id, tunerChannelNumber, StringComparison.OrdinalIgnoreCase));
+ }
+
+ private List<(IListingsProvider Provider, ListingsProviderInfo ProviderInfo)> GetListingProviders()
+ => _config.GetLiveTvConfiguration().ListingProviders
+ .Select(info => (
+ Provider: _listingsProviders.FirstOrDefault(l
+ => string.Equals(l.Type, info.Type, StringComparison.OrdinalIgnoreCase)),
+ ProviderInfo: info))
+ .Where(i => i.Provider is not null)
+ .ToList()!; // Already filtered out null
+
+ private async Task AddMetadata(
+ IListingsProvider provider,
+ ListingsProviderInfo info,
+ IEnumerable<ChannelInfo> tunerChannels,
+ bool enableCache,
+ CancellationToken cancellationToken)
+ {
+ var epgChannels = await GetEpgChannels(provider, info, enableCache, cancellationToken).ConfigureAwait(false);
+
+ foreach (var tunerChannel in tunerChannels)
+ {
+ var epgChannel = GetEpgChannelFromTunerChannel(info.ChannelMappings, tunerChannel, epgChannels);
+ if (epgChannel is null)
+ {
+ continue;
+ }
+
+ if (!string.IsNullOrWhiteSpace(epgChannel.ImageUrl))
+ {
+ tunerChannel.ImageUrl = epgChannel.ImageUrl;
+ }
+ }
+ }
+
+ private static bool IsListingProviderEnabledForTuner(ListingsProviderInfo info, string tunerHostId)
+ {
+ if (info.EnableAllTuners)
+ {
+ return true;
+ }
+
+ ArgumentException.ThrowIfNullOrWhiteSpace(tunerHostId);
+
+ return info.EnabledTuners.Contains(tunerHostId, StringComparer.OrdinalIgnoreCase);
+ }
+
+ private static string GetMappedChannel(string channelId, NameValuePair[] mappings)
+ {
+ foreach (NameValuePair mapping in mappings)
+ {
+ if (string.Equals(mapping.Name, channelId, StringComparison.OrdinalIgnoreCase))
+ {
+ return mapping.Value;
+ }
+ }
+
+ return channelId;
+ }
+
+ private async Task<EpgChannelData> GetEpgChannels(
+ IListingsProvider provider,
+ ListingsProviderInfo info,
+ bool enableCache,
+ CancellationToken cancellationToken)
+ {
+ if (enableCache && _epgChannels.TryGetValue(info.Id, out var result))
+ {
+ return result;
+ }
+
+ var channels = await provider.GetChannels(info, cancellationToken).ConfigureAwait(false);
+ foreach (var channel in channels)
+ {
+ _logger.LogInformation("Found epg channel in {0} {1} {2} {3}", provider.Name, info.ListingsId, channel.Name, channel.Id);
+ }
+
+ result = new EpgChannelData(channels);
+ _epgChannels.AddOrUpdate(info.Id, result, (_, _) => result);
+
+ return result;
+ }
+
+ private static ChannelInfo? GetEpgChannelFromTunerChannel(
+ NameValuePair[] mappings,
+ ChannelInfo tunerChannel,
+ EpgChannelData epgChannelData)
+ {
+ if (!string.IsNullOrWhiteSpace(tunerChannel.Id))
+ {
+ var mappedTunerChannelId = GetMappedChannel(tunerChannel.Id, mappings);
+ if (string.IsNullOrWhiteSpace(mappedTunerChannelId))
+ {
+ mappedTunerChannelId = tunerChannel.Id;
+ }
+
+ var channel = epgChannelData.GetChannelById(mappedTunerChannelId);
+ if (channel is not null)
+ {
+ return channel;
+ }
+ }
+
+ if (!string.IsNullOrWhiteSpace(tunerChannel.TunerChannelId))
+ {
+ var tunerChannelId = tunerChannel.TunerChannelId;
+ if (tunerChannelId.Contains(".json.schedulesdirect.org", StringComparison.OrdinalIgnoreCase))
+ {
+ tunerChannelId = tunerChannelId.Replace(".json.schedulesdirect.org", string.Empty, StringComparison.OrdinalIgnoreCase).TrimStart('I');
+ }
+
+ var mappedTunerChannelId = GetMappedChannel(tunerChannelId, mappings);
+ if (string.IsNullOrWhiteSpace(mappedTunerChannelId))
+ {
+ mappedTunerChannelId = tunerChannelId;
+ }
+
+ var channel = epgChannelData.GetChannelById(mappedTunerChannelId);
+ if (channel is not null)
+ {
+ return channel;
+ }
+ }
+
+ if (!string.IsNullOrWhiteSpace(tunerChannel.Number))
+ {
+ var tunerChannelNumber = GetMappedChannel(tunerChannel.Number, mappings);
+ if (string.IsNullOrWhiteSpace(tunerChannelNumber))
+ {
+ tunerChannelNumber = tunerChannel.Number;
+ }
+
+ var channel = epgChannelData.GetChannelByNumber(tunerChannelNumber);
+ if (channel is not null)
+ {
+ return channel;
+ }
+ }
+
+ if (!string.IsNullOrWhiteSpace(tunerChannel.Name))
+ {
+ var normalizedName = EpgChannelData.NormalizeName(tunerChannel.Name);
+
+ var channel = epgChannelData.GetChannelByName(normalizedName);
+ if (channel is not null)
+ {
+ return channel;
+ }
+ }
+
+ return null;
+ }
+
+ private static TunerChannelMapping GetTunerChannelMapping(ChannelInfo tunerChannel, NameValuePair[] mappings, IList<ChannelInfo> providerChannels)
+ {
+ var result = new TunerChannelMapping
+ {
+ Name = tunerChannel.Name,
+ Id = tunerChannel.Id
+ };
+
+ if (!string.IsNullOrWhiteSpace(tunerChannel.Number))
+ {
+ result.Name = tunerChannel.Number + " " + result.Name;
+ }
+
+ var providerChannel = GetEpgChannelFromTunerChannel(mappings, tunerChannel, new EpgChannelData(providerChannels));
+ if (providerChannel is not null)
+ {
+ result.ProviderChannelName = providerChannel.Name;
+ result.ProviderChannelId = providerChannel.Id;
+ }
+
+ return result;
+ }
+
+ private async Task<List<ChannelInfo>> GetChannelsForListingsProvider(ListingsProviderInfo info, CancellationToken cancellationToken)
+ {
+ var channels = new List<ChannelInfo>();
+ foreach (var hostInstance in _tunerHostManager.TunerHosts)
+ {
+ try
+ {
+ var tunerChannels = await hostInstance.GetChannels(false, cancellationToken).ConfigureAwait(false);
+
+ channels.AddRange(tunerChannels.Where(channel => IsListingProviderEnabledForTuner(info, channel.TunerHostId)));
+ }
+ catch (Exception ex)
+ {
+ _logger.LogError(ex, "Error getting channels");
+ }
+ }
+
+ return channels;
+ }
+
+ private IListingsProvider GetProvider(string? providerType)
+ => _listingsProviders.FirstOrDefault(i => string.Equals(providerType, i.Type, StringComparison.OrdinalIgnoreCase))
+ ?? throw new ResourceNotFoundException($"Couldn't find provider of type {providerType}");
+}
diff --git a/src/Jellyfin.LiveTv/Listings/SchedulesDirect.cs b/src/Jellyfin.LiveTv/Listings/SchedulesDirect.cs
index 3b20cd160..c7a57859e 100644
--- a/src/Jellyfin.LiveTv/Listings/SchedulesDirect.cs
+++ b/src/Jellyfin.LiveTv/Listings/SchedulesDirect.cs
@@ -16,6 +16,7 @@ using System.Text;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
+using AsyncKeyedLock;
using Jellyfin.Extensions;
using Jellyfin.Extensions.Json;
using Jellyfin.LiveTv.Listings.SchedulesDirectDtos;
@@ -35,7 +36,7 @@ namespace Jellyfin.LiveTv.Listings
private readonly ILogger<SchedulesDirect> _logger;
private readonly IHttpClientFactory _httpClientFactory;
- private readonly SemaphoreSlim _tokenSemaphore = new SemaphoreSlim(1, 1);
+ private readonly AsyncNonKeyedLocker _tokenLock = new(1);
private readonly ConcurrentDictionary<string, NameValuePair> _tokens = new ConcurrentDictionary<string, NameValuePair>();
private readonly JsonSerializerOptions _jsonOptions = JsonDefaults.Options;
@@ -105,8 +106,7 @@ namespace Jellyfin.LiveTv.Listings
using var options = new HttpRequestMessage(HttpMethod.Post, ApiUrl + "/schedules");
options.Content = JsonContent.Create(requestList, options: _jsonOptions);
options.Headers.TryAddWithoutValidation("token", token);
- using var response = await Send(options, true, info, cancellationToken).ConfigureAwait(false);
- var dailySchedules = await response.Content.ReadFromJsonAsync<IReadOnlyList<DayDto>>(_jsonOptions, cancellationToken).ConfigureAwait(false);
+ var dailySchedules = await Request<IReadOnlyList<DayDto>>(options, true, info, cancellationToken).ConfigureAwait(false);
if (dailySchedules is null)
{
return Array.Empty<ProgramInfo>();
@@ -120,8 +120,8 @@ namespace Jellyfin.LiveTv.Listings
var programIds = dailySchedules.SelectMany(d => d.Programs.Select(s => s.ProgramId)).Distinct();
programRequestOptions.Content = JsonContent.Create(programIds, options: _jsonOptions);
- using var innerResponse = await Send(programRequestOptions, true, info, cancellationToken).ConfigureAwait(false);
- var programDetails = await innerResponse.Content.ReadFromJsonAsync<IReadOnlyList<ProgramDetailsDto>>(_jsonOptions, cancellationToken).ConfigureAwait(false);
+ var programDetails = await Request<IReadOnlyList<ProgramDetailsDto>>(programRequestOptions, true, info, cancellationToken)
+ .ConfigureAwait(false);
if (programDetails is null)
{
return Array.Empty<ProgramInfo>();
@@ -471,16 +471,13 @@ namespace Jellyfin.LiveTv.Listings
str.Length--;
str.Append(']');
- using var message = new HttpRequestMessage(HttpMethod.Post, ApiUrl + "/metadata/programs")
- {
- Content = new StringContent(str.ToString(), Encoding.UTF8, MediaTypeNames.Application.Json)
- };
+ using var message = new HttpRequestMessage(HttpMethod.Post, ApiUrl + "/metadata/programs");
message.Headers.TryAddWithoutValidation("token", token);
+ message.Content = new StringContent(str.ToString(), Encoding.UTF8, MediaTypeNames.Application.Json);
try
{
- using var innerResponse2 = await Send(message, true, info, cancellationToken).ConfigureAwait(false);
- return await innerResponse2.Content.ReadFromJsonAsync<IReadOnlyList<ShowImagesDto>>(_jsonOptions, cancellationToken).ConfigureAwait(false);
+ return await Request<IReadOnlyList<ShowImagesDto>>(message, true, info, cancellationToken).ConfigureAwait(false);
}
catch (Exception ex)
{
@@ -506,8 +503,7 @@ namespace Jellyfin.LiveTv.Listings
try
{
- using var httpResponse = await Send(options, false, info, cancellationToken).ConfigureAwait(false);
- var root = await httpResponse.Content.ReadFromJsonAsync<IReadOnlyList<HeadendsDto>>(_jsonOptions, cancellationToken).ConfigureAwait(false);
+ var root = await Request<IReadOnlyList<HeadendsDto>>(options, false, info, cancellationToken).ConfigureAwait(false);
if (root is not null)
{
foreach (HeadendsDto headend in root)
@@ -573,60 +569,64 @@ namespace Jellyfin.LiveTv.Listings
}
}
- await _tokenSemaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
- try
- {
- var result = await GetTokenInternal(username, password, cancellationToken).ConfigureAwait(false);
- savedToken.Name = result;
- savedToken.Value = DateTime.UtcNow.Ticks.ToString(CultureInfo.InvariantCulture);
- return result;
- }
- catch (HttpRequestException ex)
+ using (await _tokenLock.LockAsync(cancellationToken).ConfigureAwait(false))
{
- if (ex.StatusCode.HasValue && ex.StatusCode.Value == HttpStatusCode.BadRequest)
+ try
{
- _tokens.Clear();
- _lastErrorResponse = DateTime.UtcNow;
+ var result = await GetTokenInternal(username, password, cancellationToken).ConfigureAwait(false);
+ savedToken.Name = result;
+ savedToken.Value = DateTime.UtcNow.Ticks.ToString(CultureInfo.InvariantCulture);
+ return result;
}
+ catch (HttpRequestException ex)
+ {
+ if (ex.StatusCode.HasValue && ex.StatusCode.Value == HttpStatusCode.BadRequest)
+ {
+ _tokens.Clear();
+ _lastErrorResponse = DateTime.UtcNow;
+ }
- throw;
- }
- finally
- {
- _tokenSemaphore.Release();
+ throw;
+ }
}
}
- private async Task<HttpResponseMessage> Send(
- HttpRequestMessage options,
+ private async Task<T> Request<T>(
+ HttpRequestMessage message,
bool enableRetry,
ListingsProviderInfo providerInfo,
CancellationToken cancellationToken,
HttpCompletionOption completionOption = HttpCompletionOption.ResponseContentRead)
{
- var response = await _httpClientFactory.CreateClient(NamedClient.Default)
- .SendAsync(options, completionOption, cancellationToken).ConfigureAwait(false);
+ using var response = await _httpClientFactory.CreateClient(NamedClient.Default)
+ .SendAsync(message, completionOption, cancellationToken)
+ .ConfigureAwait(false);
if (response.IsSuccessStatusCode)
{
- return response;
+ return await response.Content.ReadFromJsonAsync<T>(_jsonOptions, cancellationToken).ConfigureAwait(false);
}
- // Response is automatically disposed in the calling function,
- // so dispose manually if not returning.
-#pragma warning disable IDISP016, IDISP017
- response.Dispose();
if (!enableRetry || (int)response.StatusCode >= 500)
{
+ _logger.LogError(
+ "Request to {Url} failed with response {Response}",
+ message.RequestUri,
+ await response.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false));
+
throw new HttpRequestException(
string.Format(CultureInfo.InvariantCulture, "Request failed: {0}", response.ReasonPhrase),
null,
response.StatusCode);
}
-#pragma warning restore IDISP016, IDISP017
_tokens.Clear();
- options.Headers.TryAddWithoutValidation("token", await GetToken(providerInfo, cancellationToken).ConfigureAwait(false));
- return await Send(options, false, providerInfo, cancellationToken).ConfigureAwait(false);
+ using var retryMessage = new HttpRequestMessage(message.Method, message.RequestUri);
+ retryMessage.Content = message.Content;
+ retryMessage.Headers.TryAddWithoutValidation(
+ "token",
+ await GetToken(providerInfo, cancellationToken).ConfigureAwait(false));
+
+ return await Request<T>(retryMessage, false, providerInfo, cancellationToken).ConfigureAwait(false);
}
private async Task<string> GetTokenInternal(
@@ -643,9 +643,7 @@ namespace Jellyfin.LiveTv.Listings
string hashedPassword = Convert.ToHexString(hashedPasswordBytes).ToLowerInvariant();
options.Content = new StringContent("{\"username\":\"" + username + "\",\"password\":\"" + hashedPassword + "\"}", Encoding.UTF8, MediaTypeNames.Application.Json);
- using var response = await Send(options, false, null, cancellationToken).ConfigureAwait(false);
- response.EnsureSuccessStatusCode();
- var root = await response.Content.ReadFromJsonAsync<TokenDto>(_jsonOptions, cancellationToken).ConfigureAwait(false);
+ var root = await Request<TokenDto>(options, false, null, cancellationToken).ConfigureAwait(false);
if (string.Equals(root?.Message, "OK", StringComparison.Ordinal))
{
_logger.LogInformation("Authenticated with Schedules Direct token: {Token}", root.Token);
@@ -662,11 +660,21 @@ namespace Jellyfin.LiveTv.Listings
ArgumentException.ThrowIfNullOrEmpty(token);
ArgumentException.ThrowIfNullOrEmpty(info.ListingsId);
- _logger.LogInformation("Adding new LineUp ");
+ _logger.LogInformation("Adding new lineup {Id}", info.ListingsId);
- using var options = new HttpRequestMessage(HttpMethod.Put, ApiUrl + "/lineups/" + info.ListingsId);
- options.Headers.TryAddWithoutValidation("token", token);
- using var response = await _httpClientFactory.CreateClient(NamedClient.Default).SendAsync(options, HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false);
+ using var message = new HttpRequestMessage(HttpMethod.Put, ApiUrl + "/lineups/" + info.ListingsId);
+ message.Headers.TryAddWithoutValidation("token", token);
+
+ using var response = await _httpClientFactory.CreateClient(NamedClient.Default)
+ .SendAsync(message, HttpCompletionOption.ResponseHeadersRead, cancellationToken)
+ .ConfigureAwait(false);
+
+ if (!response.IsSuccessStatusCode)
+ {
+ _logger.LogError(
+ "Error adding lineup to account: {Response}",
+ await response.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false));
+ }
}
private async Task<bool> HasLineup(ListingsProviderInfo info, CancellationToken cancellationToken)
@@ -684,9 +692,7 @@ namespace Jellyfin.LiveTv.Listings
try
{
- using var httpResponse = await Send(options, false, null, cancellationToken).ConfigureAwait(false);
- httpResponse.EnsureSuccessStatusCode();
- var root = await httpResponse.Content.ReadFromJsonAsync<LineupsDto>(_jsonOptions, cancellationToken).ConfigureAwait(false);
+ var root = await Request<LineupsDto>(options, false, null, cancellationToken).ConfigureAwait(false);
return root?.Lineups.Any(i => string.Equals(info.ListingsId, i.Lineup, StringComparison.OrdinalIgnoreCase)) ?? false;
}
catch (HttpRequestException ex)
@@ -739,8 +745,7 @@ namespace Jellyfin.LiveTv.Listings
using var options = new HttpRequestMessage(HttpMethod.Get, ApiUrl + "/lineups/" + listingsId);
options.Headers.TryAddWithoutValidation("token", token);
- using var httpResponse = await Send(options, true, info, cancellationToken).ConfigureAwait(false);
- var root = await httpResponse.Content.ReadFromJsonAsync<ChannelDto>(_jsonOptions, cancellationToken).ConfigureAwait(false);
+ var root = await Request<ChannelDto>(options, true, info, cancellationToken).ConfigureAwait(false);
if (root is null)
{
return new List<ChannelInfo>();
@@ -801,7 +806,7 @@ namespace Jellyfin.LiveTv.Listings
if (disposing)
{
- _tokenSemaphore?.Dispose();
+ _tokenLock?.Dispose();
}
_disposed = true;
diff --git a/src/Jellyfin.LiveTv/LiveTvManager.cs b/src/Jellyfin.LiveTv/LiveTvManager.cs
index bada4249a..1b69fd7fd 100644
--- a/src/Jellyfin.LiveTv/LiveTvManager.cs
+++ b/src/Jellyfin.LiveTv/LiveTvManager.cs
@@ -6,32 +6,25 @@ using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
-using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using Jellyfin.Data.Entities;
using Jellyfin.Data.Enums;
using Jellyfin.Data.Events;
-using Jellyfin.Extensions;
using Jellyfin.LiveTv.Configuration;
using MediaBrowser.Common.Extensions;
-using MediaBrowser.Common.Progress;
using MediaBrowser.Controller.Channels;
using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Dto;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.LiveTv;
-using MediaBrowser.Controller.Persistence;
-using MediaBrowser.Controller.Providers;
using MediaBrowser.Controller.Sorting;
using MediaBrowser.Model.Dto;
using MediaBrowser.Model.Entities;
using MediaBrowser.Model.Globalization;
-using MediaBrowser.Model.IO;
using MediaBrowser.Model.LiveTv;
using MediaBrowser.Model.Querying;
-using MediaBrowser.Model.Tasks;
using Microsoft.Extensions.Logging;
namespace Jellyfin.LiveTv
@@ -41,56 +34,43 @@ namespace Jellyfin.LiveTv
/// </summary>
public class LiveTvManager : ILiveTvManager
{
- private const int MaxGuideDays = 14;
- private const string ExternalServiceTag = "ExternalServiceId";
-
- private const string EtagKey = "ProgramEtag";
-
private readonly IServerConfigurationManager _config;
private readonly ILogger<LiveTvManager> _logger;
- private readonly IItemRepository _itemRepo;
private readonly IUserManager _userManager;
private readonly IDtoService _dtoService;
private readonly IUserDataManager _userDataManager;
private readonly ILibraryManager _libraryManager;
- private readonly ITaskManager _taskManager;
private readonly ILocalizationManager _localization;
- private readonly IFileSystem _fileSystem;
private readonly IChannelManager _channelManager;
private readonly LiveTvDtoService _tvDtoService;
- private readonly ITunerHostManager _tunerHostManager;
-
- private ILiveTvService[] _services = Array.Empty<ILiveTvService>();
- private IListingsProvider[] _listingProviders = Array.Empty<IListingsProvider>();
+ private readonly ILiveTvService[] _services;
public LiveTvManager(
IServerConfigurationManager config,
ILogger<LiveTvManager> logger,
- IItemRepository itemRepo,
IUserDataManager userDataManager,
IDtoService dtoService,
IUserManager userManager,
ILibraryManager libraryManager,
- ITaskManager taskManager,
ILocalizationManager localization,
- IFileSystem fileSystem,
IChannelManager channelManager,
LiveTvDtoService liveTvDtoService,
- ITunerHostManager tunerHostManager)
+ IEnumerable<ILiveTvService> services)
{
_config = config;
_logger = logger;
- _itemRepo = itemRepo;
_userManager = userManager;
_libraryManager = libraryManager;
- _taskManager = taskManager;
_localization = localization;
- _fileSystem = fileSystem;
_dtoService = dtoService;
_userDataManager = userDataManager;
_channelManager = channelManager;
_tvDtoService = liveTvDtoService;
- _tunerHostManager = tunerHostManager;
+ _services = services.ToArray();
+
+ var defaultService = _services.OfType<EmbyTV.EmbyTV>().First();
+ defaultService.TimerCreated += OnEmbyTvTimerCreated;
+ defaultService.TimerCancelled += OnEmbyTvTimerCancelled;
}
public event EventHandler<GenericEventArgs<TimerEventInfo>> SeriesTimerCancelled;
@@ -107,30 +87,11 @@ namespace Jellyfin.LiveTv
/// <value>The services.</value>
public IReadOnlyList<ILiveTvService> Services => _services;
- public IReadOnlyList<IListingsProvider> ListingProviders => _listingProviders;
-
public string GetEmbyTvActiveRecordingPath(string id)
{
return EmbyTV.EmbyTV.Current.GetActiveRecordingPath(id);
}
- /// <inheritdoc />
- public void AddParts(IEnumerable<ILiveTvService> services, IEnumerable<IListingsProvider> listingProviders)
- {
- _services = services.ToArray();
-
- _listingProviders = listingProviders.ToArray();
-
- foreach (var service in _services)
- {
- if (service is EmbyTV.EmbyTV embyTv)
- {
- embyTv.TimerCreated += OnEmbyTvTimerCreated;
- embyTv.TimerCancelled += OnEmbyTvTimerCancelled;
- }
- }
- }
-
private void OnEmbyTvTimerCancelled(object sender, GenericEventArgs<string> e)
{
var timerId = e.Argument;
@@ -151,7 +112,7 @@ namespace Jellyfin.LiveTv
public QueryResult<BaseItem> GetInternalChannels(LiveTvChannelQuery query, DtoOptions dtoOptions, CancellationToken cancellationToken)
{
- var user = query.UserId.IsEmpty()
+ var user = query.UserId.Equals(default)
? null
: _userManager.GetUserById(query.UserId);
@@ -401,355 +362,6 @@ namespace Jellyfin.LiveTv
}
}
- private async Task<LiveTvChannel> GetChannelAsync(ChannelInfo channelInfo, string serviceName, BaseItem parentFolder, CancellationToken cancellationToken)
- {
- var parentFolderId = parentFolder.Id;
- var isNew = false;
- var forceUpdate = false;
-
- var id = _tvDtoService.GetInternalChannelId(serviceName, channelInfo.Id);
-
- var item = _libraryManager.GetItemById(id) as LiveTvChannel;
-
- if (item is null)
- {
- item = new LiveTvChannel
- {
- Name = channelInfo.Name,
- Id = id,
- DateCreated = DateTime.UtcNow
- };
-
- isNew = true;
- }
-
- if (channelInfo.Tags is not null)
- {
- if (!channelInfo.Tags.SequenceEqual(item.Tags, StringComparer.OrdinalIgnoreCase))
- {
- isNew = true;
- }
-
- item.Tags = channelInfo.Tags;
- }
-
- if (!item.ParentId.Equals(parentFolderId))
- {
- isNew = true;
- }
-
- item.ParentId = parentFolderId;
-
- item.ChannelType = channelInfo.ChannelType;
- item.ServiceName = serviceName;
-
- if (!string.Equals(item.GetProviderId(ExternalServiceTag), serviceName, StringComparison.OrdinalIgnoreCase))
- {
- forceUpdate = true;
- }
-
- item.SetProviderId(ExternalServiceTag, serviceName);
-
- if (!string.Equals(channelInfo.Id, item.ExternalId, StringComparison.Ordinal))
- {
- forceUpdate = true;
- }
-
- item.ExternalId = channelInfo.Id;
-
- if (!string.Equals(channelInfo.Number, item.Number, StringComparison.Ordinal))
- {
- forceUpdate = true;
- }
-
- item.Number = channelInfo.Number;
-
- if (!string.Equals(channelInfo.Name, item.Name, StringComparison.Ordinal))
- {
- forceUpdate = true;
- }
-
- item.Name = channelInfo.Name;
-
- if (!item.HasImage(ImageType.Primary))
- {
- if (!string.IsNullOrWhiteSpace(channelInfo.ImagePath))
- {
- item.SetImagePath(ImageType.Primary, channelInfo.ImagePath);
- forceUpdate = true;
- }
- else if (!string.IsNullOrWhiteSpace(channelInfo.ImageUrl))
- {
- item.SetImagePath(ImageType.Primary, channelInfo.ImageUrl);
- forceUpdate = true;
- }
- }
-
- if (isNew)
- {
- _libraryManager.CreateItem(item, parentFolder);
- }
- else if (forceUpdate)
- {
- await _libraryManager.UpdateItemAsync(item, parentFolder, ItemUpdateType.MetadataImport, cancellationToken).ConfigureAwait(false);
- }
-
- return item;
- }
-
- private (LiveTvProgram Item, bool IsNew, bool IsUpdated) GetProgram(ProgramInfo info, Dictionary<Guid, LiveTvProgram> allExistingPrograms, LiveTvChannel channel)
- {
- var id = _tvDtoService.GetInternalProgramId(info.Id);
-
- var isNew = false;
- var forceUpdate = false;
-
- if (!allExistingPrograms.TryGetValue(id, out LiveTvProgram item))
- {
- isNew = true;
- item = new LiveTvProgram
- {
- Name = info.Name,
- Id = id,
- DateCreated = DateTime.UtcNow,
- DateModified = DateTime.UtcNow
- };
-
- if (!string.IsNullOrEmpty(info.Etag))
- {
- item.SetProviderId(EtagKey, info.Etag);
- }
- }
-
- if (!string.Equals(info.ShowId, item.ShowId, StringComparison.OrdinalIgnoreCase))
- {
- item.ShowId = info.ShowId;
- forceUpdate = true;
- }
-
- var seriesId = info.SeriesId;
-
- if (!item.ParentId.Equals(channel.Id))
- {
- forceUpdate = true;
- }
-
- item.ParentId = channel.Id;
-
- item.Audio = info.Audio;
- item.ChannelId = channel.Id;
- item.CommunityRating ??= info.CommunityRating;
- if ((item.CommunityRating ?? 0).Equals(0))
- {
- item.CommunityRating = null;
- }
-
- item.EpisodeTitle = info.EpisodeTitle;
- item.ExternalId = info.Id;
-
- if (!string.IsNullOrWhiteSpace(seriesId) && !string.Equals(item.ExternalSeriesId, seriesId, StringComparison.Ordinal))
- {
- forceUpdate = true;
- }
-
- item.ExternalSeriesId = seriesId;
-
- var isSeries = info.IsSeries || !string.IsNullOrEmpty(info.EpisodeTitle);
-
- if (isSeries || !string.IsNullOrEmpty(info.EpisodeTitle))
- {
- item.SeriesName = info.Name;
- }
-
- var tags = new List<string>();
- if (info.IsLive)
- {
- tags.Add("Live");
- }
-
- if (info.IsPremiere)
- {
- tags.Add("Premiere");
- }
-
- if (info.IsNews)
- {
- tags.Add("News");
- }
-
- if (info.IsSports)
- {
- tags.Add("Sports");
- }
-
- if (info.IsKids)
- {
- tags.Add("Kids");
- }
-
- if (info.IsRepeat)
- {
- tags.Add("Repeat");
- }
-
- if (info.IsMovie)
- {
- tags.Add("Movie");
- }
-
- if (isSeries)
- {
- tags.Add("Series");
- }
-
- item.Tags = tags.ToArray();
-
- item.Genres = info.Genres.ToArray();
-
- if (info.IsHD ?? false)
- {
- item.Width = 1280;
- item.Height = 720;
- }
-
- item.IsMovie = info.IsMovie;
- item.IsRepeat = info.IsRepeat;
-
- if (item.IsSeries != isSeries)
- {
- forceUpdate = true;
- }
-
- item.IsSeries = isSeries;
-
- item.Name = info.Name;
- item.OfficialRating ??= info.OfficialRating;
- item.Overview ??= info.Overview;
- item.RunTimeTicks = (info.EndDate - info.StartDate).Ticks;
- item.ProviderIds = info.ProviderIds;
-
- foreach (var providerId in info.SeriesProviderIds)
- {
- info.ProviderIds["Series" + providerId.Key] = providerId.Value;
- }
-
- if (item.StartDate != info.StartDate)
- {
- forceUpdate = true;
- }
-
- item.StartDate = info.StartDate;
-
- if (item.EndDate != info.EndDate)
- {
- forceUpdate = true;
- }
-
- item.EndDate = info.EndDate;
-
- item.ProductionYear = info.ProductionYear;
-
- if (!isSeries || info.IsRepeat)
- {
- item.PremiereDate = info.OriginalAirDate;
- }
-
- item.IndexNumber = info.EpisodeNumber;
- item.ParentIndexNumber = info.SeasonNumber;
-
- if (!item.HasImage(ImageType.Primary))
- {
- if (!string.IsNullOrWhiteSpace(info.ImagePath))
- {
- item.SetImage(
- new ItemImageInfo
- {
- Path = info.ImagePath,
- Type = ImageType.Primary
- },
- 0);
- }
- else if (!string.IsNullOrWhiteSpace(info.ImageUrl))
- {
- item.SetImage(
- new ItemImageInfo
- {
- Path = info.ImageUrl,
- Type = ImageType.Primary
- },
- 0);
- }
- }
-
- if (!item.HasImage(ImageType.Thumb))
- {
- if (!string.IsNullOrWhiteSpace(info.ThumbImageUrl))
- {
- item.SetImage(
- new ItemImageInfo
- {
- Path = info.ThumbImageUrl,
- Type = ImageType.Thumb
- },
- 0);
- }
- }
-
- if (!item.HasImage(ImageType.Logo))
- {
- if (!string.IsNullOrWhiteSpace(info.LogoImageUrl))
- {
- item.SetImage(
- new ItemImageInfo
- {
- Path = info.LogoImageUrl,
- Type = ImageType.Logo
- },
- 0);
- }
- }
-
- if (!item.HasImage(ImageType.Backdrop))
- {
- if (!string.IsNullOrWhiteSpace(info.BackdropImageUrl))
- {
- item.SetImage(
- new ItemImageInfo
- {
- Path = info.BackdropImageUrl,
- Type = ImageType.Backdrop
- },
- 0);
- }
- }
-
- var isUpdated = false;
- if (isNew)
- {
- }
- else if (forceUpdate || string.IsNullOrWhiteSpace(info.Etag))
- {
- isUpdated = true;
- }
- else
- {
- var etag = info.Etag;
-
- if (!string.Equals(etag, item.GetProviderId(EtagKey), StringComparison.OrdinalIgnoreCase))
- {
- item.SetProviderId(EtagKey, etag);
- isUpdated = true;
- }
- }
-
- if (isNew || isUpdated)
- {
- item.OnMetadataChanged();
- }
-
- return (item, isNew, isUpdated);
- }
-
public async Task<BaseItemDto> GetProgram(string id, CancellationToken cancellationToken, User user = null)
{
var program = _libraryManager.GetItemById(id);
@@ -1001,293 +613,6 @@ namespace Jellyfin.LiveTv
}
}
- internal Task RefreshChannels(IProgress<double> progress, CancellationToken cancellationToken)
- {
- return RefreshChannelsInternal(progress, cancellationToken);
- }
-
- private async Task RefreshChannelsInternal(IProgress<double> progress, CancellationToken cancellationToken)
- {
- await EmbyTV.EmbyTV.Current.CreateRecordingFolders().ConfigureAwait(false);
-
- await _tunerHostManager.ScanForTunerDeviceChanges(cancellationToken).ConfigureAwait(false);
-
- var numComplete = 0;
- double progressPerService = _services.Length == 0
- ? 0
- : 1.0 / _services.Length;
-
- var newChannelIdList = new List<Guid>();
- var newProgramIdList = new List<Guid>();
-
- var cleanDatabase = true;
-
- foreach (var service in _services)
- {
- cancellationToken.ThrowIfCancellationRequested();
-
- _logger.LogDebug("Refreshing guide from {Name}", service.Name);
-
- try
- {
- var innerProgress = new ActionableProgress<double>();
- innerProgress.RegisterAction(p => progress.Report(p * progressPerService));
-
- var idList = await RefreshChannelsInternal(service, innerProgress, cancellationToken).ConfigureAwait(false);
-
- newChannelIdList.AddRange(idList.Item1);
- newProgramIdList.AddRange(idList.Item2);
- }
- catch (OperationCanceledException)
- {
- throw;
- }
- catch (Exception ex)
- {
- cleanDatabase = false;
- _logger.LogError(ex, "Error refreshing channels for service");
- }
-
- numComplete++;
- double percent = numComplete;
- percent /= _services.Length;
-
- progress.Report(100 * percent);
- }
-
- if (cleanDatabase)
- {
- CleanDatabaseInternal(newChannelIdList.ToArray(), new[] { BaseItemKind.LiveTvChannel }, progress, cancellationToken);
- CleanDatabaseInternal(newProgramIdList.ToArray(), new[] { BaseItemKind.LiveTvProgram }, progress, cancellationToken);
- }
-
- var coreService = _services.OfType<EmbyTV.EmbyTV>().FirstOrDefault();
-
- if (coreService is not null)
- {
- await coreService.RefreshSeriesTimers(cancellationToken).ConfigureAwait(false);
- await coreService.RefreshTimers(cancellationToken).ConfigureAwait(false);
- }
-
- // Load these now which will prefetch metadata
- var dtoOptions = new DtoOptions();
- var fields = dtoOptions.Fields.ToList();
- dtoOptions.Fields = fields.ToArray();
-
- progress.Report(100);
- }
-
- private async Task<Tuple<List<Guid>, List<Guid>>> RefreshChannelsInternal(ILiveTvService service, ActionableProgress<double> progress, CancellationToken cancellationToken)
- {
- progress.Report(10);
-
- var allChannelsList = (await service.GetChannelsAsync(cancellationToken).ConfigureAwait(false))
- .Select(i => new Tuple<string, ChannelInfo>(service.Name, i))
- .ToList();
-
- var list = new List<LiveTvChannel>();
-
- var numComplete = 0;
- var parentFolder = GetInternalLiveTvFolder(cancellationToken);
-
- foreach (var channelInfo in allChannelsList)
- {
- cancellationToken.ThrowIfCancellationRequested();
-
- try
- {
- var item = await GetChannelAsync(channelInfo.Item2, channelInfo.Item1, parentFolder, cancellationToken).ConfigureAwait(false);
-
- list.Add(item);
- }
- catch (OperationCanceledException)
- {
- throw;
- }
- catch (Exception ex)
- {
- _logger.LogError(ex, "Error getting channel information for {Name}", channelInfo.Item2.Name);
- }
-
- numComplete++;
- double percent = numComplete;
- percent /= allChannelsList.Count;
-
- progress.Report((5 * percent) + 10);
- }
-
- progress.Report(15);
-
- numComplete = 0;
- var programs = new List<Guid>();
- var channels = new List<Guid>();
-
- var guideDays = GetGuideDays();
-
- _logger.LogInformation("Refreshing guide with {0} days of guide data", guideDays);
-
- cancellationToken.ThrowIfCancellationRequested();
-
- foreach (var currentChannel in list)
- {
- channels.Add(currentChannel.Id);
- cancellationToken.ThrowIfCancellationRequested();
-
- try
- {
- var start = DateTime.UtcNow.AddHours(-1);
- var end = start.AddDays(guideDays);
-
- var isMovie = false;
- var isSports = false;
- var isNews = false;
- var isKids = false;
- var iSSeries = false;
-
- var channelPrograms = (await service.GetProgramsAsync(currentChannel.ExternalId, start, end, cancellationToken).ConfigureAwait(false)).ToList();
-
- var existingPrograms = _libraryManager.GetItemList(new InternalItemsQuery
- {
- IncludeItemTypes = new[] { BaseItemKind.LiveTvProgram },
- ChannelIds = new Guid[] { currentChannel.Id },
- DtoOptions = new DtoOptions(true)
- }).Cast<LiveTvProgram>().ToDictionary(i => i.Id);
-
- var newPrograms = new List<LiveTvProgram>();
- var updatedPrograms = new List<BaseItem>();
-
- foreach (var program in channelPrograms)
- {
- var programTuple = GetProgram(program, existingPrograms, currentChannel);
- var programItem = programTuple.Item;
-
- if (programTuple.IsNew)
- {
- newPrograms.Add(programItem);
- }
- else if (programTuple.IsUpdated)
- {
- updatedPrograms.Add(programItem);
- }
-
- programs.Add(programItem.Id);
-
- isMovie |= program.IsMovie;
- iSSeries |= program.IsSeries;
- isSports |= program.IsSports;
- isNews |= program.IsNews;
- isKids |= program.IsKids;
- }
-
- _logger.LogDebug("Channel {0} has {1} new programs and {2} updated programs", currentChannel.Name, newPrograms.Count, updatedPrograms.Count);
-
- if (newPrograms.Count > 0)
- {
- _libraryManager.CreateItems(newPrograms, null, cancellationToken);
- }
-
- if (updatedPrograms.Count > 0)
- {
- await _libraryManager.UpdateItemsAsync(
- updatedPrograms,
- currentChannel,
- ItemUpdateType.MetadataImport,
- cancellationToken).ConfigureAwait(false);
- }
-
- currentChannel.IsMovie = isMovie;
- currentChannel.IsNews = isNews;
- currentChannel.IsSports = isSports;
- currentChannel.IsSeries = iSSeries;
-
- if (isKids)
- {
- currentChannel.AddTag("Kids");
- }
-
- await currentChannel.UpdateToRepositoryAsync(ItemUpdateType.MetadataImport, cancellationToken).ConfigureAwait(false);
- await currentChannel.RefreshMetadata(
- new MetadataRefreshOptions(new DirectoryService(_fileSystem))
- {
- ForceSave = true
- },
- cancellationToken).ConfigureAwait(false);
- }
- catch (OperationCanceledException)
- {
- throw;
- }
- catch (Exception ex)
- {
- _logger.LogError(ex, "Error getting programs for channel {Name}", currentChannel.Name);
- }
-
- numComplete++;
- double percent = numComplete / (double)allChannelsList.Count;
-
- progress.Report((85 * percent) + 15);
- }
-
- progress.Report(100);
- return new Tuple<List<Guid>, List<Guid>>(channels, programs);
- }
-
- private void CleanDatabaseInternal(Guid[] currentIdList, BaseItemKind[] validTypes, IProgress<double> progress, CancellationToken cancellationToken)
- {
- var list = _itemRepo.GetItemIdsList(new InternalItemsQuery
- {
- IncludeItemTypes = validTypes,
- DtoOptions = new DtoOptions(false)
- });
-
- var numComplete = 0;
-
- foreach (var itemId in list)
- {
- cancellationToken.ThrowIfCancellationRequested();
-
- if (itemId.IsEmpty())
- {
- // Somehow some invalid data got into the db. It probably predates the boundary checking
- continue;
- }
-
- if (!currentIdList.Contains(itemId))
- {
- var item = _libraryManager.GetItemById(itemId);
-
- if (item is not null)
- {
- _libraryManager.DeleteItem(
- item,
- new DeleteOptions
- {
- DeleteFileLocation = false,
- DeleteFromExternalProvider = false
- },
- false);
- }
- }
-
- numComplete++;
- double percent = numComplete / (double)list.Count;
-
- progress.Report(100 * percent);
- }
- }
-
- private double GetGuideDays()
- {
- var config = _config.GetLiveTvConfiguration();
-
- if (config.GuideDays.HasValue)
- {
- return Math.Max(1, Math.Min(config.GuideDays.Value, MaxGuideDays));
- }
-
- return 7;
- }
-
private async Task<QueryResult<BaseItem>> GetEmbyRecordingsAsync(RecordingQuery query, DtoOptions dtoOptions, User user)
{
if (user is null)
@@ -1505,7 +830,7 @@ namespace Jellyfin.LiveTv
public async Task<QueryResult<BaseItemDto>> GetRecordingsAsync(RecordingQuery query, DtoOptions options)
{
- var user = query.UserId.IsEmpty()
+ var user = query.UserId.Equals(default)
? null
: _userManager.GetUserById(query.UserId);
@@ -1819,12 +1144,6 @@ namespace Jellyfin.LiveTv
return new QueryResult<SeriesTimerInfoDto>(returnArray);
}
- public BaseItem GetLiveTvChannel(TimerInfo timer, ILiveTvService service)
- {
- var internalChannelId = _tvDtoService.GetInternalChannelId(service.Name, timer.ChannelId);
- return _libraryManager.GetItemById(internalChannelId);
- }
-
public void AddChannelInfo(IReadOnlyCollection<(BaseItemDto ItemDto, LiveTvChannel Channel)> items, DtoOptions options, User user)
{
var now = DateTime.UtcNow;
@@ -2057,18 +1376,6 @@ namespace Jellyfin.LiveTv
await service.UpdateSeriesTimerAsync(info, cancellationToken).ConfigureAwait(false);
}
- public GuideInfo GetGuideInfo()
- {
- var startDate = DateTime.UtcNow;
- var endDate = startDate.AddDays(GetGuideDays());
-
- return new GuideInfo
- {
- StartDate = startDate,
- EndDate = endDate
- };
- }
-
private LiveTvServiceInfo[] GetServiceInfos()
{
return Services.Select(GetServiceInfo).ToArray();
@@ -2147,171 +1454,6 @@ namespace Jellyfin.LiveTv
return _libraryManager.GetNamedView(name, CollectionType.livetv, name);
}
- public async Task<ListingsProviderInfo> SaveListingProvider(ListingsProviderInfo info, bool validateLogin, bool validateListings)
- {
- // Hack to make the object a pure ListingsProviderInfo instead of an AddListingProvider
- // ServerConfiguration.SaveConfiguration crashes during xml serialization for AddListingProvider
- info = JsonSerializer.Deserialize<ListingsProviderInfo>(JsonSerializer.SerializeToUtf8Bytes(info));
-
- var provider = _listingProviders.FirstOrDefault(i => string.Equals(info.Type, i.Type, StringComparison.OrdinalIgnoreCase));
-
- if (provider is null)
- {
- throw new ResourceNotFoundException(
- string.Format(
- CultureInfo.InvariantCulture,
- "Couldn't find provider of type: '{0}'",
- info.Type));
- }
-
- await provider.Validate(info, validateLogin, validateListings).ConfigureAwait(false);
-
- var config = _config.GetLiveTvConfiguration();
-
- var list = config.ListingProviders.ToList();
- int index = list.FindIndex(i => string.Equals(i.Id, info.Id, StringComparison.OrdinalIgnoreCase));
-
- if (index == -1 || string.IsNullOrWhiteSpace(info.Id))
- {
- info.Id = Guid.NewGuid().ToString("N", CultureInfo.InvariantCulture);
- list.Add(info);
- config.ListingProviders = list.ToArray();
- }
- else
- {
- config.ListingProviders[index] = info;
- }
-
- _config.SaveConfiguration("livetv", config);
-
- _taskManager.CancelIfRunningAndQueue<RefreshGuideScheduledTask>();
-
- return info;
- }
-
- public void DeleteListingsProvider(string id)
- {
- var config = _config.GetLiveTvConfiguration();
-
- config.ListingProviders = config.ListingProviders.Where(i => !string.Equals(id, i.Id, StringComparison.OrdinalIgnoreCase)).ToArray();
-
- _config.SaveConfiguration("livetv", config);
- _taskManager.CancelIfRunningAndQueue<RefreshGuideScheduledTask>();
- }
-
- public async Task<TunerChannelMapping> SetChannelMapping(string providerId, string tunerChannelNumber, string providerChannelNumber)
- {
- var config = _config.GetLiveTvConfiguration();
-
- var listingsProviderInfo = config.ListingProviders.First(i => string.Equals(providerId, i.Id, StringComparison.OrdinalIgnoreCase));
- listingsProviderInfo.ChannelMappings = listingsProviderInfo.ChannelMappings.Where(i => !string.Equals(i.Name, tunerChannelNumber, StringComparison.OrdinalIgnoreCase)).ToArray();
-
- if (!string.Equals(tunerChannelNumber, providerChannelNumber, StringComparison.OrdinalIgnoreCase))
- {
- var list = listingsProviderInfo.ChannelMappings.ToList();
- list.Add(new NameValuePair
- {
- Name = tunerChannelNumber,
- Value = providerChannelNumber
- });
- listingsProviderInfo.ChannelMappings = list.ToArray();
- }
-
- _config.SaveConfiguration("livetv", config);
-
- var tunerChannels = await GetChannelsForListingsProvider(providerId, CancellationToken.None)
- .ConfigureAwait(false);
-
- var providerChannels = await GetChannelsFromListingsProviderData(providerId, CancellationToken.None)
- .ConfigureAwait(false);
-
- var mappings = listingsProviderInfo.ChannelMappings;
-
- var tunerChannelMappings =
- tunerChannels.Select(i => GetTunerChannelMapping(i, mappings, providerChannels)).ToList();
-
- _taskManager.CancelIfRunningAndQueue<RefreshGuideScheduledTask>();
-
- return tunerChannelMappings.First(i => string.Equals(i.Id, tunerChannelNumber, StringComparison.OrdinalIgnoreCase));
- }
-
- public TunerChannelMapping GetTunerChannelMapping(ChannelInfo tunerChannel, NameValuePair[] mappings, List<ChannelInfo> providerChannels)
- {
- var result = new TunerChannelMapping
- {
- Name = tunerChannel.Name,
- Id = tunerChannel.Id
- };
-
- if (!string.IsNullOrWhiteSpace(tunerChannel.Number))
- {
- result.Name = tunerChannel.Number + " " + result.Name;
- }
-
- var providerChannel = EmbyTV.EmbyTV.Current.GetEpgChannelFromTunerChannel(mappings, tunerChannel, providerChannels);
-
- if (providerChannel is not null)
- {
- result.ProviderChannelName = providerChannel.Name;
- result.ProviderChannelId = providerChannel.Id;
- }
-
- return result;
- }
-
- public Task<List<NameIdPair>> GetLineups(string providerType, string providerId, string country, string location)
- {
- var config = _config.GetLiveTvConfiguration();
-
- if (string.IsNullOrWhiteSpace(providerId))
- {
- var provider = _listingProviders.FirstOrDefault(i => string.Equals(providerType, i.Type, StringComparison.OrdinalIgnoreCase));
-
- if (provider is null)
- {
- throw new ResourceNotFoundException();
- }
-
- return provider.GetLineups(null, country, location);
- }
- else
- {
- var info = config.ListingProviders.FirstOrDefault(i => string.Equals(i.Id, providerId, StringComparison.OrdinalIgnoreCase));
-
- var provider = _listingProviders.FirstOrDefault(i => string.Equals(info.Type, i.Type, StringComparison.OrdinalIgnoreCase));
-
- if (provider is null)
- {
- throw new ResourceNotFoundException();
- }
-
- return provider.GetLineups(info, country, location);
- }
- }
-
- public Task<List<ChannelInfo>> GetChannelsForListingsProvider(string id, CancellationToken cancellationToken)
- {
- var info = _config.GetLiveTvConfiguration().ListingProviders.First(i => string.Equals(i.Id, id, StringComparison.OrdinalIgnoreCase));
- return EmbyTV.EmbyTV.Current.GetChannelsForListingsProvider(info, cancellationToken);
- }
-
- public Task<List<ChannelInfo>> GetChannelsFromListingsProviderData(string id, CancellationToken cancellationToken)
- {
- var info = _config.GetLiveTvConfiguration().ListingProviders.First(i => string.Equals(i.Id, id, StringComparison.OrdinalIgnoreCase));
- var provider = _listingProviders.First(i => string.Equals(i.Type, info.Type, StringComparison.OrdinalIgnoreCase));
- return provider.GetChannels(info, cancellationToken);
- }
-
- public Guid GetInternalChannelId(string serviceName, string externalId)
- {
- return _tvDtoService.GetInternalChannelId(serviceName, externalId);
- }
-
- public Guid GetInternalProgramId(string externalId)
- {
- return _tvDtoService.GetInternalProgramId(externalId);
- }
-
/// <inheritdoc />
public Task<BaseItem[]> GetRecordingFoldersAsync(User user)
=> GetRecordingFoldersAsync(user, false);
diff --git a/src/Jellyfin.LiveTv/RecordingNotifier.cs b/src/Jellyfin.LiveTv/RecordingNotifier.cs
index 2923948eb..226d525e7 100644
--- a/src/Jellyfin.LiveTv/RecordingNotifier.cs
+++ b/src/Jellyfin.LiveTv/RecordingNotifier.cs
@@ -1,7 +1,3 @@
-#nullable disable
-
-#pragma warning disable CS1591
-
using System;
using System.Linq;
using System.Threading;
@@ -10,34 +6,44 @@ using Jellyfin.Data.Enums;
using Jellyfin.Data.Events;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.LiveTv;
-using MediaBrowser.Controller.Plugins;
using MediaBrowser.Controller.Session;
using MediaBrowser.Model.Session;
+using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
namespace Jellyfin.LiveTv
{
- public sealed class RecordingNotifier : IServerEntryPoint
+ /// <summary>
+ /// <see cref="IHostedService"/> responsible for notifying users when a LiveTV recording is completed.
+ /// </summary>
+ public sealed class RecordingNotifier : IHostedService
{
- private readonly ILiveTvManager _liveTvManager;
+ private readonly ILogger<RecordingNotifier> _logger;
private readonly ISessionManager _sessionManager;
private readonly IUserManager _userManager;
- private readonly ILogger<RecordingNotifier> _logger;
+ private readonly ILiveTvManager _liveTvManager;
+ /// <summary>
+ /// Initializes a new instance of the <see cref="RecordingNotifier"/> class.
+ /// </summary>
+ /// <param name="logger">The <see cref="ILogger"/>.</param>
+ /// <param name="sessionManager">The <see cref="ISessionManager"/>.</param>
+ /// <param name="userManager">The <see cref="IUserManager"/>.</param>
+ /// <param name="liveTvManager">The <see cref="ILiveTvManager"/>.</param>
public RecordingNotifier(
+ ILogger<RecordingNotifier> logger,
ISessionManager sessionManager,
IUserManager userManager,
- ILogger<RecordingNotifier> logger,
ILiveTvManager liveTvManager)
{
+ _logger = logger;
_sessionManager = sessionManager;
_userManager = userManager;
- _logger = logger;
_liveTvManager = liveTvManager;
}
/// <inheritdoc />
- public Task RunAsync()
+ public Task StartAsync(CancellationToken cancellationToken)
{
_liveTvManager.TimerCancelled += OnLiveTvManagerTimerCancelled;
_liveTvManager.SeriesTimerCancelled += OnLiveTvManagerSeriesTimerCancelled;
@@ -47,29 +53,35 @@ namespace Jellyfin.LiveTv
return Task.CompletedTask;
}
- private async void OnLiveTvManagerSeriesTimerCreated(object sender, GenericEventArgs<TimerEventInfo> e)
+ /// <inheritdoc />
+ public Task StopAsync(CancellationToken cancellationToken)
{
- await SendMessage(SessionMessageType.SeriesTimerCreated, e.Argument).ConfigureAwait(false);
- }
+ _liveTvManager.TimerCancelled -= OnLiveTvManagerTimerCancelled;
+ _liveTvManager.SeriesTimerCancelled -= OnLiveTvManagerSeriesTimerCancelled;
+ _liveTvManager.TimerCreated -= OnLiveTvManagerTimerCreated;
+ _liveTvManager.SeriesTimerCreated -= OnLiveTvManagerSeriesTimerCreated;
- private async void OnLiveTvManagerTimerCreated(object sender, GenericEventArgs<TimerEventInfo> e)
- {
- await SendMessage(SessionMessageType.TimerCreated, e.Argument).ConfigureAwait(false);
+ return Task.CompletedTask;
}
- private async void OnLiveTvManagerSeriesTimerCancelled(object sender, GenericEventArgs<TimerEventInfo> e)
- {
- await SendMessage(SessionMessageType.SeriesTimerCancelled, e.Argument).ConfigureAwait(false);
- }
+ private async void OnLiveTvManagerSeriesTimerCreated(object? sender, GenericEventArgs<TimerEventInfo> e)
+ => await SendMessage(SessionMessageType.SeriesTimerCreated, e.Argument).ConfigureAwait(false);
- private async void OnLiveTvManagerTimerCancelled(object sender, GenericEventArgs<TimerEventInfo> e)
- {
- await SendMessage(SessionMessageType.TimerCancelled, e.Argument).ConfigureAwait(false);
- }
+ private async void OnLiveTvManagerTimerCreated(object? sender, GenericEventArgs<TimerEventInfo> e)
+ => await SendMessage(SessionMessageType.TimerCreated, e.Argument).ConfigureAwait(false);
+
+ private async void OnLiveTvManagerSeriesTimerCancelled(object? sender, GenericEventArgs<TimerEventInfo> e)
+ => await SendMessage(SessionMessageType.SeriesTimerCancelled, e.Argument).ConfigureAwait(false);
+
+ private async void OnLiveTvManagerTimerCancelled(object? sender, GenericEventArgs<TimerEventInfo> e)
+ => await SendMessage(SessionMessageType.TimerCancelled, e.Argument).ConfigureAwait(false);
private async Task SendMessage(SessionMessageType name, TimerEventInfo info)
{
- var users = _userManager.Users.Where(i => i.HasPermission(PermissionKind.EnableLiveTvAccess)).Select(i => i.Id).ToList();
+ var users = _userManager.Users
+ .Where(i => i.HasPermission(PermissionKind.EnableLiveTvAccess))
+ .Select(i => i.Id)
+ .ToList();
try
{
@@ -80,14 +92,5 @@ namespace Jellyfin.LiveTv
_logger.LogError(ex, "Error sending message");
}
}
-
- /// <inheritdoc />
- public void Dispose()
- {
- _liveTvManager.TimerCancelled -= OnLiveTvManagerTimerCancelled;
- _liveTvManager.SeriesTimerCancelled -= OnLiveTvManagerSeriesTimerCancelled;
- _liveTvManager.TimerCreated -= OnLiveTvManagerTimerCreated;
- _liveTvManager.SeriesTimerCreated -= OnLiveTvManagerSeriesTimerCreated;
- }
}
}
diff --git a/src/Jellyfin.LiveTv/RefreshGuideScheduledTask.cs b/src/Jellyfin.LiveTv/RefreshGuideScheduledTask.cs
deleted file mode 100644
index 18bd61d99..000000000
--- a/src/Jellyfin.LiveTv/RefreshGuideScheduledTask.cs
+++ /dev/null
@@ -1,70 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Threading;
-using System.Threading.Tasks;
-using Jellyfin.LiveTv.Configuration;
-using MediaBrowser.Common.Configuration;
-using MediaBrowser.Controller.LiveTv;
-using MediaBrowser.Model.Tasks;
-
-namespace Jellyfin.LiveTv
-{
- /// <summary>
- /// The "Refresh Guide" scheduled task.
- /// </summary>
- public class RefreshGuideScheduledTask : IScheduledTask, IConfigurableScheduledTask
- {
- private readonly ILiveTvManager _liveTvManager;
- private readonly IConfigurationManager _config;
-
- /// <summary>
- /// Initializes a new instance of the <see cref="RefreshGuideScheduledTask"/> class.
- /// </summary>
- /// <param name="liveTvManager">The live tv manager.</param>
- /// <param name="config">The configuration manager.</param>
- public RefreshGuideScheduledTask(ILiveTvManager liveTvManager, IConfigurationManager config)
- {
- _liveTvManager = liveTvManager;
- _config = config;
- }
-
- /// <inheritdoc />
- public string Name => "Refresh Guide";
-
- /// <inheritdoc />
- public string Description => "Downloads channel information from live tv services.";
-
- /// <inheritdoc />
- public string Category => "Live TV";
-
- /// <inheritdoc />
- public bool IsHidden => _liveTvManager.Services.Count == 1 && _config.GetLiveTvConfiguration().TunerHosts.Length == 0;
-
- /// <inheritdoc />
- public bool IsEnabled => true;
-
- /// <inheritdoc />
- public bool IsLogged => true;
-
- /// <inheritdoc />
- public string Key => "RefreshGuide";
-
- /// <inheritdoc />
- public Task ExecuteAsync(IProgress<double> progress, CancellationToken cancellationToken)
- {
- var manager = (LiveTvManager)_liveTvManager;
-
- return manager.RefreshChannels(progress, cancellationToken);
- }
-
- /// <inheritdoc />
- public IEnumerable<TaskTriggerInfo> GetDefaultTriggers()
- {
- return new[]
- {
- // Every so often
- new TaskTriggerInfo { Type = TaskTriggerInfo.TriggerInterval, IntervalTicks = TimeSpan.FromHours(24).Ticks }
- };
- }
- }
-}
diff --git a/src/Jellyfin.LiveTv/TunerHosts/TunerHostManager.cs b/src/Jellyfin.LiveTv/TunerHosts/TunerHostManager.cs
index 3e4b0e13f..60be19c68 100644
--- a/src/Jellyfin.LiveTv/TunerHosts/TunerHostManager.cs
+++ b/src/Jellyfin.LiveTv/TunerHosts/TunerHostManager.cs
@@ -6,6 +6,7 @@ using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using Jellyfin.LiveTv.Configuration;
+using Jellyfin.LiveTv.Guide;
using MediaBrowser.Common.Configuration;
using MediaBrowser.Common.Extensions;
using MediaBrowser.Controller.LiveTv;
diff --git a/src/Jellyfin.Networking/ExternalPortForwarding.cs b/src/Jellyfin.Networking/PortForwardingHost.cs
index df9e43ca9..d01343624 100644
--- a/src/Jellyfin.Networking/ExternalPortForwarding.cs
+++ b/src/Jellyfin.Networking/PortForwardingHost.cs
@@ -1,7 +1,3 @@
-#nullable disable
-
-#pragma warning disable CS1591
-
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
@@ -12,36 +8,34 @@ using System.Threading.Tasks;
using MediaBrowser.Common.Net;
using MediaBrowser.Controller;
using MediaBrowser.Controller.Configuration;
-using MediaBrowser.Controller.Plugins;
+using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Mono.Nat;
namespace Jellyfin.Networking;
/// <summary>
-/// Server entrypoint handling external port forwarding.
+/// <see cref="IHostedService"/> responsible for UPnP port forwarding.
/// </summary>
-public sealed class ExternalPortForwarding : IServerEntryPoint
+public sealed class PortForwardingHost : IHostedService, IDisposable
{
private readonly IServerApplicationHost _appHost;
- private readonly ILogger<ExternalPortForwarding> _logger;
+ private readonly ILogger<PortForwardingHost> _logger;
private readonly IServerConfigurationManager _config;
+ private readonly ConcurrentDictionary<IPEndPoint, byte> _createdRules = new();
- private readonly ConcurrentDictionary<IPEndPoint, byte> _createdRules = new ConcurrentDictionary<IPEndPoint, byte>();
-
- private Timer _timer;
- private string _configIdentifier;
-
+ private Timer? _timer;
+ private string? _configIdentifier;
private bool _disposed;
/// <summary>
- /// Initializes a new instance of the <see cref="ExternalPortForwarding"/> class.
+ /// Initializes a new instance of the <see cref="PortForwardingHost"/> class.
/// </summary>
/// <param name="logger">The logger.</param>
/// <param name="appHost">The application host.</param>
/// <param name="config">The configuration manager.</param>
- public ExternalPortForwarding(
- ILogger<ExternalPortForwarding> logger,
+ public PortForwardingHost(
+ ILogger<PortForwardingHost> logger,
IServerApplicationHost appHost,
IServerConfigurationManager config)
{
@@ -66,7 +60,7 @@ public sealed class ExternalPortForwarding : IServerEntryPoint
.ToString();
}
- private void OnConfigurationUpdated(object sender, EventArgs e)
+ private void OnConfigurationUpdated(object? sender, EventArgs e)
{
var oldConfigIdentifier = _configIdentifier;
_configIdentifier = GetConfigIdentifier();
@@ -79,7 +73,7 @@ public sealed class ExternalPortForwarding : IServerEntryPoint
}
/// <inheritdoc />
- public Task RunAsync()
+ public Task StartAsync(CancellationToken cancellationToken)
{
Start();
@@ -88,6 +82,14 @@ public sealed class ExternalPortForwarding : IServerEntryPoint
return Task.CompletedTask;
}
+ /// <inheritdoc />
+ public Task StopAsync(CancellationToken cancellationToken)
+ {
+ Stop();
+
+ return Task.CompletedTask;
+ }
+
private void Start()
{
var config = _config.GetNetworkConfiguration();
@@ -101,7 +103,8 @@ public sealed class ExternalPortForwarding : IServerEntryPoint
NatUtility.DeviceFound += OnNatUtilityDeviceFound;
NatUtility.StartDiscovery();
- _timer = new Timer((_) => _createdRules.Clear(), null, TimeSpan.FromMinutes(10), TimeSpan.FromMinutes(10));
+ _timer?.Dispose();
+ _timer = new Timer(_ => _createdRules.Clear(), null, TimeSpan.FromMinutes(10), TimeSpan.FromMinutes(10));
}
private void Stop()
@@ -112,13 +115,23 @@ public sealed class ExternalPortForwarding : IServerEntryPoint
NatUtility.DeviceFound -= OnNatUtilityDeviceFound;
_timer?.Dispose();
+ _timer = null;
}
- private async void OnNatUtilityDeviceFound(object sender, DeviceEventArgs e)
+ private async void OnNatUtilityDeviceFound(object? sender, DeviceEventArgs e)
{
+ ObjectDisposedException.ThrowIf(_disposed, this);
+
try
{
- await CreateRules(e.Device).ConfigureAwait(false);
+ // On some systems the device discovered event seems to fire repeatedly
+ // This check will help ensure we're not trying to port map the same device over and over
+ if (!_createdRules.TryAdd(e.Device.DeviceEndpoint, 0))
+ {
+ return;
+ }
+
+ await Task.WhenAll(CreatePortMaps(e.Device)).ConfigureAwait(false);
}
catch (Exception ex)
{
@@ -126,20 +139,6 @@ public sealed class ExternalPortForwarding : IServerEntryPoint
}
}
- private Task CreateRules(INatDevice device)
- {
- ObjectDisposedException.ThrowIf(_disposed, this);
-
- // On some systems the device discovered event seems to fire repeatedly
- // This check will help ensure we're not trying to port map the same device over and over
- if (!_createdRules.TryAdd(device.DeviceEndpoint, 0))
- {
- return Task.CompletedTask;
- }
-
- return Task.WhenAll(CreatePortMaps(device));
- }
-
private IEnumerable<Task> CreatePortMaps(INatDevice device)
{
var config = _config.GetNetworkConfiguration();
@@ -185,8 +184,6 @@ public sealed class ExternalPortForwarding : IServerEntryPoint
_config.ConfigurationUpdated -= OnConfigurationUpdated;
- Stop();
-
_timer?.Dispose();
_timer = null;
diff --git a/tests/Jellyfin.Api.Tests/Controllers/SystemControllerTests.cs b/tests/Jellyfin.Api.Tests/Controllers/SystemControllerTests.cs
new file mode 100644
index 000000000..dd84c1a18
--- /dev/null
+++ b/tests/Jellyfin.Api.Tests/Controllers/SystemControllerTests.cs
@@ -0,0 +1,35 @@
+using Jellyfin.Api.Controllers;
+using MediaBrowser.Common.Net;
+using MediaBrowser.Controller;
+using MediaBrowser.Model.IO;
+using Microsoft.AspNetCore.Mvc;
+using Microsoft.Extensions.Logging;
+using Moq;
+using Xunit;
+
+namespace Jellyfin.Api.Tests.Controllers
+{
+ public class SystemControllerTests
+ {
+ [Fact]
+ public void GetLogFile_FileDoesNotExist_ReturnsNotFound()
+ {
+ var mockFileSystem = new Mock<IFileSystem>();
+ mockFileSystem
+ .Setup(fs => fs.GetFiles(It.IsAny<string>(), It.IsAny<bool>()))
+ .Returns([new() { Name = "file1.txt" }, new() { Name = "file2.txt" }]);
+
+ var controller = new SystemController(
+ Mock.Of<ILogger<SystemController>>(),
+ Mock.Of<IServerApplicationHost>(),
+ Mock.Of<IServerApplicationPaths>(),
+ mockFileSystem.Object,
+ Mock.Of<INetworkManager>(),
+ Mock.Of<ISystemManager>());
+
+ var result = controller.GetLogFile("DOES_NOT_EXIST.txt");
+
+ Assert.IsType<NotFoundObjectResult>(result);
+ }
+ }
+}
diff --git a/tests/Jellyfin.MediaEncoding.Tests/Probing/ProbeResultNormalizerTests.cs b/tests/Jellyfin.MediaEncoding.Tests/Probing/ProbeResultNormalizerTests.cs
index 344ac8971..020e20fb8 100644
--- a/tests/Jellyfin.MediaEncoding.Tests/Probing/ProbeResultNormalizerTests.cs
+++ b/tests/Jellyfin.MediaEncoding.Tests/Probing/ProbeResultNormalizerTests.cs
@@ -46,6 +46,8 @@ namespace Jellyfin.MediaEncoding.Tests.Probing
var internalMediaInfoResult = JsonSerializer.Deserialize<InternalMediaInfoResult>(bytes, _jsonOptions);
MediaInfo res = _probeResultNormalizer.GetMediaInfo(internalMediaInfoResult, VideoType.VideoFile, false, "Test Data/Probing/video_metadata.mkv", MediaProtocol.File);
+ Assert.Equal("mkv", res.Container);
+
Assert.Equal(3, res.MediaStreams.Count);
Assert.NotNull(res.VideoStream);
@@ -178,6 +180,21 @@ namespace Jellyfin.MediaEncoding.Tests.Probing
}
[Fact]
+ public void GetMediaInfo_WebM_Success()
+ {
+ var bytes = File.ReadAllBytes("Test Data/Probing/video_webm.json");
+ var internalMediaInfoResult = JsonSerializer.Deserialize<InternalMediaInfoResult>(bytes, _jsonOptions);
+
+ MediaInfo res = _probeResultNormalizer.GetMediaInfo(internalMediaInfoResult, VideoType.VideoFile, false, "Test Data/Probing/video_metadata.webm", MediaProtocol.File);
+
+ Assert.Equal("mkv,webm", res.Container);
+
+ Assert.Equal(2, res.MediaStreams.Count);
+
+ Assert.False(res.MediaStreams[0].IsAVC);
+ }
+
+ [Fact]
public void GetMediaInfo_ProgressiveVideoNoFieldOrder_Success()
{
var bytes = File.ReadAllBytes("Test Data/Probing/video_progressive_no_field_order.json");
diff --git a/tests/Jellyfin.MediaEncoding.Tests/Test Data/Probing/video_webm.json b/tests/Jellyfin.MediaEncoding.Tests/Test Data/Probing/video_webm.json
new file mode 100644
index 000000000..4cc7db80d
--- /dev/null
+++ b/tests/Jellyfin.MediaEncoding.Tests/Test Data/Probing/video_webm.json
@@ -0,0 +1,106 @@
+{
+ "streams": [
+ {
+ "index": 0,
+ "codec_name": "vp8",
+ "codec_long_name": "On2 VP8",
+ "profile": "1",
+ "codec_type": "video",
+ "codec_tag_string": "[0][0][0][0]",
+ "codec_tag": "0x0000",
+ "width": 540,
+ "height": 360,
+ "coded_width": 540,
+ "coded_height": 360,
+ "closed_captions": 0,
+ "film_grain": 0,
+ "has_b_frames": 0,
+ "sample_aspect_ratio": "1:1",
+ "display_aspect_ratio": "3:2",
+ "pix_fmt": "yuv420p",
+ "level": -99,
+ "field_order": "progressive",
+ "refs": 1,
+ "r_frame_rate": "2997/125",
+ "avg_frame_rate": "2997/125",
+ "time_base": "1/1000",
+ "start_pts": 0,
+ "start_time": "0.000000",
+ "disposition": {
+ "default": 1,
+ "dub": 0,
+ "original": 0,
+ "comment": 0,
+ "lyrics": 0,
+ "karaoke": 0,
+ "forced": 0,
+ "hearing_impaired": 0,
+ "visual_impaired": 0,
+ "clean_effects": 0,
+ "attached_pic": 0,
+ "timed_thumbnails": 0,
+ "captions": 0,
+ "descriptions": 0,
+ "metadata": 0,
+ "dependent": 0,
+ "still_image": 0
+ },
+ "tags": {
+ "language": "eng"
+ }
+ },
+ {
+ "index": 1,
+ "codec_name": "vorbis",
+ "codec_long_name": "Vorbis",
+ "codec_type": "audio",
+ "codec_tag_string": "[0][0][0][0]",
+ "codec_tag": "0x0000",
+ "sample_fmt": "fltp",
+ "sample_rate": "44100",
+ "channels": 1,
+ "channel_layout": "mono",
+ "bits_per_sample": 0,
+ "r_frame_rate": "0/0",
+ "avg_frame_rate": "0/0",
+ "time_base": "1/1000",
+ "start_pts": 0,
+ "start_time": "0.000000",
+ "extradata_size": 3097,
+ "disposition": {
+ "default": 1,
+ "dub": 0,
+ "original": 0,
+ "comment": 0,
+ "lyrics": 0,
+ "karaoke": 0,
+ "forced": 0,
+ "hearing_impaired": 0,
+ "visual_impaired": 0,
+ "clean_effects": 0,
+ "attached_pic": 0,
+ "timed_thumbnails": 0,
+ "captions": 0,
+ "descriptions": 0,
+ "metadata": 0,
+ "dependent": 0,
+ "still_image": 0
+ },
+ "tags": {
+ "language": "eng"
+ }
+ }
+ ],
+ "format": {
+ "filename": "sample.webm",
+ "nb_streams": 2,
+ "nb_programs": 0,
+ "format_name": "matroska,webm",
+ "format_long_name": "Matroska / WebM",
+ "start_time": "0.000000",
+ "duration": "117.700914",
+ "size": "8566268",
+ "bit_rate": "582239",
+ "probe_score": 100
+ }
+}
diff --git a/tests/Jellyfin.Model.Tests/Dlna/StreamBuilderTests.cs b/tests/Jellyfin.Model.Tests/Dlna/StreamBuilderTests.cs
index 2f84fa544..d9dceee55 100644
--- a/tests/Jellyfin.Model.Tests/Dlna/StreamBuilderTests.cs
+++ b/tests/Jellyfin.Model.Tests/Dlna/StreamBuilderTests.cs
@@ -28,7 +28,7 @@ namespace Jellyfin.Model.Tests
[InlineData("Chrome", "mp4-hevc-aac-srt-15200k", PlayMethod.Transcode, TranscodeReason.VideoCodecNotSupported, "Transcode")]
[InlineData("Chrome", "mp4-hevc-ac3-aac-srt-15200k", PlayMethod.Transcode, TranscodeReason.VideoCodecNotSupported | TranscodeReason.SecondaryAudioNotSupported, "Transcode")]
[InlineData("Chrome", "mkv-vp9-aac-srt-2600k", PlayMethod.DirectStream, TranscodeReason.ContainerNotSupported, "Remux")] // #6450
- [InlineData("Chrome", "mkv-vp9-ac3-srt-2600k", PlayMethod.DirectStream, TranscodeReason.AudioCodecNotSupported)] // #6450
+ [InlineData("Chrome", "mkv-vp9-ac3-srt-2600k", PlayMethod.DirectStream, TranscodeReason.ContainerNotSupported | TranscodeReason.AudioCodecNotSupported)] // #6450
[InlineData("Chrome", "mkv-vp9-vorbis-vtt-2600k", PlayMethod.DirectPlay, (TranscodeReason)0, "Remux")] // #6450
// Firefox
[InlineData("Firefox", "mp4-h264-aac-vtt-2600k", PlayMethod.DirectPlay)] // #6450
@@ -39,7 +39,7 @@ namespace Jellyfin.Model.Tests
[InlineData("Firefox", "mp4-hevc-aac-srt-15200k", PlayMethod.Transcode, TranscodeReason.VideoCodecNotSupported, "Transcode")]
[InlineData("Firefox", "mp4-hevc-ac3-aac-srt-15200k", PlayMethod.Transcode, TranscodeReason.VideoCodecNotSupported | TranscodeReason.SecondaryAudioNotSupported, "Transcode")]
[InlineData("Firefox", "mkv-vp9-aac-srt-2600k", PlayMethod.DirectStream, TranscodeReason.ContainerNotSupported, "Remux")] // #6450
- [InlineData("Firefox", "mkv-vp9-ac3-srt-2600k", PlayMethod.DirectStream, TranscodeReason.AudioCodecNotSupported)] // #6450
+ [InlineData("Firefox", "mkv-vp9-ac3-srt-2600k", PlayMethod.DirectStream, TranscodeReason.ContainerNotSupported | TranscodeReason.AudioCodecNotSupported)] // #6450
[InlineData("Firefox", "mkv-vp9-vorbis-vtt-2600k", PlayMethod.DirectPlay, (TranscodeReason)0, "Remux")] // #6450
// Safari
[InlineData("SafariNext", "mp4-h264-aac-vtt-2600k", PlayMethod.DirectPlay)] // #6450
@@ -90,7 +90,7 @@ namespace Jellyfin.Model.Tests
[InlineData("Chrome-NoHLS", "mp4-hevc-aac-srt-15200k", PlayMethod.Transcode, TranscodeReason.VideoCodecNotSupported, "Transcode", "http")]
[InlineData("Chrome-NoHLS", "mp4-hevc-ac3-aac-srt-15200k", PlayMethod.Transcode, TranscodeReason.VideoCodecNotSupported | TranscodeReason.SecondaryAudioNotSupported, "Transcode", "http")]
[InlineData("Chrome-NoHLS", "mkv-vp9-aac-srt-2600k", PlayMethod.DirectStream, TranscodeReason.ContainerNotSupported, "Remux")] // #6450
- [InlineData("Chrome-NoHLS", "mkv-vp9-ac3-srt-2600k", PlayMethod.DirectStream, TranscodeReason.AudioCodecNotSupported)] // #6450
+ [InlineData("Chrome-NoHLS", "mkv-vp9-ac3-srt-2600k", PlayMethod.DirectStream, TranscodeReason.ContainerNotSupported | TranscodeReason.AudioCodecNotSupported)] // #6450
[InlineData("Chrome-NoHLS", "mkv-vp9-vorbis-vtt-2600k", PlayMethod.DirectPlay, (TranscodeReason)0, "Remux")] // #6450
// TranscodeMedia
[InlineData("TranscodeMedia", "mp4-h264-aac-vtt-2600k", PlayMethod.Transcode, TranscodeReason.DirectPlayError, "Remux", "HLS.mp4")]
@@ -178,7 +178,7 @@ namespace Jellyfin.Model.Tests
[InlineData("Chrome", "mp4-hevc-aac-srt-15200k", PlayMethod.Transcode, TranscodeReason.VideoCodecNotSupported, "Transcode")]
[InlineData("Chrome", "mp4-hevc-ac3-aac-srt-15200k", PlayMethod.Transcode, TranscodeReason.VideoCodecNotSupported | TranscodeReason.AudioCodecNotSupported, "Transcode")]
[InlineData("Chrome", "mkv-vp9-aac-srt-2600k", PlayMethod.DirectStream, TranscodeReason.ContainerNotSupported, "Remux")] // #6450
- [InlineData("Chrome", "mkv-vp9-ac3-srt-2600k", PlayMethod.DirectStream, TranscodeReason.AudioCodecNotSupported)] // #6450
+ [InlineData("Chrome", "mkv-vp9-ac3-srt-2600k", PlayMethod.DirectStream, TranscodeReason.ContainerNotSupported | TranscodeReason.AudioCodecNotSupported)] // #6450
[InlineData("Chrome", "mkv-vp9-vorbis-vtt-2600k", PlayMethod.DirectPlay, (TranscodeReason)0, "Remux")] // #6450
// Firefox
[InlineData("Firefox", "mp4-h264-aac-vtt-2600k", PlayMethod.DirectPlay)] // #6450
@@ -188,7 +188,7 @@ namespace Jellyfin.Model.Tests
[InlineData("Firefox", "mp4-hevc-aac-srt-15200k", PlayMethod.Transcode, TranscodeReason.VideoCodecNotSupported, "Transcode")]
[InlineData("Firefox", "mp4-hevc-ac3-aac-srt-15200k", PlayMethod.Transcode, TranscodeReason.VideoCodecNotSupported | TranscodeReason.AudioCodecNotSupported, "Transcode")]
[InlineData("Firefox", "mkv-vp9-aac-srt-2600k", PlayMethod.DirectStream, TranscodeReason.ContainerNotSupported, "Remux")] // #6450
- [InlineData("Firefox", "mkv-vp9-ac3-srt-2600k", PlayMethod.DirectStream, TranscodeReason.AudioCodecNotSupported)] // #6450
+ [InlineData("Firefox", "mkv-vp9-ac3-srt-2600k", PlayMethod.DirectStream, TranscodeReason.ContainerNotSupported | TranscodeReason.AudioCodecNotSupported)] // #6450
[InlineData("Firefox", "mkv-vp9-vorbis-vtt-2600k", PlayMethod.DirectPlay, (TranscodeReason)0, "Remux")] // #6450
// Safari
[InlineData("SafariNext", "mp4-h264-aac-vtt-2600k", PlayMethod.DirectPlay)] // #6450
diff --git a/tests/Jellyfin.Model.Tests/Net/MimeTypesTests.cs b/tests/Jellyfin.Model.Tests/Net/MimeTypesTests.cs
index 371c3811a..a18a85ec0 100644
--- a/tests/Jellyfin.Model.Tests/Net/MimeTypesTests.cs
+++ b/tests/Jellyfin.Model.Tests/Net/MimeTypesTests.cs
@@ -6,6 +6,11 @@ namespace Jellyfin.Model.Tests.Net
public class MimeTypesTests
{
[Theory]
+ [InlineData(".cb7", "application/x-cb7")]
+ [InlineData(".cba", "application/x-cba")]
+ [InlineData(".cbr", "application/vnd.comicbook-rar")]
+ [InlineData(".cbt", "application/x-cbt")]
+ [InlineData(".cbz", "application/vnd.comicbook+zip")]
[InlineData(".dll", "application/octet-stream")]
[InlineData(".log", "text/plain")]
[InlineData(".srt", "application/x-subrip")]
@@ -69,7 +74,7 @@ namespace Jellyfin.Model.Tests.Net
[InlineData(".dsp", "audio/dsp")]
[InlineData(".flac", "audio/flac")]
[InlineData(".m4a", "audio/mp4")]
- [InlineData(".m4b", "audio/m4b")]
+ [InlineData(".m4b", "audio/mp4")]
[InlineData(".mid", "audio/midi")]
[InlineData(".midi", "audio/midi")]
[InlineData(".mp3", "audio/mpeg")]
@@ -94,10 +99,16 @@ namespace Jellyfin.Model.Tests.Net
[InlineData("application/pdf", ".pdf")]
[InlineData("application/ttml+xml", ".ttml")]
[InlineData("application/vnd.amazon.ebook", ".azw")]
+ [InlineData("application/vnd.comicbook-rar", ".cbr")]
+ [InlineData("application/vnd.comicbook+zip", ".cbz")]
[InlineData("application/vnd.ms-fontobject", ".eot")]
[InlineData("application/vnd.rar", ".rar")]
[InlineData("application/wasm", ".wasm")]
[InlineData("application/x-7z-compressed", ".7z")]
+ [InlineData("application/x-cb7", ".cb7")]
+ [InlineData("application/x-cba", ".cba")]
+ [InlineData("application/x-cbr", ".cbr")]
+ [InlineData("application/x-cbt", ".cbt")]
[InlineData("application/x-cbz", ".cbz")]
[InlineData("application/x-javascript", ".js")]
[InlineData("application/x-mobipocket-ebook", ".mobi")]
diff --git a/tests/Jellyfin.Model.Tests/Test Data/MediaSourceInfo-mkv-av1-aac-srt-2600k.json b/tests/Jellyfin.Model.Tests/Test Data/MediaSourceInfo-mkv-av1-aac-srt-2600k.json
index da185aacf..e528281bd 100644
--- a/tests/Jellyfin.Model.Tests/Test Data/MediaSourceInfo-mkv-av1-aac-srt-2600k.json
+++ b/tests/Jellyfin.Model.Tests/Test Data/MediaSourceInfo-mkv-av1-aac-srt-2600k.json
@@ -1,7 +1,7 @@
{
"Id": "a766d122b58e45d9492d17af66748bf5",
"Path": "/Media/MyVideo-720p.mkv",
- "Container": "mkv,webm",
+ "Container": "mkv",
"Size": 835317696,
"Name": "MyVideo-1080p",
"ETag": "579a34c6d5dfb23f61539a51220b6a23",
diff --git a/tests/Jellyfin.Model.Tests/Test Data/MediaSourceInfo-mkv-vp9-aac-srt-2600k.json b/tests/Jellyfin.Model.Tests/Test Data/MediaSourceInfo-mkv-vp9-aac-srt-2600k.json
index 0a85a1353..8ef10ae87 100644
--- a/tests/Jellyfin.Model.Tests/Test Data/MediaSourceInfo-mkv-vp9-aac-srt-2600k.json
+++ b/tests/Jellyfin.Model.Tests/Test Data/MediaSourceInfo-mkv-vp9-aac-srt-2600k.json
@@ -1,7 +1,7 @@
{
"Id": "a766d122b58e45d9492d17af66748bf5",
"Path": "/Media/MyVideo-720p.mkv",
- "Container": "mkv,webm",
+ "Container": "mkv",
"Size": 835317696,
"Name": "MyVideo-1080p",
"ETag": "579a34c6d5dfb23f61539a51220b6a23",
diff --git a/tests/Jellyfin.Model.Tests/Test Data/MediaSourceInfo-mkv-vp9-ac3-srt-2600k.json b/tests/Jellyfin.Model.Tests/Test Data/MediaSourceInfo-mkv-vp9-ac3-srt-2600k.json
index 2b932ff52..80a9f4103 100644
--- a/tests/Jellyfin.Model.Tests/Test Data/MediaSourceInfo-mkv-vp9-ac3-srt-2600k.json
+++ b/tests/Jellyfin.Model.Tests/Test Data/MediaSourceInfo-mkv-vp9-ac3-srt-2600k.json
@@ -1,7 +1,7 @@
{
"Id": "a766d122b58e45d9492d17af66748bf5",
"Path": "/Media/MyVideo-720p.mkv",
- "Container": "mkv,webm",
+ "Container": "mkv",
"Size": 835317696,
"Name": "MyVideo-1080p",
"ETag": "579a34c6d5dfb23f61539a51220b6a23",