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; /// Settings of a screencast (Page.startScreencast). /// JPEG quality, 0–100. /// Largest frame width in pixels. /// Largest frame height in pixels. /// Send one frame out of this many. /// How missing frames are noticed and the frames started again; null: never (issue #52). public sealed record ScreencastOptions(int Quality = 70, int MaxWidth = 1280, int MaxHeight = 900, int EveryNthFrame = 1, ScreencastWatchdog? Watchdog = null); /// /// 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 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 /// of the start (Chromium sends the first frame only after answering the start). Each restart /// doubles the wait, up to : 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 ( after a /// restart) or a new document bring the wait back to . /// /// Time without frames before the first restart. /// How often the watchdog looks. /// The longest wait between two restarts without frames. public sealed record ScreencastWatchdog(TimeSpan Silence, TimeSpan Tick, TimeSpan LongestSilence) { /// /// 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. /// public const int FlowingFrames = 3; /// How long a restart waits for its first frame before it sends a still picture instead. public static readonly TimeSpan FirstFrameWait = TimeSpan.FromMilliseconds(500); /// About two seconds, looked at four times a second, at most half a minute between restarts. public static ScreencastWatchdog Default { get; } = new(TimeSpan.FromSeconds(2), TimeSpan.FromMilliseconds(250), TimeSpan.FromSeconds(30)); } /// One frame of the remote view. /// The image. /// Page width in CSS pixels the frame represents. /// Page height in CSS pixels the frame represents. /// Page zoom. /// Top offset in CSS pixels (browser controls). /// Horizontal scroll position. /// Vertical scroll position. /// Browser timestamp (seconds), when given. /// True for a still picture (Page.captureScreenshot) sent because no frame came. public sealed record ScreencastFrame( byte[] Jpeg, double DeviceWidth, double DeviceHeight, double PageScaleFactor, double OffsetTop, double ScrollOffsetX, double ScrollOffsetY, double? Timestamp, bool Still = false); /// /// The remote view's video (spec §4.1, §11): Page.startScreencast in JPEG, every frame acknowledged with /// Page.screencastFrameAck, stopped with Page.stopScreencast. Frames are delivered through /// (only the latest ones are kept when the reader is slow) and . /// /// /// /// 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 . Any other failure is reported at once. /// /// /// With a the frames are started again when they stop coming (issue #52): after a /// silence, and when the main frame finished loading a new document (Page.loadEventFired) 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. /// /// public sealed class ScreencastSession : IAsyncDisposable { /// How long a start refused because the page is between two documents is tried again. 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 _frames = Channel.CreateBounded( new BoundedChannelOptions(2) { FullMode = BoundedChannelFullMode.DropOldest, SingleReader = true }); private readonly Channel _acks = Channel.CreateUnbounded(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 _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; /// The page session. /// Where starts, restarts and silences are noted (never parameters or frames). /// Wall-clock time for the pauses between start attempts and the watchdog; null: the system clock. 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(); } /// Raised on the browser event thread for every frame: handlers must be quick. public event EventHandler? FrameReceived; /// The last frame received (or still picture sent), for mapping input coordinates. public ScreencastFrame? LastFrame { get; private set; } /// Frames of the screencast received so far (still pictures not counted). public long FramesReceived => Interlocked.Read(ref _framesReceived); /// How many times the watchdog started the frames again. 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."); } /// Frames as they arrive; the oldest are dropped if the reader falls behind. Ends when the session stops. public async IAsyncEnumerable 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(); } /// The width and height written in a JPEG's frame header (SOFn), or null when the data has none. internal static (int Width, int Height)? JpegSize(ReadOnlySpan 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); } }); /// /// The watchdog: every it looks how long no frame came; past the allowed /// silence (or when a new document loaded without frames) it starts the frames again. /// 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})."); } } } /// /// Stop and start again (a new screencast session), then one still picture when no frame came within /// . 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. /// 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(); } } /// True when completes within (on the clock). private async Task 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; } /// /// One picture of the page as it is (Page.captureScreenshot, already allowed for the preview): a page that /// does not repaint shows something, and the pointer can be placed on it. /// 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; }