Files
LlamaCasty/ViewModels/MainViewModel.Recovery.cs
T
gramps 3fde7fcfe6 refactor(ui): alert rows are two lines of text — the heading line was redundant
Creator: system messages are limited to two lines; the label above the message ('STEAM ID NOT
PRESENT', 'STREAM') was repeating what the row already said and pushing the stack past its budget.

AttentionAlert loses Label; rows render Text only. The licence row is now exactly:
    Steam ID Limit: 30fps
    Click for More Info
(60fps with a close control once owned). Rows are identified by Id internally, so nothing in the UI
depends on the removed text. Tests updated to assert position/text rather than the heading.
2026-11-05 12:13:45 -08:00

149 lines
5.9 KiB
C#

using System;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using ytLive.Helpers;
using ytLive.Services;
using ytLive.Services.Encoder;
namespace ytLive.ViewModels;
/// <summary>
/// TASK 32·1 — a dropped push is retried instead of ending the session. The loop itself lives in
/// <see cref="StreamRecovery"/> (pure, testable); this partial supplies the app-side steps and reports
/// each episode into the left panel's alert stack.
/// <para>Deliberately narrow: only the ENCODER dying is recoverable. A compositor fault still goes
/// through <see cref="OnFramePumpFailed"/> and ends the session, because retrying it would loop.</para>
/// </summary>
public partial class MainViewModel
{
private CancellationTokenSource? _recoveryCts;
/// <summary>True while a push is being relaunched — slice 2 binds the amber sign to this.</summary>
public bool IsReconnecting { get; private set; }
/// <summary>The attempt currently in flight (0 when idle).</summary>
public int ReconnectAttempt { get; private set; }
private void OnEncoderFailed(object? sender, string message)
{
if (!IsLive && !IsRecording) return;
if (_recoveryCts != null) return; // one recovery at a time
if (!IsLive) return; // a recording-only session has nothing to relive
AppLog.Write($"RECONNECT: encoder process failed: {message}");
_recoveryCts = new CancellationTokenSource();
_ = RecoverStreamAsync(message, _recoveryCts.Token);
}
private async Task RecoverStreamAsync(string reason, CancellationToken cancellationToken)
{
IsReconnecting = true;
ReconnectAttempt = 0;
var logFrom = AppLog.SnapshotCurrentLaunch().Count > 0
? AppLog.SnapshotCurrentLaunch()[^1].Sequence + 1
: 1;
var recovery = new StreamRecovery(
StreamRetryPolicy.Default,
new StreamRecoverySteps
{
RestartAudio = _ =>
{
// The audio pipe's server is single-instance and its client just died, so it has
// to be recreated before ffmpeg can attach — otherwise the restart fails on a
// missing input.
_audioMixer.StopLive();
_audioMixer.StartLive(EncoderOptions.DefaultAudioPipeName);
return Task.CompletedTask;
},
StartPush = async ct =>
{
await _framePump.StartAsync(ct);
return _framePump.IsRunning;
},
CheckBroadcast = async ct =>
{
if (_currentBroadcastId == null || _reusableStream?.Id == null)
return BroadcastLiveness.Unknown;
var status = await _youtubeStream.GetBroadcastStatusAsync(_currentBroadcastId);
return status switch
{
"complete" => BroadcastLiveness.Complete,
null => BroadcastLiveness.Unknown,
_ => BroadcastLiveness.Live,
};
},
Report = text =>
{
var progress = text.StartsWith("Stream dropped", StringComparison.Ordinal)
? ParseAttempt(text)
: 0;
if (progress > 0) ReconnectAttempt = progress;
var to = AppLog.SnapshotCurrentLaunch() is { Count: > 0 } entries
? entries[^1].Sequence
: logFrom;
PushAttentionAlert(
"stream-recovery",
text,
logFrom,
Math.Max(logFrom, to));
},
Log = line => AppLog.Write(line, AppLogMessageType.Error, AppLogErrorClass.Class2),
});
try
{
var result = await recovery.RunAsync(cancellationToken);
switch (result.Outcome)
{
case RecoveryOutcome.Recovered:
ReconnectAttempt = result.Attempts;
AppLog.WriteSuccess(
$"RECONNECT: recovered on attempt {result.Attempts} after {result.Elapsed.TotalSeconds:0.0} s");
break;
case RecoveryOutcome.Cancelled:
// The creator stopped the stream mid-recovery: nothing to report.
break;
default:
// Gave up, or the broadcast was already complete: this session is over. The alert
// stack keeps the reason; the normal stop path clears pills, audio and recording.
AppLog.Write("RECONNECT: session ended — the broadcast could not be recovered",
AppLogMessageType.Error, AppLogErrorClass.Class1);
StopStream();
break;
}
}
catch (Exception ex)
{
AppLog.Write(ex, "RECONNECT: recovery loop faulted");
StopStream();
}
finally
{
IsReconnecting = false;
ReconnectAttempt = 0;
_recoveryCts?.Dispose();
_recoveryCts = null;
}
}
private static int ParseAttempt(string text)
{
// "Stream dropped — reconnecting (attempt 2 of 4)"
var marker = text.IndexOf("attempt ", StringComparison.Ordinal);
if (marker < 0) return 0;
var rest = text[(marker + "attempt ".Length)..];
var space = rest.IndexOf(' ');
return int.TryParse(space > 0 ? rest[..space] : rest, out var attempt) ? attempt : 0;
}
/// <summary>The creator asked to stop: never race a stop against a relaunch.</summary>
private void CancelStreamRecovery() => _recoveryCts?.Cancel();
}