From f9bd2451585e3823b5b5a56d9c782bf7a95f0acd Mon Sep 17 00:00:00 2001 From: Timothy Date: Mon, 20 Jul 2026 22:38:28 +0200 Subject: [PATCH 1/2] fix(502): render the on-screen bug for external-URL channel logos MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A channel whose logo is an external URL never rendered a watermark, even with an ImageSource=ChannelLogo watermark attached. WatermarkSelector resolved the URL correctly and then existence-checked it on the filesystem — File.Exists("https://…") is always false — so all three precedence levels (playout item, channel, global) logged "Channel logo no longer exists" and returned None. The channel editor advertises the URL as winning over an uploaded logo, which was true for the guide listing and silently false for the bug. External artwork passes through rather than being downloaded into the image cache: that is already the convention everywhere else (M3U, XMLTV, SPA JSON all emit the raw URL), no fetch->SaveArtworkToCache glue exists, and the render path does not need it — ImageElementBase.LoadImage already fetches an http(s) path with HttpClient and decodes it for real pixel dimensions. A remote-URL watermark is therefore forced onto the graphics engine instead of the ffmpeg-native shortcut, which would otherwise hand the URL to ffprobe and ffmpeg as a bare -i argument, putting an unbounded network fetch inside stream startup. The three gated precedence levels now share one ChannelLogoWatermarkOptions helper — the triplicated block is what let the defect exist three times over. Scope held narrow: the generated-initials localhost fallback (#1) stays disabled behind an explicit comment and a scope-guard test, and the deco path keeps its own long-standing unchecked policy. Verified by live-E2E against a real channel playout with an external-URL logo: origin/main renders 0 logo pixels and logs the "no longer exists" warning verbatim; this branch renders the logo in the expected region. Whitespace-only reformatting in FFmpegLibraryProcessService.cs is the fix-as-you-touch format gate on pre-existing violations, plus a BOM strip. fixes #502 --- .../WatermarkSelectorChannelLogoTests.cs | 189 ++++++++++++++++++ .../FFmpeg/FFmpegLibraryProcessService.cs | 9 +- ErsatzTV.Core/FFmpeg/WatermarkSelector.cs | 103 +++++----- docs/decisions.md | 41 ++++ 4 files changed, 283 insertions(+), 59 deletions(-) create mode 100644 ErsatzTV.Core.Tests/FFmpeg/WatermarkSelectorChannelLogoTests.cs diff --git a/ErsatzTV.Core.Tests/FFmpeg/WatermarkSelectorChannelLogoTests.cs b/ErsatzTV.Core.Tests/FFmpeg/WatermarkSelectorChannelLogoTests.cs new file mode 100644 index 000000000..9728b40b9 --- /dev/null +++ b/ErsatzTV.Core.Tests/FFmpeg/WatermarkSelectorChannelLogoTests.cs @@ -0,0 +1,189 @@ +using ErsatzTV.Core.Domain; +using ErsatzTV.Core.FFmpeg; +using ErsatzTV.Core.Interfaces.FFmpeg; +using ErsatzTV.Core.Interfaces.Images; +using Microsoft.Extensions.Logging.Abstractions; +using NSubstitute; +using NUnit.Framework; +using Shouldly; +using Testably.Abstractions.Testing; + +namespace ErsatzTV.Core.Tests.FFmpeg; + +/// +/// Covers resolution at all three watermark +/// precedence levels (playout item, channel, global). The shared fixture in +/// deliberately makes every watermark file exist, so it cannot +/// express the "logo is an external URL" or "logo file is gone" cases this fixture exists for (#502). +/// +[TestFixture] +public class WatermarkSelectorChannelLogoTests +{ + private const string ExternalLogoUrl = "https://cdn.example.com/logos/channel.png"; + private const string LocalLogoPath = "abc123.png"; + private const string LocalLogoCachePath = "/cache/logos/ab/abc123.png"; + + private WatermarkSelector _selector; + + [SetUp] + public void SetUp() + { + var mockFileSystem = new MockFileSystem(); + mockFileSystem.Initialize().WithFile(LocalLogoCachePath); + + var fakeImageCache = Substitute.For(); + fakeImageCache.GetPathForImage(Arg.Any(), Arg.Is(ArtworkKind.Logo), Arg.Any>()) + .Returns(_ => LocalLogoCachePath); + + _selector = new WatermarkSelector( + mockFileSystem, + fakeImageCache, + Substitute.For(), + NullLogger.Instance); + } + + private static ChannelWatermark ChannelLogoWatermark(int id, string name) => + new() + { + Id = id, + Name = name, + ImageSource = ChannelWatermarkImageSource.ChannelLogo, + Mode = ChannelWatermarkMode.Permanent + }; + + private static Channel ChannelWithLogo(string logoPath, ChannelWatermark channelWatermark = null) + { + var channel = new Channel(Guid.Empty) + { + Id = 1, + Number = "1", + Name = "Test", + StreamingMode = StreamingMode.TransportStream, + Artwork = [], + Watermark = channelWatermark, + WatermarkId = channelWatermark?.Id + }; + + if (logoPath is not null) + { + channel.Artwork.Add(new Artwork { ArtworkKind = ArtworkKind.Logo, Path = logoPath }); + } + + return channel; + } + + // ---- external URL logo: the #502 defect ---------------------------------------------------- + + [Test] + public void PlayoutItemWatermark_Should_Use_External_Url_Channel_Logo() + { + ChannelWatermark watermark = ChannelLogoWatermark(1, "PlayoutItem"); + Channel channel = ChannelWithLogo(ExternalLogoUrl); + + Option result = _selector.GetWatermarkOptions( + channel, + watermark, + Option.None); + + result.IsSome.ShouldBeTrue(); + WatermarkOptions options = result.IfNone(() => throw new InvalidOperationException()); + options.ImagePath.ShouldBe(ExternalLogoUrl); + options.Watermark.ShouldBe(watermark); + } + + [Test] + public void ChannelWatermark_Should_Use_External_Url_Channel_Logo() + { + ChannelWatermark watermark = ChannelLogoWatermark(2, "Channel"); + Channel channel = ChannelWithLogo(ExternalLogoUrl, watermark); + + Option result = _selector.GetWatermarkOptions( + channel, + Option.None, + Option.None); + + result.IsSome.ShouldBeTrue(); + WatermarkOptions options = result.IfNone(() => throw new InvalidOperationException()); + options.ImagePath.ShouldBe(ExternalLogoUrl); + options.Watermark.ShouldBe(watermark); + } + + [Test] + public void GlobalWatermark_Should_Use_External_Url_Channel_Logo() + { + ChannelWatermark watermark = ChannelLogoWatermark(3, "Global"); + Channel channel = ChannelWithLogo(ExternalLogoUrl); + + Option result = _selector.GetWatermarkOptions( + channel, + Option.None, + watermark); + + result.IsSome.ShouldBeTrue(); + WatermarkOptions options = result.IfNone(() => throw new InvalidOperationException()); + options.ImagePath.ShouldBe(ExternalLogoUrl); + options.Watermark.ShouldBe(watermark); + } + + // ---- regressions: local-file behavior must not change --------------------------------------- + + [Test] + public void ChannelWatermark_Should_Use_Cached_Path_For_Local_Channel_Logo() + { + ChannelWatermark watermark = ChannelLogoWatermark(2, "Channel"); + Channel channel = ChannelWithLogo(LocalLogoPath, watermark); + + Option result = _selector.GetWatermarkOptions( + channel, + Option.None, + Option.None); + + result.IsSome.ShouldBeTrue(); + result.IfNone(() => throw new InvalidOperationException()).ImagePath.ShouldBe(LocalLogoCachePath); + } + + [Test] + public void ChannelWatermark_Should_Be_Ignored_When_Local_Channel_Logo_File_Is_Missing() + { + var mockFileSystem = new MockFileSystem(); // nothing on disk + var fakeImageCache = Substitute.For(); + fakeImageCache.GetPathForImage(Arg.Any(), Arg.Is(ArtworkKind.Logo), Arg.Any>()) + .Returns(_ => LocalLogoCachePath); + + var selector = new WatermarkSelector( + mockFileSystem, + fakeImageCache, + Substitute.For(), + NullLogger.Instance); + + ChannelWatermark watermark = ChannelLogoWatermark(2, "Channel"); + Channel channel = ChannelWithLogo(LocalLogoPath, watermark); + + Option result = selector.GetWatermarkOptions( + channel, + Option.None, + Option.None); + + result.IsNone.ShouldBeTrue(); + } + + /// + /// Scope guard for #502: with no logo artwork at all, the resolved path is the generated-initials + /// URL from , which hardcodes + /// localhost (issue #1). That fallback stays disabled here — reviving it is deliberately deferred + /// in docs/decisions.md and is not part of this fix. + /// + [Test] + public void ChannelWatermark_Should_Be_Ignored_When_Channel_Has_No_Logo_Artwork() + { + ChannelWatermark watermark = ChannelLogoWatermark(2, "Channel"); + Channel channel = ChannelWithLogo(null, watermark); + + Option result = _selector.GetWatermarkOptions( + channel, + Option.None, + Option.None); + + result.IsNone.ShouldBeTrue(); + } +} diff --git a/ErsatzTV.Core/FFmpeg/FFmpegLibraryProcessService.cs b/ErsatzTV.Core/FFmpeg/FFmpegLibraryProcessService.cs index f9c729b69..c2048d8be 100644 --- a/ErsatzTV.Core/FFmpeg/FFmpegLibraryProcessService.cs +++ b/ErsatzTV.Core/FFmpeg/FFmpegLibraryProcessService.cs @@ -379,8 +379,13 @@ public class FFmpegLibraryProcessService : IFFmpegProcessService Option graphicsEngineContext = Option.None; List graphicsElementContexts = []; - // use ffmpeg for single permanent watermark, graphics engine for all others - if (graphicsElements.Count == 0 && watermarks.Count == 1 && watermarks.All(wm => wm.Watermark.Mode is ChannelWatermarkMode.Permanent)) + // use ffmpeg for single permanent watermark, graphics engine for all others. + // a remote-URL watermark always takes the graphics engine (#502): that path fetches the image with + // HttpClient and reads its real dimensions, whereas this one would hand the URL to ffprobe and + // ffmpeg as a bare -i argument, putting an unbounded network fetch inside stream startup. + if (graphicsElements.Count == 0 && watermarks.Count == 1 + && watermarks.All(wm => wm.Watermark.Mode is ChannelWatermarkMode.Permanent) + && watermarks.All(wm => !Artwork.IsExternalUrl(wm.ImagePath))) { foreach (var wm in watermarks) { diff --git a/ErsatzTV.Core/FFmpeg/WatermarkSelector.cs b/ErsatzTV.Core/FFmpeg/WatermarkSelector.cs index 6519860c6..de760bccf 100644 --- a/ErsatzTV.Core/FFmpeg/WatermarkSelector.cs +++ b/ErsatzTV.Core/FFmpeg/WatermarkSelector.cs @@ -216,25 +216,7 @@ public class WatermarkSelector( case ChannelWatermarkImageSource.ChannelLogo: logger.LogDebug("Watermark will come from playout item (channel logo)"); - string channelPath = ChannelLogoGenerator.GenerateChannelLogoUrl(channel); - Option maybeLogoArtwork = - Optional(channel.Artwork.Find(a => a.ArtworkKind == ArtworkKind.Logo)); - foreach (var logoArtwork in maybeLogoArtwork) - { - channelPath = Artwork.IsExternalUrl(logoArtwork.Path) - ? logoArtwork.Path - : imageCache.GetPathForImage(logoArtwork.Path, ArtworkKind.Logo, Option.None); - } - - if (fileSystem.File.Exists(channelPath)) - { - return new WatermarkOptions(watermark, channelPath, None); - } - - logger.LogWarning( - "Channel logo no longer exists at {Path} and will be ignored", - channelPath); - return None; + return ChannelLogoWatermarkOptions(channel, watermark); default: throw new NotSupportedException("Unsupported watermark image source"); } @@ -265,25 +247,7 @@ public class WatermarkSelector( case ChannelWatermarkImageSource.ChannelLogo: logger.LogDebug("Watermark will come from channel (channel logo)"); - string channelPath = ChannelLogoGenerator.GenerateChannelLogoUrl(channel); - Option maybeLogoArtwork = - Optional(channel.Artwork.Find(a => a.ArtworkKind == ArtworkKind.Logo)); - foreach (var logoArtwork in maybeLogoArtwork) - { - channelPath = Artwork.IsExternalUrl(logoArtwork.Path) - ? logoArtwork.Path - : imageCache.GetPathForImage(logoArtwork.Path, ArtworkKind.Logo, Option.None); - } - - if (fileSystem.File.Exists(channelPath)) - { - return new WatermarkOptions(channel.Watermark, channelPath, None); - } - - logger.LogWarning( - "Channel logo no longer exists at {Path} and will be ignored", - channelPath); - return None; + return ChannelLogoWatermarkOptions(channel, channel.Watermark); default: throw new NotSupportedException("Unsupported watermark image source"); } @@ -314,25 +278,7 @@ public class WatermarkSelector( case ChannelWatermarkImageSource.ChannelLogo: logger.LogDebug("Watermark will come from global (channel logo)"); - string channelPath = ChannelLogoGenerator.GenerateChannelLogoUrl(channel); - Option maybeLogoArtwork = - Optional(channel.Artwork.Find(a => a.ArtworkKind == ArtworkKind.Logo)); - foreach (var logoArtwork in maybeLogoArtwork) - { - channelPath = Artwork.IsExternalUrl(logoArtwork.Path) - ? logoArtwork.Path - : imageCache.GetPathForImage(logoArtwork.Path, ArtworkKind.Logo, Option.None); - } - - if (fileSystem.File.Exists(channelPath)) - { - return new WatermarkOptions(watermark, channelPath, None); - } - - logger.LogWarning( - "Channel logo no longer exists at {Path} and will be ignored", - channelPath); - return None; + return ChannelLogoWatermarkOptions(channel, watermark); default: throw new NotSupportedException("Unsupported watermark image source"); } @@ -341,6 +287,45 @@ public class WatermarkSelector( return Option.None; } + /// + /// Resolves a watermark to a renderable path, + /// shared by the playout-item, channel and global precedence levels so all three agree. + /// + /// + /// An external-URL logo has no local file, so it must not be existence-checked: the branding tab + /// advertises the URL as winning, but File.Exists("https://…") is always false, which silently + /// dropped the bug for every such channel (#502). External URLs are handed downstream as-is, matching + /// how every other consumer treats external artwork (M3U, XMLTV, SPA JSON all emit the raw URL); + /// ImageElementBase.LoadImage fetches it over http when compositing. + /// + private Option ChannelLogoWatermarkOptions(Channel channel, ChannelWatermark watermark) + { + foreach (var logoArtwork in Optional(channel.Artwork.Find(a => a.ArtworkKind == ArtworkKind.Logo))) + { + if (Artwork.IsExternalUrl(logoArtwork.Path)) + { + return new WatermarkOptions(watermark, logoArtwork.Path, None); + } + + string cachedPath = imageCache.GetPathForImage(logoArtwork.Path, ArtworkKind.Logo, Option.None); + if (fileSystem.File.Exists(cachedPath)) + { + return new WatermarkOptions(watermark, cachedPath, None); + } + + logger.LogWarning("Channel logo no longer exists at {Path} and will be ignored", cachedPath); + return None; + } + + // with no logo artwork the only candidate is the generated-initials image, whose URL hardcodes + // localhost (ChannelLogoGenerator.GenerateChannelLogoUrl, issue #1). It has never rendered here and + // reviving it is deliberately deferred in docs/decisions.md, so it stays ignored. + logger.LogWarning( + "Channel logo no longer exists at {Path} and will be ignored", + ChannelLogoGenerator.GenerateChannelLogoUrl(channel)); + return None; + } + private List OptionsForWatermarks(Channel channel, IEnumerable watermarks) { var result = new List(); @@ -382,6 +367,10 @@ public class WatermarkSelector( customPath, None); case ChannelWatermarkImageSource.ChannelLogo: + // deliberately NOT ChannelLogoWatermarkOptions: the deco path has always passed its + // resolved path through unchecked, so it already honored external-URL logos and #502 does + // not apply here. Aligning its missing-file / no-artwork policy with the three precedence + // levels above is a behavior change beyond this fix — tracked separately. string channelPath = ChannelLogoGenerator.GenerateChannelLogoUrl(channel); Option maybeLogoArtwork = Optional(channel.Artwork.Find(a => a.ArtworkKind == ArtworkKind.Logo)); diff --git a/docs/decisions.md b/docs/decisions.md index 68323d5e4..2c4b7643c 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -102,6 +102,7 @@ in-file entries. - [2026-07-19 — WeightedShuffle SPA: weights edited on the multi-collection, order offered only on classic MultiCollection schedule items; fair-share is a reset not a mode (#404)](#2026-07-19--weightedshuffle-spa-weights-edited-on-the-multi-collection-order-offered-only-on-classic-multicollection-schedule-items-fair-share-is-a-reset-not-a-mode-404) - [2026-07-19 — Health-check results are TTL-cached; `?refresh=true` forces a fresh run (#431)](#2026-07-19--health-check-results-are-ttl-cached-refreshtrue-forces-a-fresh-run-431) - [2026-07-19 — CI `test` job reports a sampled true peak-anon, not cache-inflated `memory.peak` (#412)](#2026-07-19--ci-test-job-reports-a-sampled-true-peak-anon-not-cache-inflated-memorypeak-412) +- [2026-07-20 — External-URL channel logos pass through to the graphics engine; never `File.Exists`-gated, never ffmpeg-native (#502)](#2026-07-20--external-url-channel-logos-pass-through-to-the-graphics-engine-never-fileexists-gated-never-ffmpeg-native-502) --- @@ -2466,3 +2467,43 @@ ErsatzTV. Full design: `docs/superpowers/specs/2026-07-20-qsv-native-decode-desi - **#574's skip-task queueing does not return** by moving `build` back to `ubuntu-latest`: `needs: [test, migrations]` means it cannot be dispatched until the jobs it would have queued behind have already finished. + +## 2026-07-20 — External-URL channel logos pass through to the graphics engine; never `File.Exists`-gated, never ffmpeg-native (#502) + +A channel whose logo is an **external URL** never rendered an on-screen bug, even with a +`ImageSource = ChannelLogo` watermark attached. `WatermarkSelector` resolved the URL correctly and then +existence-checked it on the filesystem — `File.Exists("https://…")` is always false — so all three +precedence levels (playout item, channel, global) logged *"Channel logo no longer exists"* and returned +`None`. The channel editor advertises the URL as winning over an uploaded logo, which is true for the +guide listing and was silently false for the bug. + +**External artwork passes through; it is not downloaded into the image cache.** That is already the +codebase-wide convention — `ChannelPlaylist` (M3U), the XMLTV template data and `Channels/Mapper` +(SPA JSON) all emit the raw URL and let the client fetch it. No fetch→`SaveArtworkToCache` glue exists +anywhere, and adding it here would have invented a second convention for one consumer. The render path +needs no such glue: `ImageElementBase.LoadImage` already detects an `http(s)` path, fetches it with +`HttpClient`, and decodes it with ImageSharp for real pixel dimensions. + +**A remote-URL watermark is therefore forced onto the graphics engine, not the ffmpeg-native path.** +`FFmpegLibraryProcessService` normally shortcuts a single permanent watermark into a `WatermarkInputFile` +handed to ffmpeg as a bare `-i` argument (and to `ffprobe` for animation detection). ffmpeg would likely +open an http URL itself, but that puts an unbounded network fetch *inside stream startup*, with no +timeout, redirect or auth handling under our control, and with dimensions left as a `FrameSize(1, 1)` +placeholder. The graphics engine is the path actually built for remote images, so the shortcut now +additionally requires a non-URL path. + +**Scope held deliberately narrow — two adjacent defects were left alone:** + +- The **generated-initials fallback** (no logo artwork ⇒ `ChannelLogoGenerator.GenerateChannelLogoUrl`, + which hardcodes `localhost`, issue #1) is *also* killed by the same `File.Exists`. Reviving it is + deferred by an earlier entry in this file, so it stays ignored — now behind an explicit comment and a + scope-guard test rather than as an accident of the existence check. +- The **deco path** (`OptionsForWatermarks` → the private `GetWatermarkOptions`) has always returned its + resolved path unchecked, so it already honored external URLs and #502 never applied to it. It keeps its + own policy; aligning its missing-file and no-artwork behavior with the three precedence levels is a + behavior change in its own right. + +The three gated levels now share one `ChannelLogoWatermarkOptions` helper so they cannot drift apart +again — the duplication is what let the defect exist in triplicate. Covered by +`WatermarkSelectorChannelLogoTests`, which pins the external-URL fix, both preserved regressions +(cached local path, missing local file ignored) and the generated-fallback scope guard. -- 2.47.3 From 66448e1abfa3b48feb1ec6b786ab7b640cae04c4 Mon Sep 17 00:00:00 2001 From: Timothy Date: Mon, 20 Jul 2026 22:58:50 +0200 Subject: [PATCH 2/2] fix(502): correct the deco-scoping claim, extract + test the routing guard MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Adversarial review found a documentation defect, not a code one: both docs/decisions.md and the WatermarkSelector comment asserted the deco path was unaffected by this change. That is true of the *resolution* half and false of the *routing* half. SelectWatermarks puts deco-derived options into the same list the routing guard filters, so a deco watermark whose resolved path is a URL is rerouted to the graphics engine too — including the generated-initials localhost URL, which only the deco path still emits and which plausibly rendered through ffmpeg before. That reroute is intended (routing by what the path is beats routing by provenance, which would drift), so the fix is to say so accurately rather than to narrow the guard. Also records the accepted per-frame cost asymmetry the entry previously argued on correctness grounds alone. The guard is extracted as CanUseFFmpegNativeWatermark so it can be tested directly — review's highest-value gap was that the half of the fix which decides whether pixels appear had no automated coverage, only the one-off live E2E. Nine cases pin it, including the localhost-fallback reroute. Both deferrals now point at real issues instead of an unverifiable "tracked separately": #510 (deco vs precedence-level missing-logo policy) and #511 (remote-fetch hardening — timeout, size cap, redirects, pooling, caching, SSRF). Also pins scheme-case insensitivity in the selector. --- .../FFmpegNativeWatermarkRoutingTests.cs | 77 +++++++++++++++++++ .../WatermarkSelectorChannelLogoTests.cs | 21 +++++ .../FFmpeg/FFmpegLibraryProcessService.cs | 31 ++++++-- ErsatzTV.Core/FFmpeg/WatermarkSelector.cs | 12 ++- docs/decisions.md | 20 ++++- 5 files changed, 147 insertions(+), 14 deletions(-) create mode 100644 ErsatzTV.Core.Tests/FFmpeg/FFmpegNativeWatermarkRoutingTests.cs diff --git a/ErsatzTV.Core.Tests/FFmpeg/FFmpegNativeWatermarkRoutingTests.cs b/ErsatzTV.Core.Tests/FFmpeg/FFmpegNativeWatermarkRoutingTests.cs new file mode 100644 index 000000000..a2ce62a70 --- /dev/null +++ b/ErsatzTV.Core.Tests/FFmpeg/FFmpegNativeWatermarkRoutingTests.cs @@ -0,0 +1,77 @@ +using ErsatzTV.Core.Domain; +using ErsatzTV.Core.FFmpeg; +using NUnit.Framework; +using Shouldly; + +namespace ErsatzTV.Core.Tests.FFmpeg; + +/// +/// Pins which watermarks ffmpeg may carry natively and which must go to the graphics engine. +/// The remote-URL rule is the second half of the #502 fix: resolving the URL is useless if the +/// resolved path is then handed to ffmpeg as a bare -i argument. +/// +[TestFixture] +public class FFmpegNativeWatermarkRoutingTests +{ + private const string LocalPath = "/cache/logos/ab/abc123.png"; + + private static WatermarkOptions Options( + string imagePath, + ChannelWatermarkMode mode = ChannelWatermarkMode.Permanent) => + new(new ChannelWatermark { Id = 1, Name = "wm", Mode = mode }, imagePath, Option.None); + + [Test] + public void Local_Path_Single_Permanent_Watermark_Uses_FFmpeg() + { + FFmpegLibraryProcessService.CanUseFFmpegNativeWatermark(0, [Options(LocalPath)]) + .ShouldBeTrue(); + } + + [TestCase("https://cdn.example.com/logos/channel.png")] + [TestCase("http://cdn.example.com/logos/channel.png")] + public void Remote_Url_Watermark_Goes_To_Graphics_Engine(string url) + { + FFmpegLibraryProcessService.CanUseFFmpegNativeWatermark(0, [Options(url)]) + .ShouldBeFalse(); + } + + /// + /// The generated-initials fallback is a localhost URL. Only the deco path still emits it, and it is + /// routed by its resolved path like any other URL — see the #502 entry in docs/decisions.md and #510. + /// + [Test] + public void Generated_Localhost_Logo_Url_Goes_To_Graphics_Engine() + { + FFmpegLibraryProcessService + .CanUseFFmpegNativeWatermark(0, [Options("http://localhost:8409/iptv/logos/gen?text=Test")]) + .ShouldBeFalse(); + } + + [Test] + public void Graphics_Elements_Present_Goes_To_Graphics_Engine() + { + FFmpegLibraryProcessService.CanUseFFmpegNativeWatermark(1, [Options(LocalPath)]) + .ShouldBeFalse(); + } + + [Test] + public void Multiple_Watermarks_Go_To_Graphics_Engine() + { + FFmpegLibraryProcessService.CanUseFFmpegNativeWatermark(0, [Options(LocalPath), Options(LocalPath)]) + .ShouldBeFalse(); + } + + [Test] + public void No_Watermarks_Does_Not_Use_FFmpeg() + { + FFmpegLibraryProcessService.CanUseFFmpegNativeWatermark(0, []).ShouldBeFalse(); + } + + [TestCase(ChannelWatermarkMode.Intermittent)] + [TestCase(ChannelWatermarkMode.None)] + public void Non_Permanent_Watermark_Goes_To_Graphics_Engine(ChannelWatermarkMode mode) + { + FFmpegLibraryProcessService.CanUseFFmpegNativeWatermark(0, [Options(LocalPath, mode)]) + .ShouldBeFalse(); + } +} diff --git a/ErsatzTV.Core.Tests/FFmpeg/WatermarkSelectorChannelLogoTests.cs b/ErsatzTV.Core.Tests/FFmpeg/WatermarkSelectorChannelLogoTests.cs index 9728b40b9..5714d9376 100644 --- a/ErsatzTV.Core.Tests/FFmpeg/WatermarkSelectorChannelLogoTests.cs +++ b/ErsatzTV.Core.Tests/FFmpeg/WatermarkSelectorChannelLogoTests.cs @@ -125,6 +125,27 @@ public class WatermarkSelectorChannelLogoTests options.Watermark.ShouldBe(watermark); } + /// + /// Scheme comparison goes through , which lower-cases it. Pinned because the fix + /// turns on Artwork.IsExternalUrl, and a case-sensitive check would silently fall back to the + /// existence-gated branch and re-introduce the defect for an oddly-cased URL. + /// + [Test] + public void ChannelWatermark_Should_Use_External_Url_Channel_Logo_Regardless_Of_Scheme_Case() + { + const string UpperCaseUrl = "HTTPS://cdn.example.com/logos/channel.png"; + ChannelWatermark watermark = ChannelLogoWatermark(2, "Channel"); + Channel channel = ChannelWithLogo(UpperCaseUrl, watermark); + + Option result = _selector.GetWatermarkOptions( + channel, + Option.None, + Option.None); + + result.IsSome.ShouldBeTrue(); + result.IfNone(() => throw new InvalidOperationException()).ImagePath.ShouldBe(UpperCaseUrl); + } + // ---- regressions: local-file behavior must not change --------------------------------------- [Test] diff --git a/ErsatzTV.Core/FFmpeg/FFmpegLibraryProcessService.cs b/ErsatzTV.Core/FFmpeg/FFmpegLibraryProcessService.cs index c2048d8be..5f328e943 100644 --- a/ErsatzTV.Core/FFmpeg/FFmpegLibraryProcessService.cs +++ b/ErsatzTV.Core/FFmpeg/FFmpegLibraryProcessService.cs @@ -68,6 +68,29 @@ public class FFmpegLibraryProcessService : IFFmpegProcessService _logger = logger; } + /// + /// Whether ffmpeg can carry the watermark itself (a single permanent watermark and no other graphics), + /// rather than handing it to the graphics engine. + /// + /// + /// A watermark whose resolved path is a remote URL is always refused here (#502). ffmpeg would receive it + /// as a bare -i argument — and ffprobe the same string for animation detection — putting an + /// unbounded network fetch inside stream startup, with no timeout, redirect or auth handling of ours, and + /// with the image's real dimensions never probed. The graphics engine fetches remote images deliberately + /// (ImageElementBase.LoadImage) and decodes them for their true size. + /// + /// This is decided by the resolved alone, so it applies + /// uniformly however the watermark was selected — channel, global, playout item or deco. Only + /// `ChannelLogo` watermarks can produce a URL: `Custom` resolves through the image cache and + /// `Resource` through the resources folder, so neither is ever rerouted. + /// + /// + internal static bool CanUseFFmpegNativeWatermark(int graphicsElementCount, List watermarks) => + graphicsElementCount == 0 + && watermarks.Count == 1 + && watermarks.All(wm => wm.Watermark.Mode is ChannelWatermarkMode.Permanent + && !Artwork.IsExternalUrl(wm.ImagePath)); + public async Task ForPlayoutItem( string ffmpegPath, string ffprobePath, @@ -379,13 +402,7 @@ public class FFmpegLibraryProcessService : IFFmpegProcessService Option graphicsEngineContext = Option.None; List graphicsElementContexts = []; - // use ffmpeg for single permanent watermark, graphics engine for all others. - // a remote-URL watermark always takes the graphics engine (#502): that path fetches the image with - // HttpClient and reads its real dimensions, whereas this one would hand the URL to ffprobe and - // ffmpeg as a bare -i argument, putting an unbounded network fetch inside stream startup. - if (graphicsElements.Count == 0 && watermarks.Count == 1 - && watermarks.All(wm => wm.Watermark.Mode is ChannelWatermarkMode.Permanent) - && watermarks.All(wm => !Artwork.IsExternalUrl(wm.ImagePath))) + if (CanUseFFmpegNativeWatermark(graphicsElements.Count, watermarks)) { foreach (var wm in watermarks) { diff --git a/ErsatzTV.Core/FFmpeg/WatermarkSelector.cs b/ErsatzTV.Core/FFmpeg/WatermarkSelector.cs index de760bccf..2b0bbd2ce 100644 --- a/ErsatzTV.Core/FFmpeg/WatermarkSelector.cs +++ b/ErsatzTV.Core/FFmpeg/WatermarkSelector.cs @@ -367,10 +367,14 @@ public class WatermarkSelector( customPath, None); case ChannelWatermarkImageSource.ChannelLogo: - // deliberately NOT ChannelLogoWatermarkOptions: the deco path has always passed its - // resolved path through unchecked, so it already honored external-URL logos and #502 does - // not apply here. Aligning its missing-file / no-artwork policy with the three precedence - // levels above is a behavior change beyond this fix — tracked separately. + // deliberately NOT ChannelLogoWatermarkOptions: the deco path has always passed its resolved + // path through unchecked, so #502's File.Exists defect never reached it and its *resolution* + // is unchanged here. Aligning its missing-file / no-artwork policy with the three precedence + // levels above is a behavior change beyond this fix — tracked in #510. + // Note this only scopes resolution: the ffmpeg-native-vs-graphics-engine routing in + // FFmpegLibraryProcessService.CanUseFFmpegNativeWatermark keys off the resolved path alone, so a + // deco watermark resolving to a URL (an external logo, or the generated-initials URL below) is + // rerouted to the graphics engine like any other. That is intended: it is the URL-aware path. string channelPath = ChannelLogoGenerator.GenerateChannelLogoUrl(channel); Option maybeLogoArtwork = Optional(channel.Artwork.Find(a => a.ArtworkKind == ArtworkKind.Logo)); diff --git a/docs/decisions.md b/docs/decisions.md index 2c4b7643c..f59b5f3a6 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -2499,9 +2499,23 @@ additionally requires a non-URL path. deferred by an earlier entry in this file, so it stays ignored — now behind an explicit comment and a scope-guard test rather than as an accident of the existence check. - The **deco path** (`OptionsForWatermarks` → the private `GetWatermarkOptions`) has always returned its - resolved path unchecked, so it already honored external URLs and #502 never applied to it. It keeps its - own policy; aligning its missing-file and no-artwork behavior with the three precedence levels is a - behavior change in its own right. + resolved path unchecked, so #502's `File.Exists` defect never reached it and its *resolution* is unchanged. + Aligning its missing-file and no-artwork behavior with the three precedence levels is a behavior change in + its own right, tracked as **#510**. + +**The routing change is NOT scoped that way, deliberately.** `CanUseFFmpegNativeWatermark` keys off the +resolved `WatermarkOptions.ImagePath` alone, and `SelectWatermarks` puts deco-derived options into the same +list — so a *deco* watermark resolving to a URL is rerouted to the graphics engine too, including the +generated-initials `http://localhost:…/iptv/logos/gen` URL that the deco path does still pass through. +Routing by provenance instead of by what the path actually is would mean deciding the same thing twice and +letting the two drift; the URL-aware path is the right one for any URL. Worth knowing when picking up #510: +that fallback plausibly rendered through ffmpeg before and now composites through ImageSharp, which this +change's live-E2E did not cover. + +**Accepted cost asymmetry.** Graphics-engine compositing is per-frame ImageSharp work rather than ffmpeg's +`overlay` filter, so two channels with visually identical bugs now transcode at different cost based only on +whether the logo is a URL. The rejected fetch-once-into-the-image-cache alternative would have avoided that; +if **#511** (remote-fetch hardening: timeout, size cap, pooling, caching) adds such a cache, this goes with it. The three gated levels now share one `ChannelLogoWatermarkOptions` helper so they cannot drift apart again — the duplication is what let the defect exist in triplicate. Covered by -- 2.47.3