diff --git a/PARITY.md b/PARITY.md index 5781e49..e326afa 100644 --- a/PARITY.md +++ b/PARITY.md @@ -39,18 +39,18 @@ Status of each Windows feature on Linux. This file describes the tree it ships w | Feature | Linux | Files | |---|---|---| | Record a region to MP4 | working on X11. Tray **Record video** and `opensnip --record`. | `linux/App.cs`, `linux/RecordingSession.cs`, `linux/FramePump.cs` | -| Wayland recording | missing. The portal ScreenCast API is not wired. The app reports that recording needs an X11 session. | `linux/App.cs` | +| Wayland recording | partial. ScreenCast portal and GStreamer PipeWire plugin feed cropped frames to ffmpeg; share the selected monitor. Restore tokens persist when supported. Pause, mute, audio and countdown use the existing pipeline. Requires GStreamer tools, PipeWire, video conversion/crop/rate plugins. Monitor geometry must be identifiable; mixed-DPI layouts may be rejected. | `linux/PortalScreenCast.cs`, `linux/FramePump.cs`, `linux/RecordingSession.cs`, `linux/App.cs` | | Record the window under the cursor | working on X11. | `linux/OverlayWindow.cs` | | One monitor, even dimensions, 16 px minimum | working | `linux/RecordGeometry.cs` | | 3-2-1 countdown | working | `linux/RecordingChrome.cs` | -| Red outline | working | `linux/RecordingChrome.cs` | +| Red outline | working on X11; Wayland uses Xwayland outlines when available. | `linux/RecordingChrome.cs` | | Pause, microphone mute, stop, discard | working | `linux/RecordingChrome.cs`, `linux/RecordingSession.cs` | -| Outline and bar left out of the video | working on X11. Those rectangles are rebuilt from the wallpaper pixmap and the windows underneath. | `linux/X11FrameSource.cs` | +| Outline and bar left out of the video | working on X11. Those rectangles are rebuilt from the wallpaper pixmap and the windows underneath. Wayland cannot exclude the outline or controls; controls may appear for full-monitor recordings. | `linux/X11FrameSource.cs` | | System audio | partial. PulseAudio or PipeWire monitor source through `pactl` and `ffmpeg`. Video only when `pactl` or a monitor source is missing. | `linux/AudioDevices.cs`, `linux/FfmpegPlan.cs` | | Microphone, off until enabled | partial. Same `pactl` dependency. Mute keeps a silent stream so paused segments stay compatible. | `linux/AudioDevices.cs` | | Hardware H.264 | partial. Software libx264 (CRF 18 high, 28 standard). VAAPI and NVENC are not selected. | `linux/FfmpegPlan.cs` | | 30 or 60 fps | working | `linux/FfmpegPlan.cs`, `linux/SettingsWindow.cs` | -| Mouse cursor in the video | working. XFixes cursor image. | `linux/X11FrameSource.cs` | +| Mouse cursor in the video | working on X11 (XFixes); Wayland requests an embedded cursor when the portal supports it. | `linux/X11FrameSource.cs`, `linux/PortalScreenCast.cs` | | Copy the MP4 | partial. `text/uri-list` through `xclip` or `wl-copy`. | `linux/ClipboardService.cs`, `linux/FileUri.cs` | | Preview still that plays on click | working. Play badge; click opens the file. The preview stays at least 8 seconds. | `linux/ThumbnailWindow.cs`, `linux/App.cs` | | Drag the video preview out | missing | `linux/ThumbnailWindow.cs` | diff --git a/linux/App.cs b/linux/App.cs index 69e9576..0344a92 100644 --- a/linux/App.cs +++ b/linux/App.cs @@ -397,12 +397,13 @@ public async void StartRecording() await ShowErrorAsync("Screen recording needs ffmpeg."); return; } - if (PlatformInfo.IsWayland || !PlatformInfo.HasDisplay) + if (!PlatformInfo.IsWayland && !PlatformInfo.HasDisplay) { - await ShowErrorAsync("Screen recording needs an X11 session."); + await ShowErrorAsync("Screen recording needs a desktop session."); return; } + PortalScreenCast portal = null; _busy = true; try { @@ -414,7 +415,9 @@ public async void StartRecording() var region = await OverlayWindow.SelectAsync(frame, Settings, WindowsFor(frame), record: true); if (region is not { } selected) return; - var monitors = X11Monitors.Query(); + var layouts = OverlaySession.ReadLayouts(frame); + IReadOnlyList monitors = PlatformInfo.IsWayland + ? layouts.Select(m => m.Bounds).ToArray() : X11Monitors.Query(); if (monitors.Count == 0) monitors = new[] { new PixelRect(0, 0, frame.Width, frame.Height) }; if (!RecordGeometry.TryNormalize(selected, monitors, out var area)) @@ -423,10 +426,16 @@ public async void StartRecording() return; } + if (PlatformInfo.IsWayland) + { + portal = await PortalScreenCast.OpenAsync(Settings.RecordCursor); + portal.SetRegion(area, layouts); + } var audio = await Task.Run(AudioDevices.Discover); string system = Settings.RecordSystemAudio ? audio.SystemSource : null; string mic = Settings.RecordMicrophone ? audio.ResolveMicrophone(Settings.MicrophoneDevice) : null; - var session = new RecordingSession(area, Settings, system, mic); + var session = new RecordingSession(area, Settings, system, mic, portal); + portal = null; session.Saved += (path, preview) => Dispatcher.UIThread.Post(() => _ = OnRecordingSavedAsync(session, path, preview)); session.Failed += message => Dispatcher.UIThread.Post(() => { @@ -461,6 +470,7 @@ public async void StartRecording() } finally { + portal?.Dispose(); _busy = false; QuitIfIdle(); } diff --git a/linux/DBus.cs b/linux/DBus.cs index 5d5943a..a0c4bbe 100644 --- a/linux/DBus.cs +++ b/linux/DBus.cs @@ -5,7 +5,7 @@ namespace OpenSnip; sealed record PortalResponse(string Path, uint Code, Dictionary Results); -static class DBus +static partial class DBus { static string SessionAddress { diff --git a/linux/FramePump.cs b/linux/FramePump.cs index 7fe76d8..5bb6057 100644 --- a/linux/FramePump.cs +++ b/linux/FramePump.cs @@ -12,6 +12,8 @@ sealed class FramePump : IDisposable { readonly PixelRect _area; readonly EncodeSpec _spec; + readonly PortalScreenCast _portal; + Process _capture; readonly Func _exclude; readonly object _gate = new(); readonly StringBuilder _stderr = new(); @@ -25,9 +27,10 @@ sealed class FramePump : IDisposable volatile bool _failed; bool _disposed; - public FramePump(PixelRect area, EncodeSpec spec, Func exclude) + public FramePump(PixelRect area, EncodeSpec spec, Func exclude, PortalScreenCast portal = null) { _area = area; + _portal = portal; _spec = spec; _exclude = exclude; } @@ -40,8 +43,11 @@ public void Start() _run = true; _thread = new Thread(Run) { IsBackground = true, Name = "OpenSnip recording" }; _thread.Start(); - if (!_started.Wait(8000)) - throw new InvalidOperationException(_error ?? "ffmpeg did not start."); + if (!_started.Wait(_portal == null ? 8000 : 15000)) + { + Stop(); + throw new InvalidOperationException(_error ?? "Screen capture did not start."); + } if (_failed) throw new InvalidOperationException(string.IsNullOrWhiteSpace(_error) ? "ffmpeg did not start." : _error); } @@ -60,6 +66,7 @@ public CapturedFrame CopyLatest() public void Stop() { _run = false; + try { if (_capture != null && !_capture.HasExited) _capture.Kill(entireProcessTree: true); } catch { } if (_thread != null && !_thread.Join(6000)) { try { _process?.Kill(entireProcessTree: true); } catch { } @@ -75,6 +82,7 @@ public void Dispose() try { Stop(); } catch { } _started.Dispose(); try { _process?.Dispose(); } catch { } + try { _capture?.Dispose(); } catch { } } void Run() @@ -82,7 +90,17 @@ void Run() X11FrameSource source = null; try { - source = new X11FrameSource(_area.X, _area.Y, _area.Width, _area.Height); + if (_portal == null) source = new X11FrameSource(_area.X, _area.Y, _area.Width, _area.Height); + else + { + _capture = _portal.StartFrames(_spec.Framerate); + _capture.ErrorDataReceived += (_, e) => + { + if (e.Data == null) return; + lock (_stderr) { if (_stderr.Length > 8000) _stderr.Clear(); _stderr.AppendLine(e.Data); } + }; + _capture.BeginErrorReadLine(); + } var psi = new ProcessStartInfo("ffmpeg") { UseShellExecute = false, @@ -115,7 +133,7 @@ void Run() } var buffer = new byte[_area.Width * _area.Height * 4]; - _started.Set(); + if (_portal == null) _started.Set(); long interval = Stopwatch.Frequency / Math.Max(1, _spec.Framerate); long next = Stopwatch.GetTimestamp(); while (_run) @@ -136,7 +154,21 @@ void Run() try { exclude = _exclude?.Invoke() ?? exclude; } catch { exclude = Array.Empty(); } - if (!source.Grab(buffer, exclude, _spec.Cursor)) + if (_portal != null) + { + try + { + using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(10)); + _capture.StandardOutput.BaseStream.ReadExactlyAsync(buffer, timeout.Token).AsTask().GetAwaiter().GetResult(); + _started.Set(); + } + catch + { + if (_run) Fail(Stderr("Wayland screen capture stopped or timed out.")); + break; + } + } + else if (!source.Grab(buffer, exclude, _spec.Cursor)) { Fail("Screen capture failed."); break; @@ -168,6 +200,7 @@ void Run() try { _input?.Close(); } catch { } _started.Set(); try { source?.Dispose(); } catch { } + try { if (_capture != null && !_capture.HasExited) _capture.Kill(entireProcessTree: true); } catch { } } } diff --git a/linux/PortalScreenCast.cs b/linux/PortalScreenCast.cs new file mode 100644 index 0000000..5a57334 --- /dev/null +++ b/linux/PortalScreenCast.cs @@ -0,0 +1,275 @@ +using System.Collections.Concurrent; +using System.Diagnostics; +using System.Runtime.InteropServices; +using Microsoft.Win32.SafeHandles; +using Avalonia; +using Tmds.DBus.Protocol; + +namespace OpenSnip; + +/// The connection and PipeWire remote stay alive across pause and mute segments. +sealed class PortalScreenCast : IDisposable +{ + readonly Connection _connection; + readonly string _session; + readonly SafeFileHandle _remote; + readonly uint _node; + readonly PixelRect? _logical; + PixelRect _monitor; + PixelRect _crop; + bool _disposed; + static readonly object SpawnGate = new(); + + internal PortalScreenCast(Connection connection, string session, SafeFileHandle remote, uint node, PixelRect? logical) + { + _connection = connection; + _session = session; + _remote = remote; + _node = node; + _logical = logical; + } + + public static async Task OpenAsync(bool cursor) + { + foreach (string tool in new[] { "gst-launch-1.0", "gst-inspect-1.0" }) + if (!PlatformInfo.CommandExists(tool)) + throw new InvalidOperationException("Wayland recording needs GStreamer and its PipeWire plugin."); + foreach (string plugin in new[] { "pipewiresrc", "videoconvert", "videoscale", "videocrop", "videorate", "fdsink" }) + { + using var check = Process.Start(new ProcessStartInfo("gst-inspect-1.0", plugin) + { + UseShellExecute = false, RedirectStandardOutput = true, RedirectStandardError = true, + }); + var stdout = check.StandardOutput.ReadToEndAsync(); + var stderr = check.StandardError.ReadToEndAsync(); + try { await check.WaitForExitAsync().WaitAsync(TimeSpan.FromSeconds(5)); } + catch (TimeoutException) + { + try { check.Kill(entireProcessTree: true); } catch { } + throw new InvalidOperationException("GStreamer did not respond."); + } + await Task.WhenAll(stdout, stderr); + if (check.ExitCode != 0) + throw new InvalidOperationException($"Wayland recording needs the GStreamer {plugin} plugin."); + } + return await DBus.OpenScreenCastAsync(cursor); + } + + public void SetRegion(PixelRect area, IReadOnlyList layouts) + { + var matches = layouts.Where(m => RecordGeometry.Contains(m.Bounds, area) && + (_logical == null ? layouts.Count == 1 : Matches(_logical.Value, m))).ToArray(); + if (matches.Length != 1) + throw new InvalidOperationException("Select the same monitor in the sharing dialog and recording selection."); + _monitor = matches[0].Bounds; + _crop = Crop(area, _monitor); + } + + internal static bool Matches(PixelRect logical, MonitorLayout monitor) + { + double scale = monitor.ScaleOrOne; + return Math.Abs(logical.X - monitor.Bounds.X / scale) <= 2 && + Math.Abs(logical.Y - monitor.Bounds.Y / scale) <= 2 && + Math.Abs(logical.Width - monitor.Bounds.Width / scale) <= 2 && + Math.Abs(logical.Height - monitor.Bounds.Height / scale) <= 2; + } + + internal static PixelRect Crop(PixelRect area, PixelRect monitor) + { + if (!RecordGeometry.Contains(monitor, area) || area.Width < 16 || area.Height < 16 || + (area.Width & 1) != 0 || (area.Height & 1) != 0) + throw new InvalidOperationException("The recording region must fit the shared monitor."); + return new PixelRect(area.X - monitor.X, area.Y - monitor.Y, area.Width, area.Height); + } + + internal static string[] Arguments(int fd, uint node, PixelRect monitor, PixelRect crop, int fps) => + [ + "-q", "pipewiresrc", $"fd={fd}", $"path={node}", "do-timestamp=true", "!", + "videoconvert", "!", "videoscale", "!", + $"video/x-raw,format=BGRA,width={monitor.Width},height={monitor.Height},pixel-aspect-ratio=1/1", "!", + "videocrop", $"left={crop.X}", $"top={crop.Y}", + $"right={monitor.Width - crop.Right}", $"bottom={monitor.Height - crop.Bottom}", "!", + "videorate", "!", $"video/x-raw,format=BGRA,framerate={fps}/1", "!", "fdsink", "fd=1" + ]; + + public Process StartFrames(int fps) + { + // dup creates an inheritable descriptor; only expose it while launching this child. + lock (SpawnGate) + { + int fd = dup(_remote.DangerousGetHandle().ToInt32()); + if (fd < 0) throw new InvalidOperationException("Could not open the PipeWire remote."); + try + { + var psi = new ProcessStartInfo("gst-launch-1.0") + { + UseShellExecute = false, RedirectStandardOutput = true, RedirectStandardError = true, + }; + foreach (string arg in Arguments(fd, _node, _monitor, _crop, fps)) psi.ArgumentList.Add(arg); + return Process.Start(psi) ?? throw new InvalidOperationException("GStreamer did not start."); + } + finally { close(fd); } + } + } + + public void Dispose() + { + if (_disposed) return; + _disposed = true; + _remote.Dispose(); + try { DBus.CloseScreenCastAsync(_connection, _session).GetAwaiter().GetResult(); } catch { } + _connection.Dispose(); + } + + [DllImport("libc", SetLastError = true)] static extern int dup(int fd); + [DllImport("libc")] static extern int close(int fd); +} + +static partial class DBus +{ + const string Portal = "org.freedesktop.portal.Desktop"; + const string Desktop = "/org/freedesktop/portal/desktop"; + const string ScreenCast = "org.freedesktop.portal.ScreenCast"; + + internal static async Task CloseScreenCastAsync(Connection connection, string session) + { + var writer = connection.GetMessageWriter(); + writer.WriteMethodCallHeader(Portal, session, "org.freedesktop.portal.Session", "Close", "", MessageFlags.None); + await connection.CallMethodAsync(writer.CreateMessage()).WaitAsync(TimeSpan.FromSeconds(3)); + } + + internal static async Task OpenScreenCastAsync(bool cursor) + { + var connection = await ConnectAsync(); + string session = null; + SafeFileHandle remote = null; + try + { + var responses = new ConcurrentDictionary(); + using var signal = new SemaphoreSlim(0); + using var subscription = await connection.AddMatchAsync( + new MatchRule { Type = MessageType.Signal, Sender = Portal, Interface = "org.freedesktop.portal.Request", Member = "Response" }, + (Message message, object state) => + { + var reader = message.GetBodyReader(); + return new PortalResponse(message.PathAsString, reader.ReadUInt32(), reader.ReadDictionaryOfStringToVariantValue()); + }, + (Exception error, PortalResponse value, object readerState, object handlerState) => + { + if (value != null) { responses[value.Path] = value; signal.Release(); } + }, ObserverFlags.None, readerState: null, handlerState: null, emitOnCapturedContext: false); + + async Task> Request(string method, Dictionary options) + { + options["handle_token"] = VariantValue.String("opensnip_" + Guid.NewGuid().ToString("N")); + var writer = connection.GetMessageWriter(); + string signature = method == "CreateSession" ? "a{sv}" : method == "Start" ? "osa{sv}" : "oa{sv}"; + writer.WriteMethodCallHeader(Portal, Desktop, ScreenCast, method, signature, MessageFlags.None); + if (method != "CreateSession") writer.WriteObjectPath(session); + if (method == "Start") writer.WriteString(""); + writer.WriteDictionary(options); + string path = await connection.CallMethodAsync(writer.CreateMessage(), + (Message m, object s) => m.GetBodyReader().ReadObjectPathAsString(), null).WaitAsync(TimeSpan.FromSeconds(10)); + try + { + using var timeout = new CancellationTokenSource(TimeSpan.FromMinutes(2)); + while (true) + { + if (responses.TryRemove(path, out var response)) + { + if (response.Code != 0) + throw new InvalidOperationException(response.Code == 1 ? "Screen sharing was cancelled." : "Screen sharing failed."); + return response.Results; + } + try { await signal.WaitAsync(timeout.Token); } + catch (OperationCanceledException) { throw new InvalidOperationException("Screen sharing timed out."); } + } + } + catch + { + var close = connection.GetMessageWriter(); + close.WriteMethodCallHeader(Portal, path, "org.freedesktop.portal.Request", "Close", "", MessageFlags.None); + try { await connection.CallMethodAsync(close.CreateMessage()).WaitAsync(TimeSpan.FromSeconds(3)); } catch { } + throw; + } + } + + async Task Property(string name) + { + var writer = connection.GetMessageWriter(); + writer.WriteMethodCallHeader(Portal, Desktop, "org.freedesktop.DBus.Properties", "Get", "ss", MessageFlags.None); + writer.WriteString(ScreenCast); + writer.WriteString(name); + return await connection.CallMethodAsync(writer.CreateMessage(), + (Message m, object s) => m.GetBodyReader().ReadVariantValue().GetUInt32(), null).WaitAsync(TimeSpan.FromSeconds(5)); + } + + uint version = await Property("version"); + var created = await Request("CreateSession", new() + { + ["session_handle_token"] = VariantValue.String("opensnip_" + Guid.NewGuid().ToString("N")), + }); + session = created["session_handle"].GetString(); + var options = new Dictionary + { + ["types"] = VariantValue.UInt32(1), ["multiple"] = VariantValue.Bool(false), + }; + if (version >= 2) + { + uint modes = await Property("AvailableCursorModes"); + uint mode = cursor && (modes & 2) != 0 ? 2u : 1u; + if ((modes & mode) == 0) throw new InvalidOperationException("The portal cannot provide the requested cursor mode."); + options["cursor_mode"] = VariantValue.UInt32(mode); + } + string tokenPath = Path.Combine(ConfigPaths.Dir, "screencast-token"); + if (version >= 4) + { + options["persist_mode"] = VariantValue.UInt32(2); + try + { + if (File.Exists(tokenPath)) options["restore_token"] = VariantValue.String(File.ReadAllText(tokenPath).Trim()); + } + catch (Exception ex) { Log.Error(ex); } + } + await Request("SelectSources", options); + var started = await Request("Start", new()); + try + { + if (started.TryGetValue("restore_token", out var token)) + { + Directory.CreateDirectory(ConfigPaths.Dir); + string temp = tokenPath + ".tmp"; + File.WriteAllText(temp, token.GetString()); + if (!OperatingSystem.IsWindows()) File.SetUnixFileMode(temp, UnixFileMode.UserRead | UnixFileMode.UserWrite); + File.Move(temp, tokenPath, true); + } + else if (File.Exists(tokenPath)) File.Delete(tokenPath); + } + catch (Exception ex) { Log.Error(ex); } + var streams = started["streams"]; + if (streams.Count != 1) throw new InvalidOperationException("Share one monitor to record."); + var stream = streams.GetItem(0); + uint node = stream.GetItem(0).GetUInt32(); + var properties = stream.GetItem(1).GetDictionary(); + PixelRect? logical = null; + if (properties.TryGetValue("position", out var position) && properties.TryGetValue("size", out var size)) + logical = new PixelRect(position.GetItem(0).GetInt32(), position.GetItem(1).GetInt32(), + size.GetItem(0).GetInt32(), size.GetItem(1).GetInt32()); + + var open = connection.GetMessageWriter(); + open.WriteMethodCallHeader(Portal, Desktop, ScreenCast, "OpenPipeWireRemote", "oa{sv}", MessageFlags.None); + open.WriteObjectPath(session); + open.WriteDictionary(new Dictionary()); + remote = await connection.CallMethodAsync(open.CreateMessage(), + (Message m, object s) => m.GetBodyReader().ReadHandle(), null).WaitAsync(TimeSpan.FromSeconds(5)); + return new PortalScreenCast(connection, session, remote, node, logical); + } + catch + { + remote?.Dispose(); + if (session != null) try { await CloseScreenCastAsync(connection, session); } catch { } + connection.Dispose(); + throw; + } + } +} diff --git a/linux/RecordingSession.cs b/linux/RecordingSession.cs index fb130f5..55a69eb 100644 --- a/linux/RecordingSession.cs +++ b/linux/RecordingSession.cs @@ -10,6 +10,7 @@ sealed class RecordingSession public event Action Ended; readonly Settings _settings; + readonly PortalScreenCast _portal; readonly string _system; readonly string _mic; readonly string _output; @@ -31,9 +32,10 @@ sealed class RecordingSession public bool MicOn => _micOn; public TimeSpan Elapsed => _clock.Elapsed; - public RecordingSession(PixelRect area, Settings settings, string systemSource, string micSource) + public RecordingSession(PixelRect area, Settings settings, string systemSource, string micSource, PortalScreenCast portal = null) { Area = area; + _portal = portal; _settings = settings; _system = systemSource; _mic = micSource; @@ -128,8 +130,9 @@ void StartEncoder() Cursor = _settings.RecordCursor, Output = _current, }; - var pump = new FramePump(Area, spec, () => _chrome?.WindowIds() ?? Array.Empty()); - pump.Start(); + var pump = new FramePump(Area, spec, () => _chrome?.WindowIds() ?? Array.Empty(), _portal); + try { pump.Start(); } + catch { pump.Dispose(); throw; } _pump = pump; if (!_clock.IsRunning) _clock.Start(); _chrome?.Refresh(); @@ -276,6 +279,7 @@ void End() { if (_ended) return; _ended = true; + _portal?.Dispose(); DeleteTemp(); Ended?.Invoke(); } diff --git a/tests/OpenSnip.Recording.Tests/ScreenCastTests.cs b/tests/OpenSnip.Recording.Tests/ScreenCastTests.cs new file mode 100644 index 0000000..8dd9557 --- /dev/null +++ b/tests/OpenSnip.Recording.Tests/ScreenCastTests.cs @@ -0,0 +1,51 @@ +using Avalonia; + +namespace OpenSnip.Recording.Tests; + +public class ScreenCastTests +{ + [Theory] + [InlineData(-1920, 0)] + [InlineData(0, -1080)] + [InlineData(1920, 100)] + public void CropUsesMonitorLocalPixels(int x, int y) + { + var monitor = new PixelRect(x, y, 1920, 1080); + Assert.Equal(new PixelRect(100, 50, 800, 600), + PortalScreenCast.Crop(new PixelRect(x + 100, y + 50, 800, 600), monitor)); + } + + [Theory] + [InlineData(-1, 0, 100, 100)] + [InlineData(700, 0, 200, 100)] + [InlineData(0, 0, 101, 100)] + [InlineData(0, 0, 14, 100)] + public void CropRejectsInvalidRegions(int x, int y, int width, int height) + { + Assert.Throws(() => PortalScreenCast.Crop( + new PixelRect(x, y, width, height), new PixelRect(0, 0, 800, 600))); + } + + [Fact] + public void PortalGeometryAccountsForScaleAndRejectsAnotherMonitor() + { + var monitor = new MonitorLayout(new PixelRect(0, 0, 3840, 2160), 2, true); + Assert.True(PortalScreenCast.Matches(new PixelRect(0, 0, 1920, 1080), monitor)); + Assert.False(PortalScreenCast.Matches(new PixelRect(1920, 0, 1920, 1080), monitor)); + } + + [Fact] + public void CommandScalesBeforeCroppingAndEmitsOnlyRawBgra() + { + var args = PortalScreenCast.Arguments(42, 123, new PixelRect(-800, 0, 800, 600), + new PixelRect(100, 50, 400, 300), 60); + Assert.Equal(new[] + { + "-q", "pipewiresrc", "fd=42", "path=123", "do-timestamp=true", "!", + "videoconvert", "!", "videoscale", "!", + "video/x-raw,format=BGRA,width=800,height=600,pixel-aspect-ratio=1/1", "!", + "videocrop", "left=100", "top=50", "right=300", "bottom=250", "!", + "videorate", "!", "video/x-raw,format=BGRA,framerate=60/1", "!", "fdsink", "fd=1", + }, args); + } +}