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. public sealed record ScreencastOptions(int Quality = 70, int MaxWidth = 1280, int MaxHeight = 900, int EveryNthFrame = 1); /// 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. public sealed record ScreencastFrame( byte[] Jpeg, double DeviceWidth, double DeviceHeight, double PageScaleFactor, double OffsetTop, double ScrollOffsetX, double ScrollOffsetY, double? Timestamp); /// /// 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. /// 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(); private IDisposable? _subscription; private Task? _ackPump; private ScreencastOptions? _options; private int _stopped; private long _framesReceived; /// The page session. /// Where the start and stop are noted (never parameters or frames). /// Wall-clock time for the pauses between start attempts; 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, for mapping input coordinates. public ScreencastFrame? LastFrame { get; private set; } public long FramesReceived => Interlocked.Read(ref _framesReceived); 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); _log.Debug("Vista remota avviata."); } /// 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; } 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. } } _frames.Writer.TryComplete(); _acks.Writer.TryComplete(); await _lifetime.CancelAsync().ConfigureAwait(false); if (_ackPump is not null) { try { await _ackPump.ConfigureAwait(false); } catch (OperationCanceledException) { } } _log.Debug("Vista remota fermata."); } public async ValueTask DisposeAsync() { await StopAsync().ConfigureAwait(false); _lifetime.Dispose(); } 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.Debug($"Vista remota: fotogrammi avviati al tentativo {attempt.ToString(System.Globalization.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 () => { try { await SendStartAsync(_lifetime.Token).ConfigureAwait(false); } catch (Exception ex) when (ex is not OperationCanceledException) { _log.Warn("Vista remota: non è ripartita dopo il riavvio del browser.", ex); } }); 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); LastFrame = frame; Interlocked.Increment(ref _framesReceived); _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 only pauses frames until the next start. } } } 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; }