Browser mai bianco né muto: pagina iniziale, finestra che resta, fotogrammi che ripartono (#52)
Il browser di Febe a volte era bianco o non mostrava nulla. Le cause erano
diverse e si correggono insieme.
- Pagina iniziale. Se il browser è a riposo su about:blank e Alberto lo apre
(«Usa il browser», «Apri il browser»), Febe lo porta sulla home del sito
quando è collegato, altrimenti sulla pagina di accesso. È un'azione di
Alberto, sotto il suo permesso di guida, non del motore: Febe aspetta che
la sessione finisca e prende il turno della pagina.
Il nuovo pulsante «Pagina iniziale» sta nella barra della finestra di
Windows e nella vista remota. Su about:blank la barra dice «Il browser è a
riposo su una pagina vuota». «Indietro» non torna più sulla pagina di
riposo.
- Disconnessione. «Apri il browser» nella striscia rossa apre la pagina di
accesso. Con --accesso-di-prova il primo controllo all'avvio non segnala
più una disconnessione finta.
- Windows: la finestra resta.
- Lasciare una pagina di Febe non nasconde più la finestra «Browser di
Febe» e non la rimette a riposo: finisce solo il permesso tenuto dalla
pagina (cancel con pageLeft, IConnectionService.ReleaseAsync).
- Sullo schermo la finestra ha il suo pulsante nella barra delle
applicazioni, così ridurla a icona non la fa sparire. Dopo 2 minuti
ridotta a icona torna fuori vista (S2).
- Se lo schermo è troppo piccolo, la finestra si restringe all'area di
lavoro e la pagina si rimpicciolisce con ZoomFactor, con le stesse misure
CSS.
- I bordi della pagina si riapplicano, con NotifyParentWindowPositionChanged,
quando la finestra si mostra, si sposta o riparte il processo GPU.
- Una pagina che non risponde mentre Alberto guida resta com'è.
- IBrowserWindow.ShowAsync lascia il posto a
IConnectionService.ShowBrowserAsync.
- Docker: fotogrammi che ripartono. La vista remota ha un watchdog. Riavvia
i fotogrammi dopo una pagina nuova caricata senza fotogrammi e dopo circa
2 s di silenzio. L'attesa raddoppia fino a 30 s finché la pagina resta
ferma. Se il riavvio non porta nulla, la vista riceve un'immagine ferma
(Page.captureScreenshot, già fra i comandi ammessi).
RemoteViewSession ha ora un registro vero: avvii, riavvii e silenzi vanno
a livello Info, categoria «vista», senza indirizzi.
Se dopo 8 s non arriva nessuna immagine, l'interfaccia mostra «Nessuna
immagine dal browser» con «Riprova».
Nessun comando CDP nuovo e nessuna dipendenza nuova. Aggiornati PROTOCOLLO.md
e la guida (Primo collegamento, Attività e arresti, Installazione Windows,
Problemi comuni).
Prove nuove:
- ScreencastWatchdogTests, RemoteViewFramesTests (Chromium vero, solo CI
Linux)
- Home e Indietro in RemoteViewStartTests
- RemoteViewSocketTests
- ConnectionApiTests
- BrowserStartPageTests
- BrowserWindowDecisionTests e BrowserWindowTests (WebView2 vero)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
65c0c4470e
commit
c49df4ca7b
49 files changed
+2056
-177
No files matched your search
@@ -66,7 +66,7 @@ public sealed class RemoteViewSession : IAsyncDisposable
|
||||
|
||||
/// <param name="cdp">The page session.</param>
|
||||
/// <param name="gate">Where the «Alberto is driving» lease is taken.</param>
|
||||
/// <param name="log">Where opening and closing are noted (never keys).</param>
|
||||
/// <param name="log">Where the frames' starts, restarts and silences are noted (never keys).</param>
|
||||
/// <param name="clock">Wall-clock time for the screencast's start attempts; null: the system clock.</param>
|
||||
public RemoteViewSession(ICdpSession cdp, UserDrivingGate gate, IBrowserLog? log = null, IClock? clock = null)
|
||||
{
|
||||
@@ -100,7 +100,8 @@ public sealed class RemoteViewSession : IAsyncDisposable
|
||||
throw;
|
||||
}
|
||||
|
||||
_log.Info("Vista remota aperta: il motore resta fermo finché Alberto usa il browser.");
|
||||
// The host notes the opening in its own words; here only for whoever uses the session alone.
|
||||
_log.Debug("Vista remota aperta: il motore resta fermo finché Alberto usa il browser.");
|
||||
}
|
||||
|
||||
public async Task MouseAsync(RemoteMouseEvent e, CancellationToken ct = default)
|
||||
@@ -198,7 +199,7 @@ public sealed class RemoteViewSession : IAsyncDisposable
|
||||
_buttons = 0;
|
||||
}
|
||||
|
||||
_log.Info("Vista remota chiusa.");
|
||||
_log.Debug("Vista remota chiusa.");
|
||||
}
|
||||
|
||||
public async ValueTask DisposeAsync()
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
using System.Globalization;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Nodes;
|
||||
@@ -13,7 +14,33 @@ namespace Febe.Browser.RemoteView;
|
||||
/// <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>
|
||||
public sealed record ScreencastOptions(int Quality = 70, int MaxWidth = 1280, int MaxHeight = 900, int EveryNthFrame = 1);
|
||||
/// <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 the start brings no frame. 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>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>
|
||||
@@ -24,6 +51,7 @@ public sealed record ScreencastOptions(int Quality = 70, int MaxWidth = 1280, in
|
||||
/// <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,
|
||||
@@ -32,7 +60,8 @@ public sealed record ScreencastFrame(
|
||||
double OffsetTop,
|
||||
double ScrollOffsetX,
|
||||
double ScrollOffsetY,
|
||||
double? Timestamp);
|
||||
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
|
||||
@@ -40,9 +69,16 @@ public sealed record ScreencastFrame(
|
||||
/// <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
|
||||
{
|
||||
@@ -60,15 +96,32 @@ public sealed class ScreencastSession : IAsyncDisposable
|
||||
|
||||
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;
|
||||
|
||||
/// <param name="cdp">The page session.</param>
|
||||
/// <param name="log">Where the start and stop are noted (never parameters or frames).</param>
|
||||
/// <param name="clock">Wall-clock time for the pauses between start attempts; null: the system clock.</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));
|
||||
@@ -79,11 +132,15 @@ public sealed class ScreencastSession : IAsyncDisposable
|
||||
/// <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, for mapping input coordinates.</summary>
|
||||
/// <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)
|
||||
@@ -100,7 +157,20 @@ public sealed class ScreencastSession : IAsyncDisposable
|
||||
|
||||
_ackPump = Task.Run(() => AckPumpAsync(_lifetime.Token), CancellationToken.None);
|
||||
await SendStartAsync(ct).ConfigureAwait(false);
|
||||
_log.Debug("Vista remota avviata.");
|
||||
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>
|
||||
@@ -124,31 +194,44 @@ public sealed class ScreencastSession : IAsyncDisposable
|
||||
events.Reconnected -= OnReconnected;
|
||||
}
|
||||
|
||||
if (_subscription is not null)
|
||||
foreach (var subscription in _pageEvents)
|
||||
{
|
||||
_subscription.Dispose();
|
||||
try
|
||||
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)
|
||||
{
|
||||
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.
|
||||
_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();
|
||||
await _lifetime.CancelAsync().ConfigureAwait(false);
|
||||
if (_ackPump is not null)
|
||||
{
|
||||
try
|
||||
{
|
||||
await _ackPump.ConfigureAwait(false);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
}
|
||||
await Quietly(_ackPump).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
_log.Debug("Vista remota fermata.");
|
||||
@@ -158,6 +241,55 @@ public sealed class ScreencastSession : IAsyncDisposable
|
||||
{
|
||||
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)
|
||||
@@ -182,7 +314,7 @@ public sealed class ScreencastSession : IAsyncDisposable
|
||||
ct).ConfigureAwait(false);
|
||||
if (attempt > 1)
|
||||
{
|
||||
_log.Debug($"Vista remota: fotogrammi avviati al tentativo {attempt.ToString(System.Globalization.CultureInfo.InvariantCulture)}, dopo un cambio di pagina.");
|
||||
_log.Info($"Vista remota: fotogrammi avviati al tentativo {attempt.ToString(CultureInfo.InvariantCulture)}, dopo un cambio di pagina.");
|
||||
}
|
||||
|
||||
return;
|
||||
@@ -206,16 +338,213 @@ public sealed class ScreencastSession : IAsyncDisposable
|
||||
private void OnReconnected(object? sender, EventArgs e) =>
|
||||
_ = Task.Run(async () =>
|
||||
{
|
||||
var ct = _lifetime.Token;
|
||||
try
|
||||
{
|
||||
await SendStartAsync(_lifetime.Token).ConfigureAwait(false);
|
||||
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 (Exception ex) when (ex is not OperationCanceledException)
|
||||
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.</summary>
|
||||
private async Task RestartAsync(ScreencastWatchdog watchdog, TimeSpan silence, bool afterLoad, CancellationToken ct)
|
||||
{
|
||||
await _starts.WaitAsync(ct).ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
bool first;
|
||||
lock (_watch)
|
||||
{
|
||||
first = !_silent;
|
||||
if (first)
|
||||
{
|
||||
_silent = true;
|
||||
_silentSince = _clock.Now - silence;
|
||||
}
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
var before = FramesReceived;
|
||||
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.
|
||||
}
|
||||
|
||||
await SendStartAsync(ct).ConfigureAwait(false);
|
||||
Interlocked.Increment(ref _restarts);
|
||||
if (FramesReceived == before)
|
||||
{
|
||||
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)
|
||||
{
|
||||
_watchFrom = _clock.Now;
|
||||
_restartWanted = false;
|
||||
_framesSinceRestart = 0;
|
||||
var longer = _silenceLimit + _silenceLimit;
|
||||
_silenceLimit = longer < watchdog.LongestSilence ? longer : watchdog.LongestSilence;
|
||||
}
|
||||
|
||||
_starts.Release();
|
||||
}
|
||||
}
|
||||
|
||||
/// <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 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;
|
||||
}
|
||||
|
||||
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))
|
||||
@@ -242,8 +571,35 @@ public sealed class ScreencastSession : IAsyncDisposable
|
||||
Read(meta, "scrollOffsetY"),
|
||||
meta.ValueKind == JsonValueKind.Object && meta.TryGetProperty("timestamp", out var ts) && ts.TryGetDouble(out var t) ? t : null);
|
||||
|
||||
LastFrame = frame;
|
||||
Interlocked.Increment(ref _framesReceived);
|
||||
TimeSpan? resumedAfter = null;
|
||||
lock (_watch)
|
||||
{
|
||||
_lastFrameAt = _clock.Now;
|
||||
_restartWanted = false;
|
||||
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);
|
||||
}
|
||||
@@ -258,11 +614,22 @@ public sealed class ScreencastSession : IAsyncDisposable
|
||||
}
|
||||
catch (Exception ex) when (ex is CdpDisconnectedException or BrowserUnavailableException or CdpCommandException or TimeoutException)
|
||||
{
|
||||
// A lost ack only pauses frames until the next start.
|
||||
// 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;
|
||||
}
|
||||
Reference in new issue
Block a user