diff --git a/ErsatzTV.Application/Channels/Queries/GetChannelStatesForApiHandler.cs b/ErsatzTV.Application/Channels/Queries/GetChannelStatesForApiHandler.cs index 0aafff89b..172557a41 100644 --- a/ErsatzTV.Application/Channels/Queries/GetChannelStatesForApiHandler.cs +++ b/ErsatzTV.Application/Channels/Queries/GetChannelStatesForApiHandler.cs @@ -2,6 +2,7 @@ using ErsatzTV.Core.Api.Channels; using ErsatzTV.Core.Domain; using ErsatzTV.Core.Domain.Filler; using ErsatzTV.Core.Interfaces.FFmpeg; +using ErsatzTV.Core.Interfaces.Streaming; using ErsatzTV.Infrastructure.Data; using Microsoft.EntityFrameworkCore; using PlayoutMapper = ErsatzTV.Application.Playouts.Mapper; @@ -10,7 +11,8 @@ namespace ErsatzTV.Application.Channels; public class GetChannelStatesForApiHandler( IDbContextFactory dbContextFactory, - IFFmpegSegmenterService ffmpegSegmenterService) + IFFmpegSegmenterService ffmpegSegmenterService, + IDirectStreamSessionTracker directStreamSessionTracker) : IRequestHandler> { // a guide entry (program + surrounding filler) never spans anywhere near a day; the time @@ -141,7 +143,8 @@ public class GetChannelStatesForApiHandler( return new ChannelStateResponseModel( channel.Id, channel.Number, - ffmpegSegmenterService.IsActive(channel.Number), + ffmpegSegmenterService.IsActive(channel.Number) || + directStreamSessionTracker.IsActive(channel.Number), nowPlaying); }) .ToList(); diff --git a/ErsatzTV.Tests/Application/Channels/GetChannelStatesForApiHandlerTests.cs b/ErsatzTV.Tests/Application/Channels/GetChannelStatesForApiHandlerTests.cs index 0a237b30f..5965dc814 100644 --- a/ErsatzTV.Tests/Application/Channels/GetChannelStatesForApiHandlerTests.cs +++ b/ErsatzTV.Tests/Application/Channels/GetChannelStatesForApiHandlerTests.cs @@ -3,6 +3,7 @@ using ErsatzTV.Core.Api.Channels; using ErsatzTV.Core.Domain; using ErsatzTV.Core.Domain.Filler; using ErsatzTV.Core.Interfaces.FFmpeg; +using ErsatzTV.Core.Interfaces.Streaming; using ErsatzTV.Infrastructure.Data; using ErsatzTV.Tests.Support; using NSubstitute; @@ -18,12 +19,14 @@ public class GetChannelStatesForApiHandlerTests private InMemoryTvContext _db = null!; private IFFmpegSegmenterService _segmenter = null!; + private IDirectStreamSessionTracker _directStreams = null!; [SetUp] public async Task SetUp() { _db = await InMemoryTvContext.CreateAsync(); _segmenter = Substitute.For(); + _directStreams = Substitute.For(); } [TearDown] @@ -36,7 +39,7 @@ public class GetChannelStatesForApiHandlerTests DateTime finish = Now.AddMinutes(20); await SeedChannelWithMovie(start, finish); _segmenter.IsActive("7.1").Returns(true); - var handler = new GetChannelStatesForApiHandler(_db.Factory, _segmenter); + var handler = new GetChannelStatesForApiHandler(_db.Factory, _segmenter, _directStreams); List result = await handler.Handle(new GetChannelStatesForApi(Now), CancellationToken.None); @@ -51,11 +54,26 @@ public class GetChannelStatesForApiHandlerTests state.NowPlaying.FinishUtc.ShouldBe(new DateTimeOffset(finish, TimeSpan.Zero)); } + [Test] + public async Task Handle_Should_Return_OnAir_For_Direct_Stream_Session() + { + await using TvContext context = _db.CreateContext(); + context.Channels.Add(MakeChannel(8, "8")); + await context.SaveChangesAsync(); + _directStreams.IsActive("8").Returns(true); + var handler = new GetChannelStatesForApiHandler(_db.Factory, _segmenter, _directStreams); + + List result = + await handler.Handle(new GetChannelStatesForApi(Now), CancellationToken.None); + + result.ShouldHaveSingleItem().OnAir.ShouldBeTrue(); + } + [Test] public async Task Handle_Should_Match_Item_When_Now_Equals_Start() { await SeedChannelWithMovie(Now, Now.AddMinutes(30)); - var handler = new GetChannelStatesForApiHandler(_db.Factory, _segmenter); + var handler = new GetChannelStatesForApiHandler(_db.Factory, _segmenter, _directStreams); List result = await handler.Handle(new GetChannelStatesForApi(Now), CancellationToken.None); @@ -67,7 +85,7 @@ public class GetChannelStatesForApiHandlerTests public async Task Handle_Should_Not_Match_Item_When_Now_Equals_Finish() { await SeedChannelWithMovie(Now.AddMinutes(-30), Now); - var handler = new GetChannelStatesForApiHandler(_db.Factory, _segmenter); + var handler = new GetChannelStatesForApiHandler(_db.Factory, _segmenter, _directStreams); List result = await handler.Handle(new GetChannelStatesForApi(Now), CancellationToken.None); @@ -81,7 +99,7 @@ public class GetChannelStatesForApiHandlerTests await using TvContext context = _db.CreateContext(); context.Channels.Add(MakeChannel(8, "8")); await context.SaveChangesAsync(); - var handler = new GetChannelStatesForApiHandler(_db.Factory, _segmenter); + var handler = new GetChannelStatesForApiHandler(_db.Factory, _segmenter, _directStreams); List result = await handler.Handle(new GetChannelStatesForApi(Now), CancellationToken.None); @@ -133,7 +151,7 @@ public class GetChannelStatesForApiHandlerTests MakeItem(125, movie, Now.AddMinutes(2), Now.AddMinutes(40), FillerKind.None)); await context.SaveChangesAsync(); - var handler = new GetChannelStatesForApiHandler(_db.Factory, _segmenter); + var handler = new GetChannelStatesForApiHandler(_db.Factory, _segmenter, _directStreams); List result = await handler.Handle(new GetChannelStatesForApi(Now), CancellationToken.None); @@ -176,7 +194,7 @@ public class GetChannelStatesForApiHandlerTests context.PlayoutItems.Add(item); await context.SaveChangesAsync(); - var handler = new GetChannelStatesForApiHandler(_db.Factory, _segmenter); + var handler = new GetChannelStatesForApiHandler(_db.Factory, _segmenter, _directStreams); List result = await handler.Handle(new GetChannelStatesForApi(Now), CancellationToken.None); @@ -216,7 +234,7 @@ public class GetChannelStatesForApiHandlerTests context.PlayoutItems.Add(item); await context.SaveChangesAsync(); - var handler = new GetChannelStatesForApiHandler(_db.Factory, _segmenter); + var handler = new GetChannelStatesForApiHandler(_db.Factory, _segmenter, _directStreams); ChannelStateResponseModel state = (await handler.Handle(new GetChannelStatesForApi(Now), CancellationToken.None)) @@ -264,7 +282,7 @@ public class GetChannelStatesForApiHandlerTests context.PlayoutItems.Add(item); await context.SaveChangesAsync(); - var handler = new GetChannelStatesForApiHandler(_db.Factory, _segmenter); + var handler = new GetChannelStatesForApiHandler(_db.Factory, _segmenter, _directStreams); List result = await handler.Handle(new GetChannelStatesForApi(Now), CancellationToken.None); diff --git a/docs/superpowers/specs/2026-07-02-channel-state-api-design.md b/docs/superpowers/specs/2026-07-02-channel-state-api-design.md index 36a18d359..d21fb9ace 100644 --- a/docs/superpowers/specs/2026-07-02-channel-state-api-design.md +++ b/docs/superpowers/specs/2026-07-02-channel-state-api-design.md @@ -2,16 +2,16 @@ **Date:** 2026-07-02 **Issue:** [ersatztv#97 - Backend: channel on-air / now-playing state API](http://192.168.1.95:3000/timothy/ersatztv/issues/97) -**Status:** Approved for implementation planning. +**Status:** Implemented by #97; universal streaming-mode coverage completed by #99. ## Context -The ChicoryTV Channels prototype needs runtime channel state for the **On-air** filter, live row treatment, and **Now playing** lane. The existing `GET /api/channels` endpoint returns static channel configuration and should stay cheap. Runtime state changes with wall-clock time and active streaming sessions, so it belongs in a separate pollable endpoint. +The ChicoryTV Channels prototype needs runtime channel state for the **On-air** filter, live row treatment, and **Now playing** lane. The existing `GET /api/v1/channels` endpoint returns static channel configuration and should stay cheap. Runtime state changes with wall-clock time and active streaming sessions, so it belongs in a separate pollable endpoint. ErsatzTV has two distinct concepts: - The playout schedule is clock-based and exists independent of viewers. -- A stream session exists only while a client is actively pulling a segmenter-backed stream. +- A stream session exists only while a client is actively pulling a stream. The API should expose both concepts separately rather than blending them into one ambiguous status. @@ -20,7 +20,7 @@ The API should expose both concepts separately rather than blending them into on Add a batched endpoint: ```http -GET /api/channels/state +GET /api/v1/channels/state ``` Response: @@ -48,9 +48,9 @@ Response: Fields: -- `channelId`: channel database id for joining with `GET /api/channels` rows. +- `channelId`: channel database id for joining with `GET /api/v1/channels` rows. - `channelNumber`: stable display/routing number, also useful for active session checks. -- `onAir`: `true` only when the channel has an active segmenter session. +- `onAir`: `true` when the channel has an active segmenter-backed or direct stream session. - `nowPlaying`: current scheduled `PlayoutItem` by wall-clock, or `null`. - `nowPlaying.title`: display title from the existing playout title mapper. - `nowPlaying.startUtc` / `finishUtc`: UTC item bounds. The SPA computes progress percentage client-side from these values. @@ -61,18 +61,22 @@ The endpoint returns one row per channel so the SPA can poll the whole grid with `nowPlaying` means "what is scheduled right now." It is populated for any channel with a built playout item covering the current wall-clock time, even when `onAir` is false. -`onAir` initially means "has an active HLS segmenter session" using `IFFmpegSegmenterService.IsActive(channelNumber)`. This matches the current `/api/sessions` semantics because the only session registry in the codebase is `IFFmpegSegmenterService.Workers`. +`onAir` means "has an active stream session." It combines +`IFFmpegSegmenterService.IsActive(channelNumber)` for segmenter-backed modes with +`IDirectStreamSessionTracker.IsActive(channelNumber)` for direct modes. Known `onAir` coverage: -| Streaming mode | Covered by `IsActive` | +| Streaming mode | Activity source | | --- | --- | -| `HttpLiveStreamingSegmenter` | Yes | -| `TransportStreamHybrid` | Yes | -| `TransportStream` / MPEG-TS direct | No | -| `HttpLiveStreamingDirect` | No | +| `HttpLiveStreamingSegmenter` | `IFFmpegSegmenterService` | +| `TransportStreamHybrid` | `IFFmpegSegmenterService` | +| `TransportStream` / MPEG-TS direct | `IDirectStreamSessionTracker` | +| `HttpLiveStreamingDirect` | `IDirectStreamSessionTracker` | -The direct streaming modes can be actively streaming while `onAir` reports false because they do not register a segmenter worker. That limitation is documented here and tracked as follow-up [#99](http://192.168.1.95:3000/timothy/ersatztv/issues/99). Issue #97 should not instrument the streaming hot path. +The direct-stream tracking seam landed in #99 without changing this endpoint's response contract. Direct +registrations are created only while the response body is executing and are removed on completion, +disconnect, or error; HEAD probes do not count as viewers. ## Null And Degraded States @@ -86,7 +90,7 @@ When no runtime data is available, the response should degrade to `onAir: false` `nowPlaying` is also `null` when the current playout item is filler with no program item in its guide group (for example a channel looping fallback filler). When the current item is filler *inside* a program's guide group (pre/mid-roll), the endpoint surfaces the program — matching the XMLTV guide — not the filler. -Known imprecision: OnDemand channels report `nowPlaying` from stored playout items, which are only re-anchored when a viewer tunes in. While such a channel sits idle, the reported item and progress drift from what a new viewer will actually see. This is inherent to the stored data and accepted, like the #99 `onAir` caveat. +Known imprecision: OnDemand channels report `nowPlaying` from stored playout items, which are only re-anchored when a viewer tunes in. While such a channel sits idle, the reported item and progress drift from what a new viewer will actually see. This is inherent to the stored data and accepted. ## Implementation Shape @@ -98,7 +102,8 @@ The handler should: 2. Query current playout items in one batched database query using the current UTC time. 3. Include enough media metadata to map the item title with the existing `ErsatzTV.Application.Playouts.Mapper.GetDisplayTitle` behavior. 4. Join the current items back to channels in memory. -5. Ask `IFFmpegSegmenterService.IsActive(channel.Number)` for each channel's `onAir` value. +5. Ask both `IFFmpegSegmenterService.IsActive(channel.Number)` and + `IDirectStreamSessionTracker.IsActive(channel.Number)` for each channel's `onAir` value. Avoid an N+1 database query. The endpoint is intended for frequent table polling. @@ -108,19 +113,21 @@ No database migration is required because the endpoint reads existing channel, p If #68 introduces "always playing" channels by holding a segmenter-backed session, `onAir` will continue to work without an API contract change. If that feature uses a different runtime mechanism, revisit the `onAir` implementation behind the same response field. -Once #99 adds active-session tracking for MPEG-TS and HLS-Direct paths, `onAir` can become universal without changing the endpoint contract. +#99 added active-session tracking for MPEG-TS and HLS-Direct paths, making `onAir` universal without changing +the endpoint contract. ## Testing Controller tests should verify: -- `GET /api/channels/state` routes through MediatR and returns `200 OK`. +- `GET /api/v1/channels/state` routes through MediatR and returns `200 OK`. - The endpoint advertises a `List` response. Application handler tests should verify: - A channel with an active segmenter session returns `onAir: true`. -- A channel with no active segmenter session returns `onAir: false`. +- A channel with an active direct stream session returns `onAir: true`. +- A channel with neither kind of active session returns `onAir: false`. - A current playout item returns `nowPlaying` with title, `startUtc`, and `finishUtc`. - A channel without a current item returns `nowPlaying: null`. - Multiple channels are resolved through one handler call without per-channel playout lookups.