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;
///
/// TASK 32·1 — a dropped push is retried instead of ending the session. The loop itself lives in
/// (pure, testable); this partial supplies the app-side steps and reports
/// each episode into the left panel's alert stack.
/// Deliberately narrow: only the ENCODER dying is recoverable. A compositor fault still goes
/// through and ends the session, because retrying it would loop.
///
public partial class MainViewModel
{
private CancellationTokenSource? _recoveryCts;
/// True while a push is being relaunched — slice 2 binds the amber sign to this.
public bool IsReconnecting { get; private set; }
/// The attempt currently in flight (0 when idle).
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",
"STREAM",
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;
}
/// The creator asked to stop: never race a stop against a relaunch.
private void CancelStreamRecovery() => _recoveryCts?.Cancel();
}