Files
Febe/src/Febe.Browser/RemoteView/ScreencastSession.cs
T
Alby96andClaude Opus 5.5 654076d280 Browser vuoto: correzioni dopo la revisione (#52)
La revisione di c49df4c ha trovato alcuni punti deboli. Si correggono qui.

- Fuori vista la pagina torna al 100%. Lo zoom calcolato per uno schermo
  piccolo restava anche per le sessioni del motore, e le pagine vedevano un
  devicePixelRatio diverso (regola 4). Il rapporto si ricalcola solo quando
  la finestra viene sullo schermo.
- Pulsante nella barra delle applicazioni. WPF lo cambia nascondendo la
  finestra e mostrandola di nuovo (verificato con un aggancio a
  WM_WINDOWPOSCHANGED). Ora il pulsante cambia solo mentre la finestra è
  fuori vista. Sullo schermo la finestra chiede di ridisegnarsi
  (RedrawWindow), senza nulla che la pagina veda. Una prova con WebView2
  vero controlla che la finestra non si nasconda mai sullo schermo.
- Ridotta a icona troppo a lungo, la finestra si ripristina coperta (DWM) e
  senza prendere il fuoco, e si sposta fuori vista prima di scoprirsi. Prima
  ricompariva per un attimo dove stava. Spostare la posizione di ripristino
  non basta: Windows la riporta su uno schermo (provato).
- Dopo un riavvio del processo GPU i bordi della pagina cambiano davvero: un
  pixel in meno, poi quelli veri. Gli stessi bordi di nuovo potevano non
  servire a nulla.
- «Pagina iniziale», sulla barra di Windows e nella vista remota, passa da
  BrowserConnectionService.OpenStartPageAsync. Aspetta la fine della
  sessione del motore e il turno della pagina, come l'apertura dal riposo,
  e agisce solo mentre Alberto guida.
- Vista remota.
  - Dopo un riavvio dei fotogrammi la vista aspetta il primo fotogramma per
    mezzo secondo prima dell'immagine ferma: Chromium lo manda solo dopo la
    risposta allo start, e prima quasi ogni riavvio costava una cattura.
  - L'immagine ferma si scarta se nel frattempo arriva un fotogramma vero.
  - Il silenzio si conta dall'avvio.
  - Un riavvio del browser durante la chiusura non lascia eccezioni non
    osservate.
- Un POST vuoto senza Content-Length (a pezzi, HTTP/2) non dà più 400 su
  begin, cancel e browser/show (ApiHttp.OptionalBodyAsync).
- La pagina Browser toglie ?accesso=1 dall'indirizzo. Ricaricarla riapriva
  la pagina di accesso.
- RemoteViewFramesTests aspetta fino a 20 s invece di 5. Controlla che
  l'immagine arrivi, non quanto in fretta; il tempo va nell'uscita della
  prova.

Aggiornati PROTOCOLLO.md, la guida (Primo collegamento, Installazione
Windows) e docs/decisioni.md con le righe di #52.

Prove nuove:
- AFrameSoonAfterARestartNeedsNoStillPicture
- PaginaInizialeWaitsForThePageTurnAndActsOnlyWhileAlbertoIsAtTheBrowser
- ABodyWithoutALengthIsReadAndAnEmptyOneIsNoBody
- nella prova della finestra vera: nessun nascondere sullo schermo e pagina
  al 100% fuori vista

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 13:28:08 +01:00

704 lines
27 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.Globalization;
using System.Runtime.CompilerServices;
using System.Text.Json;
using System.Text.Json.Nodes;
using System.Threading.Channels;
using Febe.Browser.Cdp;
using Febe.Browser.Diagnostics;
using Febe.Core.Abstractions;
namespace Febe.Browser.RemoteView;
/// <summary>Settings of a screencast (<c>Page.startScreencast</c>).</summary>
/// <param name="Quality">JPEG quality, 0–100.</param>
/// <param name="MaxWidth">Largest frame width in pixels.</param>
/// <param name="MaxHeight">Largest frame height in pixels.</param>
/// <param name="EveryNthFrame">Send one frame out of this many.</param>
/// <param name="Watchdog">How missing frames are noticed and the frames started again; null: never (issue #52).</param>
public sealed record ScreencastOptions(int Quality = 70, int MaxWidth = 1280, int MaxHeight = 900, int EveryNthFrame = 1, ScreencastWatchdog? Watchdog = null);
/// <summary>
/// When the remote view starts its frames again (issue #52): Chromium sends a frame only when the page repaints, a
/// lost acknowledgement stops the frames for good, and a change of renderer (another site, the rest page, a crash) may
/// leave the screencast on the old one. After <see cref="Silence"/> without frames — measured from the start, from the
/// last frame or from the last change of document of the main frame — the screencast is stopped and started again (a
/// new screencast session), and one still picture of the page is sent when no frame came within
/// <see cref="FirstFrameWait"/> of the start (Chromium sends the first frame only after answering the start). Each restart
/// doubles the wait, up to <see cref="LongestSilence"/>: a page that does not move (Chromium sends nothing then) costs
/// one restart every so often, not one every two seconds. Frames that flow again (<see cref="FlowingFrames"/> after a
/// restart) or a new document bring the wait back to <see cref="Silence"/>.
/// </summary>
/// <param name="Silence">Time without frames before the first restart.</param>
/// <param name="Tick">How often the watchdog looks.</param>
/// <param name="LongestSilence">The longest wait between two restarts without frames.</param>
public sealed record ScreencastWatchdog(TimeSpan Silence, TimeSpan Tick, TimeSpan LongestSilence)
{
/// <summary>
/// Frames after a restart that show the page is moving: a start alone brings one frame even on a still page, which
/// says that the screencast works, not that it keeps going.
/// </summary>
public const int FlowingFrames = 3;
/// <summary>How long a restart waits for its first frame before it sends a still picture instead.</summary>
public static readonly TimeSpan FirstFrameWait = TimeSpan.FromMilliseconds(500);
/// <summary>About two seconds, looked at four times a second, at most half a minute between restarts.</summary>
public static ScreencastWatchdog Default { get; } = new(TimeSpan.FromSeconds(2), TimeSpan.FromMilliseconds(250), TimeSpan.FromSeconds(30));
}
/// <summary>One frame of the remote view.</summary>
/// <param name="Jpeg">The image.</param>
/// <param name="DeviceWidth">Page width in CSS pixels the frame represents.</param>
/// <param name="DeviceHeight">Page height in CSS pixels the frame represents.</param>
/// <param name="PageScaleFactor">Page zoom.</param>
/// <param name="OffsetTop">Top offset in CSS pixels (browser controls).</param>
/// <param name="ScrollOffsetX">Horizontal scroll position.</param>
/// <param name="ScrollOffsetY">Vertical scroll position.</param>
/// <param name="Timestamp">Browser timestamp (seconds), when given.</param>
/// <param name="Still">True for a still picture (<c>Page.captureScreenshot</c>) sent because no frame came.</param>
public sealed record ScreencastFrame(
byte[] Jpeg,
double DeviceWidth,
double DeviceHeight,
double PageScaleFactor,
double OffsetTop,
double ScrollOffsetX,
double ScrollOffsetY,
double? Timestamp,
bool Still = false);
/// <summary>
/// The remote view's video (spec §4.1, §11): <c>Page.startScreencast</c> in JPEG, every frame acknowledged with
/// <c>Page.screencastFrameAck</c>, stopped with <c>Page.stopScreencast</c>. Frames are delivered through
/// <see cref="ReadFramesAsync"/> (only the latest ones are kept when the reader is slow) and <see cref="FrameReceived"/>.
/// </summary>
/// <remarks>
/// <para>
/// A view opened while the page changes document (the rest page after a session, the login page opened together with
/// the view) can meet the moment in which Chromium refuses the start with «Not attached to an active page»: the start
/// is sent again, a few times, for at most <see cref="InactivePageBudget"/>. Any other failure is reported at once.
/// </para>
/// <para>
/// With a <see cref="ScreencastWatchdog"/> the frames are started again when they stop coming (issue #52): after a
/// silence, and when the main frame finished loading a new document (<c>Page.loadEventFired</c>) without a frame. Every
/// restart, the start after a browser restart and the stop run one at a time, so the stop is never followed by a start.
/// </para>
/// </remarks>
public sealed class ScreencastSession : IAsyncDisposable
{
/// <summary>How long a start refused because the page is between two documents is tried again.</summary>
public static readonly TimeSpan InactivePageBudget = TimeSpan.FromSeconds(5);
private static readonly TimeSpan FirstPause = TimeSpan.FromMilliseconds(100);
private static readonly TimeSpan LongestPause = TimeSpan.FromMilliseconds(500);
private readonly ICdpSession _cdp;
private readonly IBrowserLog _log;
private readonly IClock _clock;
private readonly Channel<ScreencastFrame> _frames = Channel.CreateBounded<ScreencastFrame>(
new BoundedChannelOptions(2) { FullMode = BoundedChannelFullMode.DropOldest, SingleReader = true });
private readonly Channel<int> _acks = Channel.CreateUnbounded<int>(new UnboundedChannelOptions { SingleReader = true });
private readonly CancellationTokenSource _lifetime = new();
// Starts after the first one (watchdog, browser restart) and the stop: one at a time.
private readonly SemaphoreSlim _starts = new(1, 1);
private readonly Lock _watch = new();
private readonly List<IDisposable> _pageEvents = [];
private IDisposable? _subscription;
private Task? _ackPump;
private Task? _watchdog;
private ScreencastOptions? _options;
private int _stopped;
private long _framesReceived;
private long _restarts;
// Guarded by _watch: when silence is measured from, how long it may last, and what the page did meanwhile.
private DateTimeOffset _lastFrameAt;
private DateTimeOffset _watchFrom;
private TimeSpan _silenceLimit;
private long _framesAtNavigation;
private int _framesSinceRestart;
private bool _restartWanted;
private bool _silent;
private DateTimeOffset _silentSince;
private TaskCompletionSource? _nextFrame;
/// <param name="cdp">The page session.</param>
/// <param name="log">Where starts, restarts and silences are noted (never parameters or frames).</param>
/// <param name="clock">Wall-clock time for the pauses between start attempts and the watchdog; null: the system clock.</param>
public ScreencastSession(ICdpSession cdp, IBrowserLog? log = null, IClock? clock = null)
{
_cdp = cdp ?? throw new ArgumentNullException(nameof(cdp));
_log = log ?? NullBrowserLog.Instance;
_clock = clock ?? new SystemClock();
}
/// <summary>Raised on the browser event thread for every frame: handlers must be quick.</summary>
public event EventHandler<ScreencastFrame>? FrameReceived;
/// <summary>The last frame received (or still picture sent), for mapping input coordinates.</summary>
public ScreencastFrame? LastFrame { get; private set; }
/// <summary>Frames of the screencast received so far (still pictures not counted).</summary>
public long FramesReceived => Interlocked.Read(ref _framesReceived);
/// <summary>How many times the watchdog started the frames again.</summary>
public long Restarts => Interlocked.Read(ref _restarts);
public async Task StartAsync(ScreencastOptions? options = null, CancellationToken ct = default)
{
if (_subscription is not null)
{
throw new InvalidOperationException("La vista remota è già avviata.");
}
_options = options ?? new ScreencastOptions();
_subscription = _cdp.On("Page.screencastFrame", OnFrame);
if (_cdp is ICdpConnectionEvents events)
{
events.Reconnected += OnReconnected;
}
_ackPump = Task.Run(() => AckPumpAsync(_lifetime.Token), CancellationToken.None);
await SendStartAsync(ct).ConfigureAwait(false);
if (_options.Watchdog is { } watchdog)
{
lock (_watch)
{
_watchFrom = _clock.Now;
_silenceLimit = watchdog.Silence;
}
_pageEvents.Add(_cdp.On("Page.frameNavigated", OnFrameNavigated));
_pageEvents.Add(_cdp.On("Page.loadEventFired", OnLoadEventFired));
_watchdog = Task.Run(() => WatchAsync(watchdog, _lifetime.Token), CancellationToken.None);
}
_log.Info("Vista remota: fotogrammi avviati.");
}
/// <summary>Frames as they arrive; the oldest are dropped if the reader falls behind. Ends when the session stops.</summary>
public async IAsyncEnumerable<ScreencastFrame> ReadFramesAsync([EnumeratorCancellation] CancellationToken ct = default)
{
await foreach (var frame in _frames.Reader.ReadAllAsync(ct).ConfigureAwait(false))
{
yield return frame;
}
}
public async Task StopAsync(CancellationToken ct = default)
{
if (Interlocked.Exchange(ref _stopped, 1) == 1)
{
return;
}
if (_cdp is ICdpConnectionEvents events)
{
events.Reconnected -= OnReconnected;
}
foreach (var subscription in _pageEvents)
{
subscription.Dispose();
}
// The watchdog and any start under way end first: no start may follow the stop below.
await _lifetime.CancelAsync().ConfigureAwait(false);
if (_watchdog is not null)
{
await Quietly(_watchdog).ConfigureAwait(false);
}
await _starts.WaitAsync(CancellationToken.None).ConfigureAwait(false);
try
{
if (_subscription is not null)
{
_subscription.Dispose();
try
{
await _cdp.SendAsync("Page.stopScreencast", null, ct).ConfigureAwait(false);
}
catch (Exception ex) when (ex is CdpDisconnectedException or BrowserUnavailableException or CdpCommandException)
{
// The browser is gone: nothing to stop.
}
}
}
finally
{
_starts.Release();
}
_frames.Writer.TryComplete();
_acks.Writer.TryComplete();
if (_ackPump is not null)
{
await Quietly(_ackPump).ConfigureAwait(false);
}
_log.Debug("Vista remota fermata.");
}
public async ValueTask DisposeAsync()
{
await StopAsync().ConfigureAwait(false);
_lifetime.Dispose();
_starts.Dispose();
}
/// <summary>The width and height written in a JPEG's frame header (SOFn), or null when the data has none.</summary>
internal static (int Width, int Height)? JpegSize(ReadOnlySpan<byte> jpeg)
{
if (jpeg.Length < 4 || jpeg[0] != 0xFF || jpeg[1] != 0xD8)
{
return null;
}
var i = 2;
while (i + 3 < jpeg.Length)
{
if (jpeg[i] != 0xFF)
{
return null;
}
var marker = jpeg[i + 1];
if (marker == 0xFF)
{
i++;
continue;
}
var length = (jpeg[i + 2] << 8) | jpeg[i + 3];
var isFrame = marker is >= 0xC0 and <= 0xCF && marker is not (0xC4 or 0xC8 or 0xCC);
if (isFrame)
{
if (i + 8 >= jpeg.Length)
{
return null;
}
var height = (jpeg[i + 5] << 8) | jpeg[i + 6];
var width = (jpeg[i + 7] << 8) | jpeg[i + 8];
return width > 0 && height > 0 ? (width, height) : null;
}
if (length < 2)
{
return null;
}
i += 2 + length;
}
return null;
}
private async Task SendStartAsync(CancellationToken ct)
{
var o = _options ?? new ScreencastOptions();
var deadline = _clock.Now + InactivePageBudget;
var pause = FirstPause;
for (var attempt = 1; ; attempt++)
{
try
{
await _cdp.SendAsync(
"Page.startScreencast",
new JsonObject
{
["format"] = "jpeg",
["quality"] = Math.Clamp(o.Quality, 0, 100),
["maxWidth"] = o.MaxWidth,
["maxHeight"] = o.MaxHeight,
["everyNthFrame"] = Math.Max(1, o.EveryNthFrame),
},
ct).ConfigureAwait(false);
if (attempt > 1)
{
_log.Info($"Vista remota: fotogrammi avviati al tentativo {attempt.ToString(CultureInfo.InvariantCulture)}, dopo un cambio di pagina.");
}
return;
}
catch (CdpCommandException ex) when (ex.IsInactivePage && _clock.Now + pause <= deadline)
{
// A navigation is committing in a new frame of the page: nothing is started on the browser side, the
// same start a moment later finds the new document. Past the budget the error goes up as it is.
}
await _clock.Delay(pause, ct).ConfigureAwait(false);
if (Volatile.Read(ref _stopped) == 1)
{
return; // stopped meanwhile (a restart's start in the background): nothing left to start
}
pause = pause * 2 < LongestPause ? pause * 2 : LongestPause;
}
}
private void OnReconnected(object? sender, EventArgs e) =>
_ = Task.Run(async () =>
{
// Read inside the try: a browser restart that races the dispose finds the source disposed.
var ct = CancellationToken.None;
try
{
ct = _lifetime.Token;
await _starts.WaitAsync(ct).ConfigureAwait(false);
try
{
if (Volatile.Read(ref _stopped) == 0)
{
await SendStartAsync(ct).ConfigureAwait(false);
_log.Info("Vista remota: fotogrammi avviati di nuovo dopo il riavvio del browser.");
}
}
finally
{
_starts.Release();
}
lock (_watch)
{
_watchFrom = _clock.Now;
}
}
catch (OperationCanceledException) when (ct.IsCancellationRequested)
{
}
catch (ObjectDisposedException)
{
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
_log.Warn("Vista remota: non è ripartita dopo il riavvio del browser.", ex);
}
});
/// <summary>
/// The watchdog: every <see cref="ScreencastWatchdog.Tick"/> it looks how long no frame came; past the allowed
/// silence (or when a new document loaded without frames) it starts the frames again.
/// </summary>
private async Task WatchAsync(ScreencastWatchdog watchdog, CancellationToken ct)
{
while (!ct.IsCancellationRequested)
{
try
{
await _clock.Delay(watchdog.Tick, ct).ConfigureAwait(false);
bool due;
bool afterLoad;
TimeSpan silence;
lock (_watch)
{
var now = _clock.Now;
var since = _lastFrameAt > _watchFrom ? _lastFrameAt : _watchFrom;
silence = now - since;
afterLoad = _restartWanted;
due = afterLoad || silence >= _silenceLimit;
}
if (due && Volatile.Read(ref _stopped) == 0)
{
await RestartAsync(watchdog, silence, afterLoad, ct).ConfigureAwait(false);
}
}
catch (OperationCanceledException) when (ct.IsCancellationRequested)
{
return;
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
// Never the end of the watchdog: the next look tries again.
_log.Debug($"Vista remota: controllo dei fotogrammi non riuscito ({ex.GetType().Name}).");
}
}
}
/// <summary>
/// Stop and start again (a new screencast session), then one still picture when no frame came within
/// <see cref="ScreencastWatchdog.FirstFrameWait"/>. The silence counts from the start; the wait for the next restart
/// doubles here, before the start, so that frames flowing meanwhile bring it back to the short one.
/// </summary>
private async Task RestartAsync(ScreencastWatchdog watchdog, TimeSpan silence, bool afterLoad, CancellationToken ct)
{
await _starts.WaitAsync(ct).ConfigureAwait(false);
var started = false;
TaskCompletionSource? nextFrame = null;
try
{
bool first;
lock (_watch)
{
first = !_silent;
if (first)
{
_silent = true;
_silentSince = _clock.Now - silence;
}
_restartWanted = false;
_framesSinceRestart = 0;
var longer = _silenceLimit + _silenceLimit;
_silenceLimit = longer < watchdog.LongestSilence ? longer : watchdog.LongestSilence;
}
var seconds = Math.Max(1, (int)Math.Round(silence.TotalSeconds)).ToString(CultureInfo.InvariantCulture);
var why = afterLoad
? "pagina nuova caricata senza fotogrammi"
: $"nessun fotogramma da {seconds} s";
var line = $"Vista remota: {why}, riavvio dei fotogrammi.";
if (first)
{
_log.Info(line);
}
else
{
_log.Debug(line);
}
try
{
await _cdp.SendAsync("Page.stopScreencast", null, ct).ConfigureAwait(false);
}
catch (Exception ex) when (ex is CdpCommandException or TimeoutException)
{
// Nothing was running on the browser side: the start below is what matters.
}
// Ready before the start: its first frame may come as soon as Chromium has answered.
nextFrame = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
lock (_watch)
{
_nextFrame = nextFrame;
}
await SendStartAsync(ct).ConfigureAwait(false);
lock (_watch)
{
_watchFrom = _clock.Now;
}
started = true;
Interlocked.Increment(ref _restarts);
if (!await FrameWithinAsync(nextFrame.Task, ScreencastWatchdog.FirstFrameWait, ct).ConfigureAwait(false))
{
await SendStillAsync(ct).ConfigureAwait(false);
}
}
catch (Exception ex) when (ex is CdpDisconnectedException or BrowserUnavailableException or CdpCommandException or TimeoutException)
{
// The browser is restarting or the page is between two documents for longer than the budget: next time.
_log.Debug($"Vista remota: riavvio dei fotogrammi non riuscito ({ex.GetType().Name}).");
}
finally
{
lock (_watch)
{
if (!started)
{
_watchFrom = _clock.Now; // a failed restart: the next one after a whole silence, not at the next look
}
if (ReferenceEquals(_nextFrame, nextFrame))
{
_nextFrame = null;
}
}
_starts.Release();
}
}
/// <summary>True when <paramref name="frame"/> completes within <paramref name="wait"/> (on the clock).</summary>
private async Task<bool> FrameWithinAsync(Task frame, TimeSpan wait, CancellationToken ct)
{
if (frame.IsCompleted)
{
return true;
}
using var stopWaiting = CancellationTokenSource.CreateLinkedTokenSource(ct);
var delay = _clock.Delay(wait, stopWaiting.Token);
await Task.WhenAny(frame, delay).ConfigureAwait(false);
// Asked of the frame itself, not of which task woke the wait: both may be done by now, and a frame is a frame.
if (frame.IsCompleted)
{
// The pause ends here (a clock that moves only when asked keeps no sleeper behind).
await stopWaiting.CancelAsync().ConfigureAwait(false);
return true;
}
await delay.ConfigureAwait(false); // cancelled with ct: the restart ends there
return false;
}
/// <summary>
/// One picture of the page as it is (<c>Page.captureScreenshot</c>, already allowed for the preview): a page that
/// does not repaint shows something, and the pointer can be placed on it.
/// </summary>
private async Task SendStillAsync(CancellationToken ct)
{
var before = FramesReceived;
var jpeg = await PagePreview.CaptureAsync(_cdp, Math.Clamp((_options ?? new ScreencastOptions()).Quality, 0, 100), ct).ConfigureAwait(false);
if (jpeg.Length == 0 || Volatile.Read(ref _stopped) == 1)
{
return;
}
if (FramesReceived != before)
{
// A real frame came during the capture: it is newer and carries the page's scroll and zoom.
_log.Debug("Vista remota: immagine ferma scartata, è arrivato un fotogramma.");
return;
}
var last = LastFrame;
double width;
double height;
if (last is { DeviceWidth: > 0, DeviceHeight: > 0 })
{
width = last.DeviceWidth;
height = last.DeviceHeight;
}
else if (JpegSize(jpeg) is { } size)
{
// Docker's browser draws at one device pixel per CSS pixel.
width = size.Width;
height = size.Height;
}
else
{
var o = _options ?? new ScreencastOptions();
width = o.MaxWidth;
height = o.MaxHeight;
}
Deliver(new ScreencastFrame(jpeg, width, height, 1, 0, 0, 0, null, Still: true));
_log.Debug("Vista remota: immagine ferma della pagina inviata.");
}
private void OnFrameNavigated(JsonElement e)
{
if (!e.TryGetProperty("frame", out var frame) || frame.TryGetProperty("parentId", out _))
{
return;
}
// A new document in the main frame (perhaps in another renderer): the silence counts from here, short again.
lock (_watch)
{
_watchFrom = _clock.Now;
_framesAtNavigation = FramesReceived;
_silenceLimit = _options?.Watchdog?.Silence ?? _silenceLimit;
_silent = false;
}
}
private void OnLoadEventFired(JsonElement e)
{
lock (_watch)
{
if (FramesReceived == _framesAtNavigation)
{
_restartWanted = true; // loaded and still no frame of it: the next look starts them again
}
}
}
private void OnFrame(JsonElement p)
{
if (!p.TryGetProperty("sessionId", out var sid) || !sid.TryGetInt32(out var sessionId))
{
return;
}
// Acknowledge first, from the pump: the browser sends the next frame only after the ack.
_acks.Writer.TryWrite(sessionId);
if (!p.TryGetProperty("data", out var data) || !data.TryGetBytesFromBase64(out var jpeg))
{
return;
}
var meta = p.TryGetProperty("metadata", out var m) ? m : default;
var frame = new ScreencastFrame(
jpeg,
Read(meta, "deviceWidth"),
Read(meta, "deviceHeight"),
Read(meta, "pageScaleFactor", 1),
Read(meta, "offsetTop"),
Read(meta, "scrollOffsetX"),
Read(meta, "scrollOffsetY"),
meta.ValueKind == JsonValueKind.Object && meta.TryGetProperty("timestamp", out var ts) && ts.TryGetDouble(out var t) ? t : null);
Interlocked.Increment(ref _framesReceived);
TimeSpan? resumedAfter = null;
lock (_watch)
{
_lastFrameAt = _clock.Now;
_restartWanted = false;
_nextFrame?.TrySetResult();
_nextFrame = null;
if (++_framesSinceRestart >= ScreencastWatchdog.FlowingFrames && _options?.Watchdog is { } watchdog)
{
// The page moves: frames flow, and a silence from now on is worth a quick restart again.
_silenceLimit = watchdog.Silence;
if (_silent)
{
_silent = false;
resumedAfter = _lastFrameAt - _silentSince;
}
}
}
if (resumedAfter is { } after)
{
_log.Info($"Vista remota: fotogrammi di nuovo in arrivo, dopo {Math.Max(1, (int)Math.Round(after.TotalSeconds)).ToString(CultureInfo.InvariantCulture)} s di silenzio.");
}
Deliver(frame);
}
private void Deliver(ScreencastFrame frame)
{
LastFrame = frame;
_frames.Writer.TryWrite(frame);
FrameReceived?.Invoke(this, frame);
}
private async Task AckPumpAsync(CancellationToken ct)
{
await foreach (var sessionId in _acks.Reader.ReadAllAsync(ct).ConfigureAwait(false))
{
try
{
await _cdp.SendAsync("Page.screencastFrameAck", new JsonObject { ["sessionId"] = sessionId }, ct).ConfigureAwait(false);
}
catch (Exception ex) when (ex is CdpDisconnectedException or BrowserUnavailableException or CdpCommandException or TimeoutException)
{
// A lost ack pauses the frames: the watchdog, when there is one, starts them again after the silence.
}
}
}
private static async Task Quietly(Task task)
{
try
{
await task.ConfigureAwait(false);
}
catch (OperationCanceledException)
{
}
}
private static double Read(JsonElement meta, string name, double fallback = 0) =>
meta.ValueKind == JsonValueKind.Object && meta.TryGetProperty(name, out var v) && v.TryGetDouble(out var d) ? d : fallback;
}