Files
LlamaCasty/ViewModels/MainViewModel.StepDown.cs
T
gramps e654a16b60 fix(history): file each session under the real encoder, not "unknown"
FfmpegEncoder resolved the encoder name into its OWN StreamHealth instance, while the view
model read CurrentHealth — a different object. So every recorded session was filed as
"unknown", and the rate history's encoder key (evidence about NVENC says nothing about QSV)
had nothing to key on. The name now travels on the encoder interface and the pump forwards
it: IFfmpegEncoder.VideoEncoderName -> FramePump.EncoderName.

Caught while adding it: reading _framePump.EncoderName from RefreshRateProposal throws,
because that call runs at MainViewModel ctor line 354 and the pump is built at line 468.
Eight tests failed with the same NullReferenceException, which took a while to see because
the harness's test output is buffered — the first honest look at per-test logging named it
in one line. Guarded; the history falls back to the last session's encoder for that tier,
which is exactly the pre-first-session case the fallback already existed for.

Tests: FramePumpTests gains the encoder-name assertion (null before start, h264_nvenc
after), and the three fake encoders implement the new member.

675 pass, 0 warnings.
2026-11-12 13:57:03 -08:00

131 lines
5.1 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using System;
using System.Windows;
using ytLive.Helpers;
using ytLive.Models;
using ytLive.Services;
using ytLive.Services.Encoder;
namespace ytLive.ViewModels;
/// <summary>
/// TASK 33, slice 3: the session's step-down watch — policy feed, one encoder relaunch, one toast.
///
/// <para>Kept in its own file because it is the only place that both reads the pump's stats and acts on
/// the session; the pure decision lives in <see cref="StepDownPolicy"/>, the sentence in
/// <see cref="StepDownPlanner"/>.</para>
/// </summary>
public partial class MainViewModel
{
private StepDownPlanner? _stepDownPlanner;
private (int Width, int Height, int Fps, double BitrateMbps)? _encoderTierOverride;
private bool _stepDownBusy;
private double _sessionRatedMbps;
/// <summary>Starts the watch for this broadcast. Called once per session, before the pump starts.</summary>
private void StartStepDownWatch()
{
var quality = EffectiveQuality(OutputProfile.Resolve(SelectedQuality, QualityOptions, HasProOutput));
_encoderTierOverride = null;
_sessionRatedMbps = quality.Bitrate;
_stepDownPlanner = new StepDownPlanner(
new StepDownPolicy(quality.Width, quality.Height, quality.Fps, quality.Bitrate,
floorBitrateMbps: RateLadder.For(quality).Minimum),
_sessionStartedAtUtc ?? DateTime.UtcNow);
_framePump.StatsReported += OnPumpStatsReported;
}
/// <summary>Ends the watch. Called from StopStream on every path, so a stale planner can never
/// carry a spent budget into the next broadcast.</summary>
private void StopStepDownWatch()
{
_framePump.StatsReported -= OnPumpStatsReported;
RecordSessionRate();
_stepDownPlanner = null;
_encoderTierOverride = null;
_stepDownBusy = false;
_screenCaptureManager.ShedLoad(false); // never carry a shed cadence into the next show
}
/// <summary>
/// One finished session, filed as evidence for the rate-history policy (Models/RateHistory).
/// Best effort: a store failure must never be the reason a stop fails.
/// </summary>
private void RecordSessionRate()
{
if (_stepDownPlanner is not { } planner) return;
try
{
_layoutStore.AppendRateHistory(new SessionRateResult(
SelectedQuality.Display,
_framePump.EncoderName ?? "unknown",
_sessionRatedMbps,
planner.Current.BitrateMbps,
planner.Policy.StepsUsed));
}
catch (Exception ex)
{
AppLog.Write($"Rate history not recorded: {ex.Message}", AppLogMessageType.Warning, AppLogErrorClass.Class2);
}
}
/// <summary>Runs on the PUMP thread, so it must never block: the restart it may trigger stops the
/// very loop that raised this event. Decide here (pure and fast), act on the dispatcher.</summary>
private void OnPumpStatsReported(object? sender, FramePumpStats stats)
{
if (_stepDownPlanner is not { } planner) return;
var decision = planner.Observe(stats, DateTime.UtcNow);
if (!decision.Acted) return;
var dispatcher = Application.Current?.Dispatcher;
if (dispatcher == null) return;
_ = dispatcher.InvokeAsync(() => ApplyStepDownAsync(decision));
}
private async void ApplyStepDownAsync(StepDownDecision decision)
{
var planner = _stepDownPlanner;
if (planner == null || _stepDownBusy) return;
_stepDownBusy = true;
var landed = planner.Current;
try
{
if (decision.Action == StepAction.ShedCaptureCadence)
{
_screenCaptureManager.ShedLoad(true);
AppLog.Write($"Capture load shed: {decision.Why}");
return;
}
_encoderTierOverride = landed;
AppLog.Write($"Quality step-down: {decision.Why}");
await _framePump.ChangeEncoderAsync(
_audioMixer.StopLive,
() => _audioMixer.StartLive(InstanceProfile.AudioPipeName(EncoderOptions.DefaultAudioPipeName)));
// Show what is actually going out. The dropdown keeps the creator's choice — the policy
// does not get to rewrite their intent, only the encoder's output.
CurrentHealth.FPS = landed.Fps;
CurrentHealth.CurrentBitrate = landed.BitrateMbps;
ResolutionBadgeText = $"{landed.Width}×{landed.Height} @ {landed.Fps} fps · lowered";
OnPropertyChanged(nameof(CurrentHealth));
OnPropertyChanged(nameof(ResolutionBadgeText));
var copy = StepDownPlanner.Describe(decision, landed);
if (copy.Length > 0)
_notifications.Info("Quality lowered", copy);
AppLog.Write($"Quality step-down complete: {StepDownPlanner.ReportLine(DateTime.Now, decision)}");
}
catch (Exception ex)
{
AppLog.Write($"Quality step-down failed: {ex.Message}", AppLogMessageType.Error, AppLogErrorClass.Class2);
}
finally
{
_stepDownBusy = false;
}
}
}