diff --git a/ErsatzTV.Application/ProgramSchedules/ProgramScheduleItemViewModel.cs b/ErsatzTV.Application/ProgramSchedules/ProgramScheduleItemViewModel.cs
index bbd48faa0..99ce25574 100644
--- a/ErsatzTV.Application/ProgramSchedules/ProgramScheduleItemViewModel.cs
+++ b/ErsatzTV.Application/ProgramSchedules/ProgramScheduleItemViewModel.cs
@@ -44,6 +44,33 @@ public abstract record ProgramScheduleItemViewModel(
string PreferredSubtitleLanguageCode,
ChannelSubtitleMode? SubtitleMode)
{
+ ///
+ /// A rough estimate, in wall-clock time, of how long a single pass of this schedule item will play,
+ /// derived from the aggregated playout runtimes of the referenced content.
+ ///
+ /// Semantics by :
+ ///
+ /// - One — the average runtime of one item in the referenced collection.
+ /// -
+ /// Multiple — the average item runtime multiplied by the configured count
+ /// (), or the whole collection runtime for
+ /// . An expression-based (non-integer)
+ /// count cannot be evaluated here and yields null.
+ ///
+ /// - Flood — always null: a flood item fills the remaining time and is unbounded.
+ /// - Duration — the explicit playoutDuration setting on the item.
+ ///
+ ///
+ ///
+ /// null whenever a bounded estimate cannot be produced — an unbounded mode (Flood),
+ /// a referenced collection with no items that have a known positive duration, a Multiple mode other
+ /// than Count/CollectionSize, or a collection type other than
+ /// (smart/multi/playlist/search/rerun/show/season/artist references are not aggregated in this pass).
+ /// Callers should treat a null as "unknown", never as zero.
+ ///
+ ///
+ public TimeSpan? DurationEstimate { get; init; }
+
public string Name => CollectionType switch
{
CollectionType.Collection => Collection?.Name,
diff --git a/ErsatzTV.Application/ProgramSchedules/ProgramScheduleItemsWithDurationViewModel.cs b/ErsatzTV.Application/ProgramSchedules/ProgramScheduleItemsWithDurationViewModel.cs
new file mode 100644
index 000000000..0d0fa4623
--- /dev/null
+++ b/ErsatzTV.Application/ProgramSchedules/ProgramScheduleItemsWithDurationViewModel.cs
@@ -0,0 +1,18 @@
+namespace ErsatzTV.Application.ProgramSchedules;
+
+///
+/// The items of a schedule together with computed runtime estimates. Each item carries its own
+/// (nullable — see that property for
+/// the per-mode semantics), and is the sum of the items that
+/// could be estimated.
+///
+/// The schedule items, each with a nullable DurationEstimate.
+///
+/// The sum of every non-null per-item estimate, i.e. a rough runtime for a single pass through the
+/// estimable items. null when no item in the schedule could be estimated (for example a
+/// schedule made up entirely of Flood items, or of collection types that are not aggregated).
+/// Because unbounded items contribute nothing, this is a lower bound, never an exact schedule length.
+///
+public record ProgramScheduleItemsWithDurationViewModel(
+ List Items,
+ TimeSpan? TotalDurationEstimate);
diff --git a/ErsatzTV.Application/ProgramSchedules/Queries/GetProgramScheduleItemsWithDurations.cs b/ErsatzTV.Application/ProgramSchedules/Queries/GetProgramScheduleItemsWithDurations.cs
new file mode 100644
index 000000000..abfa27406
--- /dev/null
+++ b/ErsatzTV.Application/ProgramSchedules/Queries/GetProgramScheduleItemsWithDurations.cs
@@ -0,0 +1,4 @@
+namespace ErsatzTV.Application.ProgramSchedules;
+
+public record GetProgramScheduleItemsWithDurations(int Id)
+ : IRequest;
diff --git a/ErsatzTV.Application/ProgramSchedules/Queries/GetProgramScheduleItemsWithDurationsHandler.cs b/ErsatzTV.Application/ProgramSchedules/Queries/GetProgramScheduleItemsWithDurationsHandler.cs
new file mode 100644
index 000000000..72c9a1271
--- /dev/null
+++ b/ErsatzTV.Application/ProgramSchedules/Queries/GetProgramScheduleItemsWithDurationsHandler.cs
@@ -0,0 +1,70 @@
+using ErsatzTV.Core.Domain;
+using ErsatzTV.Core.Extensions;
+using ErsatzTV.Core.Interfaces.Repositories;
+using static ErsatzTV.Application.ProgramSchedules.ScheduleItemDurationEstimator;
+
+namespace ErsatzTV.Application.ProgramSchedules;
+
+public class GetProgramScheduleItemsWithDurationsHandler(
+ IMediator mediator,
+ IMediaCollectionRepository mediaCollectionRepository)
+ : IRequestHandler
+{
+ public async Task Handle(
+ GetProgramScheduleItemsWithDurations request,
+ CancellationToken cancellationToken)
+ {
+ List items =
+ await mediator.Send(new GetProgramScheduleItems(request.Id), cancellationToken);
+
+ Dictionary durationsByCollectionId =
+ await AggregateReferencedCollections(items);
+
+ var itemsWithEstimates = items
+ .Map(item => item with { DurationEstimate = Estimate(item, durationsByCollectionId) })
+ .ToList();
+
+ List estimates = itemsWithEstimates
+ .Map(item => Optional(item.DurationEstimate))
+ .Somes()
+ .ToList();
+
+ TimeSpan? total = estimates.Count > 0
+ ? TimeSpan.FromTicks(estimates.Sum(estimate => estimate.Ticks))
+ : null;
+
+ return new ProgramScheduleItemsWithDurationViewModel(itemsWithEstimates, total);
+ }
+
+ // Aggregate MediaVersion.Duration once per distinct referenced collection (not per item). Only plain
+ // collections are resolved here; other reference types are estimated as null (see DurationEstimate docs).
+ private async Task> AggregateReferencedCollections(
+ IReadOnlyList items)
+ {
+ List collectionIds = items
+ .Filter(item => item.CollectionType is CollectionType.Collection && item.Collection is not null)
+ .Filter(item => item.PlayoutMode is PlayoutMode.One or PlayoutMode.Multiple)
+ .Map(item => item.Collection.Id)
+ .Distinct()
+ .ToList();
+
+ var result = new Dictionary();
+ foreach (int collectionId in collectionIds)
+ {
+ List mediaItems = await mediaCollectionRepository.GetItems(collectionId);
+
+ List durations = mediaItems
+ .Map(mediaItem => mediaItem.GetDurationForPlayout())
+ .Filter(duration => duration > TimeSpan.Zero)
+ .ToList();
+
+ if (durations.Count > 0)
+ {
+ var total = TimeSpan.FromTicks(durations.Sum(duration => duration.Ticks));
+ result[collectionId] = new CollectionDuration(total, durations.Count);
+ }
+ }
+
+ return result;
+ }
+}
diff --git a/ErsatzTV.Application/ProgramSchedules/ScheduleItemDurationEstimator.cs b/ErsatzTV.Application/ProgramSchedules/ScheduleItemDurationEstimator.cs
new file mode 100644
index 000000000..9a6a817a3
--- /dev/null
+++ b/ErsatzTV.Application/ProgramSchedules/ScheduleItemDurationEstimator.cs
@@ -0,0 +1,73 @@
+using System.Globalization;
+using ErsatzTV.Core.Domain;
+
+namespace ErsatzTV.Application.ProgramSchedules;
+
+///
+/// Pure computation of per-item runtime estimates from pre-aggregated collection durations.
+/// Kept separate from the query handler so the (non-trivial) per-mode math can be unit-tested
+/// without a database. See for the
+/// documented semantics this implements.
+///
+internal static class ScheduleItemDurationEstimator
+{
+ ///
+ /// Aggregate runtime of a single referenced collection: the total runtime of every item with a
+ /// known non-zero duration, and how many such items there are.
+ ///
+ public sealed record CollectionDuration(TimeSpan Total, int ItemCount)
+ {
+ public TimeSpan? Average => ItemCount > 0 ? Total / ItemCount : null;
+ }
+
+ ///
+ /// Estimate the runtime of one pass of , or null when no bounded
+ /// estimate is possible. holds aggregates only for the
+ /// plain collections that were resolved; a missing entry yields null.
+ ///
+ public static TimeSpan? Estimate(
+ ProgramScheduleItemViewModel item,
+ IReadOnlyDictionary durationsByCollectionId)
+ {
+ if (item is ProgramScheduleItemDurationViewModel durationItem)
+ {
+ return durationItem.PlayoutDuration;
+ }
+
+ // only plain collections are aggregated in this pass
+ if (item.CollectionType is not CollectionType.Collection || item.Collection is null)
+ {
+ return null;
+ }
+
+ if (!durationsByCollectionId.TryGetValue(item.Collection.Id, out CollectionDuration duration))
+ {
+ return null;
+ }
+
+ return item switch
+ {
+ // one item per pass -> the average item runtime
+ ProgramScheduleItemOneViewModel => duration.Average,
+
+ // a fixed count of items, or the whole collection once
+ ProgramScheduleItemMultipleViewModel multiple => EstimateMultiple(multiple, duration),
+
+ // Flood is an unbounded fill; Duration is handled above from its explicit playoutDuration.
+ _ => null
+ };
+ }
+
+ private static TimeSpan? EstimateMultiple(
+ ProgramScheduleItemMultipleViewModel multiple,
+ CollectionDuration duration) =>
+ multiple.MultipleMode switch
+ {
+ MultipleMode.Count when
+ int.TryParse(multiple.Count, NumberStyles.Integer, CultureInfo.InvariantCulture, out int count)
+ && count > 0
+ && duration.Average is { } average => average * count,
+ MultipleMode.CollectionSize => duration.Total,
+ _ => null
+ };
+}
diff --git a/ErsatzTV.Tests/Application/ProgramSchedules/GetProgramScheduleItemsWithDurationsHandlerTests.cs b/ErsatzTV.Tests/Application/ProgramSchedules/GetProgramScheduleItemsWithDurationsHandlerTests.cs
new file mode 100644
index 000000000..c1c1d525e
--- /dev/null
+++ b/ErsatzTV.Tests/Application/ProgramSchedules/GetProgramScheduleItemsWithDurationsHandlerTests.cs
@@ -0,0 +1,247 @@
+using ErsatzTV.Application.MediaCollections;
+using ErsatzTV.Application.ProgramSchedules;
+using ErsatzTV.Core.Domain;
+using ErsatzTV.Core.Interfaces.Repositories;
+using ErsatzTV.Core.Scheduling;
+using MediatR;
+using NSubstitute;
+using NUnit.Framework;
+using Shouldly;
+
+namespace ErsatzTV.Tests.Application.ProgramSchedules;
+
+[TestFixture]
+public class GetProgramScheduleItemsWithDurationsHandlerTests
+{
+ private IMediaCollectionRepository _mediaCollectionRepository = null!;
+ private IMediator _mediator = null!;
+
+ [SetUp]
+ public void SetUp()
+ {
+ _mediator = Substitute.For();
+ _mediaCollectionRepository = Substitute.For();
+ }
+
+ [Test]
+ public async Task Handle_Should_Estimate_Items_And_Total_From_Collection_Durations()
+ {
+ ProgramScheduleItemViewModel one = MakeOneItem(1, 10);
+ ProgramScheduleItemViewModel multipleCount = MakeMultipleItem(2, 10, MultipleMode.Count, "3");
+ ProgramScheduleItemViewModel multipleCollectionSize = MakeMultipleItem(3, 20, MultipleMode.CollectionSize, "0");
+ ProgramScheduleItemViewModel duration = MakeDurationItem(4, TimeSpan.FromMinutes(45));
+ ProgramScheduleItemViewModel flood = MakeFloodItem(5, 10);
+ ProgramScheduleItemViewModel remote = MakeOneItem(6, 30);
+
+ _mediator.Send(Arg.Is(q => q.Id == 99), Arg.Any())
+ .Returns([one, multipleCount, multipleCollectionSize, duration, flood, remote]);
+ _mediaCollectionRepository.GetItems(10)
+ .Returns([MakeMovie(30), MakeMovie(60), MakeMovie(0)]);
+ _mediaCollectionRepository.GetItems(20)
+ .Returns([MakeMovie(10), MakeMovie(20)]);
+ _mediaCollectionRepository.GetItems(30)
+ .Returns([MakeRemoteStreamWithFallbackDuration(20)]);
+
+ var handler = new GetProgramScheduleItemsWithDurationsHandler(_mediator, _mediaCollectionRepository);
+
+ ProgramScheduleItemsWithDurationViewModel result =
+ await handler.Handle(new GetProgramScheduleItemsWithDurations(99), CancellationToken.None);
+
+ result.Items[0].DurationEstimate.ShouldBe(TimeSpan.FromMinutes(45));
+ result.Items[1].DurationEstimate.ShouldBe(TimeSpan.FromMinutes(135));
+ result.Items[2].DurationEstimate.ShouldBe(TimeSpan.FromMinutes(30));
+ result.Items[3].DurationEstimate.ShouldBe(TimeSpan.FromMinutes(45));
+ result.Items[4].DurationEstimate.ShouldBeNull();
+ result.Items[5].DurationEstimate.ShouldBe(TimeSpan.FromMinutes(20));
+ result.TotalDurationEstimate.ShouldBe(TimeSpan.FromMinutes(275));
+ }
+
+ [Test]
+ public async Task Handle_Should_Return_Null_Total_When_No_Items_Can_Be_Estimated()
+ {
+ ProgramScheduleItemViewModel one = MakeOneItem(1, 10);
+ ProgramScheduleItemViewModel flood = MakeFloodItem(2, 10);
+
+ _mediator.Send(Arg.Is(q => q.Id == 99), Arg.Any())
+ .Returns([one, flood]);
+ _mediaCollectionRepository.GetItems(10)
+ .Returns([MakeMovie(0)]);
+
+ var handler = new GetProgramScheduleItemsWithDurationsHandler(_mediator, _mediaCollectionRepository);
+
+ ProgramScheduleItemsWithDurationViewModel result =
+ await handler.Handle(new GetProgramScheduleItemsWithDurations(99), CancellationToken.None);
+
+ result.Items.ShouldAllBe(item => item.DurationEstimate == null);
+ result.TotalDurationEstimate.ShouldBeNull();
+ }
+
+ private static ProgramScheduleItemOneViewModel MakeOneItem(int id, int collectionId) =>
+ new(
+ id,
+ id,
+ StartType.Dynamic,
+ null,
+ null,
+ CollectionType.Collection,
+ MakeCollection(collectionId),
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ PlaybackOrder.Shuffle,
+ MarathonGroupBy.None,
+ false,
+ false,
+ null,
+ FillWithGroupMode.None,
+ null,
+ GuideMode.Normal,
+ null,
+ null,
+ null,
+ null,
+ null,
+ [],
+ [],
+ null,
+ null,
+ null,
+ null);
+
+ private static ProgramScheduleItemMultipleViewModel MakeMultipleItem(
+ int id,
+ int collectionId,
+ MultipleMode multipleMode,
+ string count) =>
+ new(
+ id,
+ id,
+ StartType.Dynamic,
+ null,
+ null,
+ CollectionType.Collection,
+ MakeCollection(collectionId),
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ PlaybackOrder.Shuffle,
+ MarathonGroupBy.None,
+ false,
+ false,
+ null,
+ FillWithGroupMode.None,
+ multipleMode,
+ count,
+ null,
+ GuideMode.Normal,
+ null,
+ null,
+ null,
+ null,
+ null,
+ [],
+ [],
+ null,
+ null,
+ null,
+ null);
+
+ private static ProgramScheduleItemDurationViewModel MakeDurationItem(int id, TimeSpan playoutDuration) =>
+ new(
+ id,
+ id,
+ StartType.Dynamic,
+ null,
+ null,
+ CollectionType.Collection,
+ MakeCollection(10),
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ PlaybackOrder.Shuffle,
+ MarathonGroupBy.None,
+ false,
+ false,
+ null,
+ FillWithGroupMode.None,
+ playoutDuration,
+ TailMode.None,
+ 0,
+ null,
+ GuideMode.Normal,
+ null,
+ null,
+ null,
+ null,
+ null,
+ [],
+ [],
+ null,
+ null,
+ null,
+ null);
+
+ private static ProgramScheduleItemFloodViewModel MakeFloodItem(int id, int collectionId) =>
+ new(
+ id,
+ id,
+ StartType.Dynamic,
+ null,
+ null,
+ CollectionType.Collection,
+ MakeCollection(collectionId),
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ PlaybackOrder.Shuffle,
+ MarathonGroupBy.None,
+ false,
+ false,
+ null,
+ FillWithGroupMode.None,
+ null,
+ GuideMode.Normal,
+ null,
+ null,
+ null,
+ null,
+ null,
+ [],
+ [],
+ null,
+ null,
+ null,
+ null);
+
+ private static MediaCollectionViewModel MakeCollection(int id) =>
+ new(CollectionType.Collection, id, $"Collection {id}", false, MediaItemState.Normal);
+
+ private static Movie MakeMovie(int minutes) =>
+ new()
+ {
+ MediaVersions = [new MediaVersion { Duration = TimeSpan.FromMinutes(minutes) }]
+ };
+
+ private static RemoteStream MakeRemoteStreamWithFallbackDuration(int minutes) =>
+ new()
+ {
+ Duration = TimeSpan.FromMinutes(minutes),
+ MediaVersions = [new MediaVersion { Duration = TimeSpan.Zero }]
+ };
+}
diff --git a/ErsatzTV.Tests/Controllers/ScheduleControllerTests.cs b/ErsatzTV.Tests/Controllers/ScheduleControllerTests.cs
index 151674a4d..91a19e90c 100644
--- a/ErsatzTV.Tests/Controllers/ScheduleControllerTests.cs
+++ b/ErsatzTV.Tests/Controllers/ScheduleControllerTests.cs
@@ -189,14 +189,18 @@ public class ScheduleControllerTests
public async Task GetItems_Should_Return_200_With_Items()
{
List items = [MakeOneItem(11)];
+ var response = new ProgramScheduleItemsWithDurationViewModel(items, TimeSpan.FromMinutes(25));
_mediator.Send(Arg.Any(), Arg.Any())
.Returns(Option.Some(MakeSchedule(4, "Daily")));
- _mediator.Send(Arg.Any(), Arg.Any())
- .Returns(items);
+ _mediator.Send(Arg.Any(), Arg.Any())
+ .Returns(response);
IActionResult result = await _controller.GetItems(4, CancellationToken.None);
- result.ShouldBeOfType().Value.ShouldBe(items);
+ result.ShouldBeOfType().Value.ShouldBe(response);
+ await _mediator.Received(1).Send(
+ Arg.Is(q => q.Id == 4),
+ Arg.Any());
}
[Test]
diff --git a/ErsatzTV/Controllers/Api/ScheduleController.cs b/ErsatzTV/Controllers/Api/ScheduleController.cs
index 7592d3562..2a8d6f5ac 100644
--- a/ErsatzTV/Controllers/Api/ScheduleController.cs
+++ b/ErsatzTV/Controllers/Api/ScheduleController.cs
@@ -99,8 +99,12 @@ public class ScheduleController(IMediator mediator) : ControllerBase
[HttpGet("/api/schedules/{id:int}/items")]
[Tags("Schedules")]
[EndpointSummary("Get schedule items")]
+ [EndpointDescription(
+ "Returns the schedule's items plus a computed, best-effort runtime estimate: each item carries a " +
+ "nullable durationEstimate and the envelope carries a nullable totalDurationEstimate. Estimates are " +
+ "derived from referenced collection/media runtimes and are null when unbounded or unknown.")]
[EndpointGroupName("general")]
- [ProducesResponseType(typeof(List), StatusCodes.Status200OK)]
+ [ProducesResponseType(typeof(ProgramScheduleItemsWithDurationViewModel), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status404NotFound)]
public async Task GetItems(int id, CancellationToken cancellationToken)
{
@@ -110,8 +114,8 @@ public class ScheduleController(IMediator mediator) : ControllerBase
return ApiResults.NotFoundProblem();
}
- List items =
- await mediator.Send(new GetProgramScheduleItems(id), cancellationToken);
+ ProgramScheduleItemsWithDurationViewModel items =
+ await mediator.Send(new GetProgramScheduleItemsWithDurations(id), cancellationToken);
return new OkObjectResult(items);
}
diff --git a/ErsatzTV/wwwroot/openapi/v1.json b/ErsatzTV/wwwroot/openapi/v1.json
index eb4ab1c7e..76730ed41 100644
--- a/ErsatzTV/wwwroot/openapi/v1.json
+++ b/ErsatzTV/wwwroot/openapi/v1.json
@@ -2580,6 +2580,7 @@
"Schedules"
],
"summary": "Get schedule items",
+ "description": "Returns the schedule's items plus a computed, best-effort runtime estimate: each item carries a nullable durationEstimate and the envelope carries a nullable totalDurationEstimate. Estimates are derived from referenced collection/media runtimes and are null when unbounded or unknown.",
"parameters": [
{
"name": "id",
@@ -2597,26 +2598,17 @@
"content": {
"text/plain": {
"schema": {
- "type": "array",
- "items": {
- "$ref": "#/components/schemas/ProgramScheduleItemViewModel"
- }
+ "$ref": "#/components/schemas/ProgramScheduleItemsWithDurationViewModel"
}
},
"application/json": {
"schema": {
- "type": "array",
- "items": {
- "$ref": "#/components/schemas/ProgramScheduleItemViewModel"
- }
+ "$ref": "#/components/schemas/ProgramScheduleItemsWithDurationViewModel"
}
},
"text/json": {
"schema": {
- "type": "array",
- "items": {
- "$ref": "#/components/schemas/ProgramScheduleItemViewModel"
- }
+ "$ref": "#/components/schemas/ProgramScheduleItemsWithDurationViewModel"
}
}
}
@@ -5445,6 +5437,31 @@
}
}
},
+ "ProgramScheduleItemsWithDurationViewModel": {
+ "required": [
+ "items",
+ "totalDurationEstimate"
+ ],
+ "type": "object",
+ "properties": {
+ "items": {
+ "type": [
+ "null",
+ "array"
+ ],
+ "items": {
+ "$ref": "#/components/schemas/ProgramScheduleItemViewModel"
+ }
+ },
+ "totalDurationEstimate": {
+ "pattern": "^-?(\\d+\\.)?\\d{2}:\\d{2}:\\d{2}(\\.\\d{1,7})?$",
+ "type": [
+ "null",
+ "string"
+ ]
+ }
+ }
+ },
"ProgramScheduleItemViewModel": {
"type": "object",
"properties": {
@@ -5604,6 +5621,13 @@
}
]
},
+ "durationEstimate": {
+ "pattern": "^-?(\\d+\\.)?\\d{2}:\\d{2}:\\d{2}(\\.\\d{1,7})?$",
+ "type": [
+ "null",
+ "string"
+ ]
+ },
"name": {
"type": [
"null",