diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 0bb9d2a..b563a4f 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -51,6 +51,7 @@ jobs: run: | sudo apt-get update sudo apt-get install -y xvfb libx11-6 + dotnet test tests/OpenSnip.Recording.Tests/OpenSnip.Recording.Tests.csproj -c Release --nologo dotnet test tests/OpenSnip.Tests/OpenSnip.Tests.csproj -c Release --nologo dotnet test tests/OpenSnip.Hotkeys.Tests/OpenSnip.Hotkeys.Tests.csproj -c Release --nologo diff --git a/PARITY.md b/PARITY.md new file mode 100644 index 0000000..1de802f --- /dev/null +++ b/PARITY.md @@ -0,0 +1,70 @@ +# Linux parity + +Status of each Windows feature on Linux. This file describes the tree it ships with. + +`working` matches Windows. `partial` works with a gap named here. `missing` has no Linux path yet. `not possible` cannot exist on Linux; the closest equivalent is named. + +## Capture + +| Feature | Linux | Files | +|---|---|---| +| Region snip on a frozen screen | working | `linux/Capture.cs`, `linux/OverlayWindow.cs` | +| Click grabs the monitor | working | `linux/OverlayWindow.cs` | +| Click grabs the window under the cursor | partial. X11 only | `linux/OverlayWindow.cs`, `src/CaptureOverlay.cs` | +| `F` selects the monitor | partial. Sets the selection; Enter or the mouse confirms. Windows completes immediately. While recording, `F` completes the monitor. | `linux/OverlayWindow.cs` | +| `A` selects all monitors | partial. Same as `F` for a snip. While recording, `A` completes the one monitor under the cursor. | `linux/OverlayWindow.cs` | +| Enter confirms, arrows nudge, Esc and right-click cancel | working | `linux/OverlayWindow.cs` | +| Magnifier with coordinates | working | `linux/OverlayWindow.cs` | +| Magnifier color | working | `linux/OverlayWindow.cs` | +| X11 capture | working | `linux/Capture.cs` | +| Wayland capture (portal screenshot) | working | `linux/Capture.cs`, `linux/DBus.cs` | +| Copy PNG to the clipboard | working. `xclip` on X11, `wl-copy` on Wayland, then Avalonia. | `linux/ClipboardService.cs` | +| Auto-save PNG or JPG | working | `linux/CapturedFrame.cs`, `linux/SettingsWindow.cs` | +| Monthly folders | working | `src/Settings.cs` | +| Preview thumbnail | working | `linux/ThumbnailWindow.cs` | +| Click the preview to annotate | working | `linux/ThumbnailWindow.cs` | +| Drag the preview into another app | working | `linux/ThumbnailWindow.cs`, `src/SmallWindows.cs` | +| Annotation editor | working | `src/EditorForm.cs` | +| Open the editor after a snip | working | `src/Settings.cs` | +| Pin a snip, including from the clipboard | partial. Pin from clipboard or file; editor pin remains Windows-only | `src/SmallWindows.cs` | +| Delayed snip | working | `linux/CountdownWindow.cs`, `linux/App.cs` | +| Repeat the last region | working | `linux/App.cs` | + +## Screen recording + +| 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` | +| 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` | +| 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` | +| 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` | +| 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` | +| `Win+Shift+R` | missing. The tray item and `opensnip --record` start and stop a recording. A global key grab is not built in. | `linux/App.cs`, `linux/Cli.cs` | +| Tray click stops a recording, otherwise snips | working | `linux/App.cs` | +| Snip blocked while recording | working | `linux/App.cs` | +| Open the recordings folder | working | `linux/App.cs` | +| Save under Videos/OpenSnip as `Recording yyyy-MM-dd HH.mm.ss.mp4` | working | `linux/FfmpegPlan.cs`, `linux/SettingsDefaults.cs` | + +## Shortcuts and settings + +| Feature | Linux | Files | +|---|---|---| +| `Win+Shift+S`, delay, repeat, Print Screen | working on X11. Bind commands in the desktop on Wayland. | `linux/Cli.cs`, `linux/SettingsWindow.cs` | +| Settings pages for capture, saving, recording, shortcuts, general | working. Shortcuts supports X11 key bindings and lists commands on Wayland. | `linux/SettingsWindow.cs` | +| Recording options: system sound, microphone, device, frame rate, quality, cursor, countdown, copy file | working | `linux/SettingsWindow.cs` | +| Reset defaults, including the recording options and video folder | working | `linux/SettingsWindow.cs`, `linux/SettingsDefaults.cs` | +| Start on login | working. XDG autostart. | `linux/Autostart.cs` | +| First-run tray balloon | missing. The tray menu is available as soon as the icon is. | `src/TrayApp.cs`, `linux/App.cs` | +| Diagnostics include capture, clipboard, ffmpeg, and audio devices | working | `linux/Diagnostics.cs` | +| Second launch forwards snip, delay, repeat, record, and settings | working | `linux/SingleInstance.cs` | diff --git a/README.md b/README.md index 310edb3..8944321 100644 --- a/README.md +++ b/README.md @@ -115,9 +115,9 @@ Run `OpenSnip.exe --diagnostics` to write a report (displays, audio devices, and ## Linux -The Linux app is a separate native Avalonia build. It covers screenshots, annotation, pinned images, and global shortcuts on X11; recording remains Windows-only. +The Linux app is a separate native Avalonia build. It covers screenshots, annotation, pinned images, global shortcuts and screen recording on X11. -**What works:** X11 capture through libX11, with `maim`, ImageMagick `import` and `scrot` as fallbacks; Wayland capture through the `xdg-desktop-portal` Screenshot API, with `grim`, `gnome-screenshot` and `spectacle` as fallbacks; region, window, monitor and all-monitor selection with a magnifier; clipboard as PNG; auto-save as PNG or JPG; preview; annotation; pinned images (under the pointer on X11, centered on Wayland); tray icon; global shortcuts on X11; and settings. +**What works:** X11 capture through libX11, with `maim`, ImageMagick `import` and `scrot` as fallbacks; Wayland capture through the `xdg-desktop-portal` Screenshot API, with `grim`, `gnome-screenshot` and `spectacle` as fallbacks; region, window, monitor and all-monitor selection with a magnifier; clipboard as PNG; auto-save as PNG or JPG; preview; annotation; pinned images (under the pointer on X11, centered on Wayland); tray icon; global shortcuts and MP4 recording on X11; and settings. **Install:** download `OpenSnip-linux-x64.tar.gz` from [Releases](https://github.com/DevanMetz/OpenSnip/releases), then: @@ -129,12 +129,14 @@ cd OpenSnip-linux-x64 The installer copies the binary to `~/.local/bin/opensnip`, so make sure `~/.local/bin` is on your `PATH`. -**Requirements:** x64 Linux; X11 or Wayland with `xdg-desktop-portal`; `xclip` (X11) or `wl-clipboard` (Wayland) for clipboard support. A tray host is optional. Without one, Settings opens on launch and closing it quits OpenSnip, unless a pin or editor is still open. `opensnip --pin` opens only the pin, and `opensnip --edit file.png` opens only the editor. +**Requirements:** x64 Linux; X11 or Wayland with `xdg-desktop-portal`; `xclip` (X11) or `wl-clipboard` (Wayland) for clipboard support; `ffmpeg` for screen recording. A tray host is optional. Without one, Settings opens on launch and closing it quits OpenSnip, unless a pin or editor is still open. `opensnip --pin` opens only the pin, and `opensnip --edit file.png` opens only the editor. ### Shortcuts On X11, OpenSnip uses the same shortcuts as Windows. The defaults are `Win` + `Shift` + `S`, `PrtSc`, `Shift` + `PrtSc`, and `Ctrl` + `PrtSc`. Change them in **Settings → Shortcuts**. `Alt` + `PrtSc` and `Win` + `PrtSc` stay with the desktop, as does any chord the desktop already owns. +Recording has no built-in global shortcut; bind `opensnip --record` in the desktop settings. + On Wayland, bind `opensnip --snip`, `opensnip --snip-delay`, or `opensnip --repeat` in the desktop's shortcut settings. Use `opensnip --pin` to pin the clipboard image, `opensnip --pin file.png` to pin a file, `opensnip --edit file.png` to edit an image, and `opensnip --settings` to open settings. ### Selecting a region @@ -151,6 +153,11 @@ On Wayland, bind `opensnip --snip`, `opensnip --snip-delay`, or `opensnip --repe On X11 the outline follows the window under the pointer. On Wayland a click grabs the monitor. +While recording, `F` and `A` record the monitor under the cursor. A recording stays on that one monitor. + +### Screen recording + +Choose **Record video** in the tray, or run `opensnip --record`, then pick a region the same way as a snip. On X11, `ffmpeg` writes an H.264 MP4. A red outline and a bar (pause, microphone, stop, discard) stay on screen and are left out of the file. Videos go to `~/Videos/OpenSnip`. Wayland sessions do not record. ### Annotating Click the preview to annotate, or drag it to drop the file. The tray command **Open image in editor…** and `opensnip --edit file.png` open an existing image. Settings can open the editor instead of the preview. Keys match the editor table above. Pin (`P`) is Windows-only. Edits are copied to the clipboard. @@ -158,6 +165,7 @@ Click the preview to annotate, or drag it to drop the file. The tray command **O ### Command line ```bash +opensnip --record # record a region (X11, needs ffmpeg) opensnip --pin # pin the clipboard image opensnip --pin file.png # pin a file opensnip --capture file.png # capture the whole desktop without UI @@ -177,6 +185,7 @@ dotnet publish linux/OpenSnip.Linux.csproj -c Release -r linux-x64 --self-contai ### Where things live - Screenshots: `~/Pictures/OpenSnip` by default +- Recordings: `~/Videos/OpenSnip` by default - Settings: `~/.config/OpenSnip/settings.json` - Crash log: `~/.config/OpenSnip/error.log` @@ -220,6 +229,7 @@ Issues and pull requests are welcome. The code is plain WinForms + GDI+; recordi | `linux/Capture.cs` / `linux/DBus.cs` | X11, Wayland portal and external capture backends | | `linux/X11Windows.cs` | Top-level X11 windows for click-to-capture | | `linux/OverlayWindow.cs` | Linux selection overlay and magnifier | +| `linux/RecordingSession.cs` | X11 recording, red outline, and control bar | | `linux/PinWindow.cs` | Linux pinned images | | `linux/Annotation.cs` | Annotation shapes for the Linux editor | | `linux/EditorWindow.cs` | Linux annotation editor | diff --git a/linux/App.cs b/linux/App.cs index 9b0a3d0..e64873a 100644 --- a/linux/App.cs +++ b/linux/App.cs @@ -17,14 +17,17 @@ sealed class App : Application IClassicDesktopStyleApplicationLifetime _desktop; TrayIcon _tray; NativeMenuItem _delayItem; + NativeMenuItem _recordItem; SettingsWindow _settingsWindow; ThumbnailWindow _thumbnail; + RecordingSession _recording; X11HotkeyService _hotkeys; readonly List _pins = new(); readonly List _editors = new(); PixelRect? _lastRegion; bool _trayAvailable; bool _busy; + bool _exiting; bool _started; int _pinJobs; @@ -108,6 +111,9 @@ async Task StartAsyncCore() case LaunchAction.Settings: ShowSettings(); break; + case LaunchAction.Record: + ToggleRecording(); + break; case LaunchAction.Pin: _ = PinAsync(argument); break; @@ -125,6 +131,8 @@ void CreateTray() { var menu = new NativeMenu(); menu.Add(Item("Snip", () => StartSnip())); + _recordItem = Item("Record video", () => _ = DelayedRecord()); + menu.Add(_recordItem); _delayItem = Item($"Snip after delay ({Settings.DelaySeconds}s)", () => StartSnip(Settings.DelaySeconds)); menu.Add(_delayItem); menu.Add(Item("Repeat last region", RepeatLast)); @@ -132,6 +140,7 @@ void CreateTray() menu.Add(Item("Pin image from clipboard", () => _ = PinAsync(null))); menu.Add(Item("Open image in editor…", () => _ = OpenImageAsync())); menu.Add(Item("Open screenshots folder", OpenScreenshotsFolder)); + menu.Add(Item("Open recordings folder", OpenRecordingsFolder)); menu.Add(Item("Settings…", () => ShowSettings())); menu.Add(new NativeMenuItemSeparator()); menu.Add(Item("Exit", ExitApp)); @@ -143,7 +152,11 @@ void CreateTray() Menu = menu, IsVisible = true, }; - _tray.Clicked += (_, _) => StartSnip(); + _tray.Clicked += (_, _) => + { + if (_recording != null) ToggleRecording(); + else StartSnip(); + }; TrayIcon.SetIcons(this, new TrayIcons { _tray }); UpdateTrayText(); } @@ -163,11 +176,19 @@ void HandleCommand(RemoteCommand command) case LaunchAction.SnipDelay: StartSnip(Settings.DelaySeconds); break; case LaunchAction.Repeat: RepeatLast(); break; case LaunchAction.Settings: ShowSettings(); break; + case LaunchAction.Record: ToggleRecording(); break; case LaunchAction.Pin: _ = PinAsync(command.Argument); break; case LaunchAction.Edit: OpenEditFile(command.Argument); break; } } + void UpdateRecordingUi() + { + bool on = _recording != null; + if (_recordItem != null) _recordItem.Header = on ? "Stop recording" : "Record video"; + if (_tray != null) _tray.ToolTipText = on ? "OpenSnip — recording (click to stop)" : "OpenSnip"; + } + public void SettingsChanged() { if (_delayItem != null) _delayItem.Header = $"Snip after delay ({Settings.DelaySeconds}s)"; @@ -296,7 +317,7 @@ void ShowPin(CapturedFrame frame) void QuitIfIdle() { - if (!_started || _trayAvailable || _settingsWindow != null || _pins.Count > 0 || _pinJobs > 0 || _editors.Count > 0) return; + if (!_started || _trayAvailable || _busy || _recording != null || _settingsWindow != null || _pins.Count > 0 || _pinJobs > 0 || _editors.Count > 0) return; Dispatcher.UIThread.Post(ExitApp); } @@ -329,9 +350,139 @@ public void OpenScreenshotsFolder() } } + public void OpenRecordingsFolder() + { + try + { + string folder = Settings.FolderFor(Settings.VideoFolder); + Directory.CreateDirectory(folder); + PlatformInfo.Open(folder); + } + catch (Exception ex) + { + Log.Error(ex); + _ = ShowErrorAsync("Could not open the recordings folder: " + ex.Message); + } + } + + async Task DelayedRecord() + { + if (_recording != null) + { + ToggleRecording(); + return; + } + await Task.Delay(200); + if (_exiting || _recording != null || _busy) return; + ToggleRecording(); + } + + public void ToggleRecording() + { + if (_recording != null) + { + try { _recording.Stop(); } + catch (Exception ex) { Log.Error(ex); } + return; + } + StartRecording(); + } + + public async void StartRecording() + { + if (_recording != null || _busy || _exiting) return; + if (!FfmpegPlan.Available) + { + await ShowErrorAsync("Screen recording needs ffmpeg."); + return; + } + if (PlatformInfo.IsWayland || !PlatformInfo.HasDisplay) + { + await ShowErrorAsync("Screen recording needs an X11 session."); + return; + } + + _busy = true; + try + { + bool hadThumbnail = _thumbnail != null; + CloseThumbnail(); + if (hadThumbnail) await Task.Delay(100); + + var frame = await CaptureService.CaptureAsync(); + var overlay = new OverlayWindow(frame, Settings, WindowsFor(frame), record: true); + var region = await overlay.SelectAsync(); + if (region is not { } selected) return; + + var monitors = X11Monitors.Query(); + if (monitors.Count == 0) + monitors = new[] { new PixelRect(0, 0, frame.Width, frame.Height) }; + if (!RecordGeometry.TryNormalize(selected, monitors, out var area)) + { + await ShowErrorAsync("That area is too small to record."); + return; + } + + 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); + session.Saved += (path, preview) => Dispatcher.UIThread.Post(() => _ = OnRecordingSavedAsync(session, path, preview)); + session.Failed += message => Dispatcher.UIThread.Post(() => + { + if (!ReferenceEquals(_recording, session) && _recording != null) return; + _ = ShowErrorAsync(message); + }); + session.Ended += () => Dispatcher.UIThread.Post(() => + { + if (ReferenceEquals(_recording, session)) _recording = null; + UpdateRecordingUi(); + QuitIfIdle(); + }); + _recording = session; + UpdateRecordingUi(); + session.Begin(); + } + catch (CaptureException ex) + { + Log.Error(ex); + await ShowErrorAsync(ex.Message); + } + catch (Exception ex) + { + Log.Error(ex); + await ShowErrorAsync("Couldn't start recording: " + ex.Message); + if (_recording != null) + { + try { _recording.Discard(); } catch { } + _recording = null; + UpdateRecordingUi(); + } + } + finally + { + _busy = false; + QuitIfIdle(); + } + } + + async Task OnRecordingSavedAsync(RecordingSession session, string path, CapturedFrame preview) + { + if (_exiting || (_recording != null && !ReferenceEquals(_recording, session))) return; + bool copied = false; + if (Settings.CopyRecordingToClipboard && !string.IsNullOrEmpty(path)) + { + try { copied = await ClipboardService.CopyFileAsync(path); } + catch (Exception ex) { Log.Error(ex); } + } + if (_exiting) return; + if ((Settings.ShowThumbnail || !copied) && preview != null) + ShowThumbnail(preview, path, Math.Max(Settings.PreviewSeconds, 8), play: true); + } + public async void StartSnip(int delaySeconds = 0) { - if (_busy) return; + if (_recording != null || _busy) return; _busy = true; try { @@ -367,7 +518,7 @@ public async void StartSnip(int delaySeconds = 0) public async void RepeatLast() { - if (_busy) return; + if (_recording != null || _busy) return; if (_lastRegion is not { } region) { StartSnip(); @@ -557,10 +708,10 @@ public async Task OpenImageAsync() } } - void ShowThumbnail(CapturedFrame frame, string path) + void ShowThumbnail(CapturedFrame frame, string path, int? seconds = null, bool play = false) { CloseThumbnail(); - var thumbnail = new ThumbnailWindow(frame, path, Settings.PreviewSeconds); + var thumbnail = new ThumbnailWindow(frame, path, seconds ?? Settings.PreviewSeconds, play); thumbnail.Closed += (_, _) => { if (ReferenceEquals(_thumbnail, thumbnail)) _thumbnail = null; @@ -578,6 +729,7 @@ void CloseThumbnail() async Task ShowErrorAsync(string message) { + if (_exiting || string.IsNullOrWhiteSpace(message)) return; try { var owner = _settingsWindow; @@ -592,6 +744,11 @@ async Task ShowErrorAsync(string message) public void ExitApp() { + if (_exiting) return; + _exiting = true; + try { _recording?.Stop(); } catch (Exception ex) { Log.Error(ex); } + _recording = null; + CloseThumbnail(); try { _hotkeys?.Dispose(); } catch { } _hotkeys = null; try { _tray?.Dispose(); } catch { } diff --git a/linux/AudioDevices.cs b/linux/AudioDevices.cs new file mode 100644 index 0000000..6e4639b --- /dev/null +++ b/linux/AudioDevices.cs @@ -0,0 +1,172 @@ +using System.Diagnostics; +using System.Text; + +namespace OpenSnip; + +/// PulseAudio / PipeWire sources used for system sound and the microphone. +sealed class AudioDevices +{ + public sealed class Device + { + public Device(string name, string description) + { + Name = name ?? ""; + Description = string.IsNullOrWhiteSpace(description) ? Name : description; + } + + public string Name { get; } + public string Description { get; } + } + + public string SystemSource { get; } + public IReadOnlyList Microphones { get; } + public string DefaultMicrophone { get; } + + public AudioDevices(string systemSource, IReadOnlyList microphones, string defaultMicrophone) + { + SystemSource = string.IsNullOrWhiteSpace(systemSource) ? null : systemSource; + Microphones = microphones ?? Array.Empty(); + DefaultMicrophone = string.IsNullOrWhiteSpace(defaultMicrophone) ? null : defaultMicrophone; + } + + public static AudioDevices Empty { get; } = new(null, Array.Empty(), null); + + public string ResolveMicrophone(string preferred) + { + if (Microphones.Count == 0) return null; + if (!string.IsNullOrEmpty(preferred)) + { + foreach (var mic in Microphones) + if (mic.Name == preferred) return mic.Name; + } + if (!string.IsNullOrEmpty(DefaultMicrophone)) + { + foreach (var mic in Microphones) + if (mic.Name == DefaultMicrophone) return mic.Name; + } + return Microphones[0].Name; + } + + public static AudioDevices Discover() + { + try + { + if (!PlatformInfo.CommandExists("pactl")) return Empty; + string sources = Run("pactl", "list", "sources"); + string sink = FirstLine(Run("pactl", "get-default-sink")); + string source = FirstLine(Run("pactl", "get-default-source")); + return ParsePactl(sources, sink, source); + } + catch (Exception ex) + { + Log.Error(ex); + return Empty; + } + } + + public static AudioDevices ParsePactl(string text, string defaultSink, string defaultSource) + { + text ??= ""; + var devices = text.Contains("Name:", StringComparison.Ordinal) + ? ParseVerbose(text) + : ParseShort(text); + return FromDevices(devices, defaultSink?.Trim(), defaultSource?.Trim()); + } + + static List ParseVerbose(string text) + { + var devices = new List(); + string name = null; + string description = null; + void Flush() + { + if (!string.IsNullOrWhiteSpace(name)) + devices.Add(new Device(name.Trim(), description?.Trim())); + name = null; + description = null; + } + + foreach (var raw in text.Split('\n')) + { + string line = raw.Trim(); + if (line.StartsWith("Source #", StringComparison.Ordinal)) + { + Flush(); + continue; + } + if (line.StartsWith("Name:", StringComparison.Ordinal)) name = line["Name:".Length..].Trim(); + else if (line.StartsWith("Description:", StringComparison.Ordinal)) description = line["Description:".Length..].Trim(); + } + Flush(); + return devices; + } + + static List ParseShort(string text) + { + var devices = new List(); + foreach (var raw in text.Split('\n')) + { + if (string.IsNullOrWhiteSpace(raw)) continue; + var parts = raw.Split('\t'); + if (parts.Length < 2) continue; + string name = parts[1].Trim(); + if (name.Length == 0 || name.Contains(' ')) continue; + devices.Add(new Device(name, name)); + } + return devices; + } + + static AudioDevices FromDevices(List devices, string defaultSink, string defaultSource) + { + string monitor = null; + if (!string.IsNullOrEmpty(defaultSink)) + { + string candidate = defaultSink.EndsWith(".monitor", StringComparison.Ordinal) + ? defaultSink + : defaultSink + ".monitor"; + if (devices.Any(d => d.Name == candidate)) monitor = candidate; + } + monitor ??= devices.FirstOrDefault(d => d.Name.EndsWith(".monitor", StringComparison.Ordinal))?.Name; + + var mics = devices.Where(d => !d.Name.EndsWith(".monitor", StringComparison.Ordinal)).ToList(); + string defaultMic = null; + if (!string.IsNullOrEmpty(defaultSource) && mics.Any(m => m.Name == defaultSource)) + defaultMic = defaultSource; + else if (mics.Count > 0) + defaultMic = mics[0].Name; + return new AudioDevices(monitor, mics, defaultMic); + } + + static string FirstLine(string text) + { + if (string.IsNullOrWhiteSpace(text)) return ""; + int cut = text.IndexOfAny(new[] { '\r', '\n' }); + return (cut < 0 ? text : text[..cut]).Trim(); + } + + static string Run(string file, params string[] args) + { + var psi = new ProcessStartInfo(file) + { + UseShellExecute = false, + RedirectStandardOutput = true, + RedirectStandardError = true, + CreateNoWindow = true, + }; + foreach (var arg in args) psi.ArgumentList.Add(arg); + using var process = Process.Start(psi); + if (process == null) return ""; + var output = new StringBuilder(); + process.OutputDataReceived += (_, e) => { if (e.Data != null) output.AppendLine(e.Data); }; + process.ErrorDataReceived += (_, e) => { if (e.Data != null) output.AppendLine(e.Data); }; + process.BeginOutputReadLine(); + process.BeginErrorReadLine(); + if (!process.WaitForExit(2000)) + { + try { process.Kill(entireProcessTree: true); } catch { } + return ""; + } + process.WaitForExit(); + return output.ToString(); + } +} diff --git a/linux/Cli.cs b/linux/Cli.cs index 76f6b74..18adbb6 100644 --- a/linux/Cli.cs +++ b/linux/Cli.cs @@ -7,6 +7,7 @@ enum LaunchAction SnipDelay, Repeat, Settings, + Record, Pin, Edit, } @@ -30,7 +31,7 @@ static class Cli "OpenSnip " + Version + "\n" + "\n" + "Usage:\n" + - " OpenSnip [--snip] [--snip-delay] [--repeat] [--settings] [--pin [file]]\n" + + " OpenSnip [--snip] [--snip-delay] [--repeat] [--record] [--settings] [--pin [file]]\n" + " OpenSnip --edit \n" + " OpenSnip --capture \n" + " OpenSnip --diagnostics [file]\n" + @@ -40,6 +41,7 @@ static class Cli " --snip Capture a region now; starts OpenSnip if needed.\n" + " --snip-delay Capture after the configured delay.\n" + " --repeat Capture the last region again.\n" + + " --record Record a region; starts OpenSnip if needed.\n" + " --settings Open settings; starts OpenSnip if needed.\n" + " --pin [file] Pin the clipboard image, or a file, on screen.\n" + " --edit Open an image in the editor.\n" + @@ -73,6 +75,9 @@ public static CliOptions Parse(string[] args) case "--repeat": action = MergeAction(action, LaunchAction.Repeat); break; + case "--record": + action = MergeAction(action, LaunchAction.Record); + break; case "--settings": action = MergeAction(action, LaunchAction.Settings); break; diff --git a/linux/ClipboardService.cs b/linux/ClipboardService.cs index 870e8c9..9b0a6f8 100644 --- a/linux/ClipboardService.cs +++ b/linux/ClipboardService.cs @@ -18,6 +18,25 @@ static class ClipboardService static Window _hidden; + public static async Task CopyFileAsync(string path) + { + if (string.IsNullOrWhiteSpace(path) || !File.Exists(path)) return false; + var bytes = System.Text.Encoding.UTF8.GetBytes(FileUri.FromPath(path) + "\n"); + if (await TryExternalAsync(bytes, "text/uri-list")) return true; + try + { + var clipboard = ClipboardOf(null); + if (clipboard == null) return false; + await clipboard.SetTextAsync(FileUri.FromPath(path)); + return true; + } + catch (Exception ex) + { + Log.Error(ex); + return false; + } + } + public static string ChooseImageType(IEnumerable types) { if (types == null) return null; @@ -35,7 +54,7 @@ public static string ChooseImageType(IEnumerable types) public static async Task CopyPngAsync(byte[] png, TopLevel topLevel = null) { if (png == null || png.Length == 0) return false; - if (await TryExternalAsync(png)) return true; + if (await TryExternalAsync(png, "image/png")) return true; try { var clipboard = ClipboardOf(topLevel); @@ -251,19 +270,19 @@ static IClipboard ClipboardOf(TopLevel topLevel) return _hidden.Clipboard; } - static async Task TryExternalAsync(byte[] png) + static async Task TryExternalAsync(byte[] payload, string mime) { string command = null; string[] args = null; if (PlatformInfo.IsWayland && PlatformInfo.CommandExists("wl-copy")) { command = "wl-copy"; - args = new[] { "--type", "image/png" }; + args = new[] { "--type", mime }; } else if (!PlatformInfo.IsWayland && PlatformInfo.CommandExists("xclip")) { command = "xclip"; - args = new[] { "-selection", "clipboard", "-t", "image/png", "-i" }; + args = new[] { "-selection", "clipboard", "-t", mime, "-i" }; } if (command == null) return false; @@ -279,7 +298,7 @@ static async Task TryExternalAsync(byte[] png) foreach (var arg in args) psi.ArgumentList.Add(arg); using var process = Process.Start(psi); if (process == null) return false; - await process.StandardInput.BaseStream.WriteAsync(png); + await process.StandardInput.BaseStream.WriteAsync(payload); process.StandardInput.Close(); using var cts = new CancellationTokenSource(3000); diff --git a/linux/Diagnostics.cs b/linux/Diagnostics.cs index 98094bd..e665c2e 100644 --- a/linux/Diagnostics.cs +++ b/linux/Diagnostics.cs @@ -28,6 +28,12 @@ public static async Task RunAsync(string file) bool tray = await DBus.TrayHostAvailableAsync(); report.AppendLine("xdg-desktop-portal: " + (portal ? "available" : "unavailable")); report.AppendLine("Tray host: " + (tray ? "available" : "unavailable")); + report.AppendLine("ffmpeg: " + (FfmpegPlan.Available ? "available" : "missing")); + var audio = AudioDevices.Discover(); + report.AppendLine("System audio: " + (audio.SystemSource ?? "none")); + report.AppendLine("Microphones: " + (audio.Microphones.Count == 0 + ? "none" + : string.Join(", ", audio.Microphones.Select(mic => mic.Description)))); var settings = Settings.Load(); SettingsDefaults.ApplyLinux(settings); string shortcuts = X11HotkeyService.IsSupported ? HotkeyBindings.From(settings).Summary : "off"; diff --git a/linux/FfmpegPlan.cs b/linux/FfmpegPlan.cs new file mode 100644 index 0000000..1d1e6a5 --- /dev/null +++ b/linux/FfmpegPlan.cs @@ -0,0 +1,141 @@ +using System.Globalization; +using System.Text; + +namespace OpenSnip; + +sealed class EncodeSpec +{ + public int Width; + public int Height; + public int Framerate; + public bool HighQuality; + public string SystemSource; + public string MicSource; + public bool MicOn; + public bool Cursor; + public string Output; +} + +/// ffmpeg command lines for one segment and for joining a paused recording back together. +static class FfmpegPlan +{ + public static bool Available => PlatformInfo.CommandExists("ffmpeg"); + + public static int NormalizeFramerate(int value) + { + if (value < 1) return 30; + if (value > 60) return 60; + return value; + } + + /// Windows quality 85 / 65, expressed as x264 CRF. Lower is sharper. + public static int Crf(bool highQuality) => highQuality ? 18 : 28; + + public static List EncodeArguments(EncodeSpec spec) + { + int framerate = NormalizeFramerate(spec.Framerate); + var args = new List + { + "-hide_banner", "-loglevel", "error", "-y", + "-f", "rawvideo", + "-pixel_format", "bgra", + "-video_size", spec.Width.ToString(CultureInfo.InvariantCulture) + "x" + spec.Height.ToString(CultureInfo.InvariantCulture), + "-framerate", framerate.ToString(CultureInfo.InvariantCulture), + // Arrival time, not frame index, so the picture stays in step with PulseAudio. + "-use_wallclock_as_timestamps", "1", + "-i", "pipe:0", + }; + + bool system = !string.IsNullOrEmpty(spec.SystemSource); + bool mic = !string.IsNullOrEmpty(spec.MicSource); + if (system) AddPulse(args, spec.SystemSource); + if (mic) AddPulse(args, spec.MicSource); + + if (system && mic) + { + string volume = spec.MicOn ? "1" : "0"; + args.Add("-filter_complex"); + args.Add("[1:a]aformat=sample_fmts=fltp:channel_layouts=stereo[sys];" + + "[2:a]aformat=sample_fmts=fltp:channel_layouts=stereo,volume=" + volume + "[mic];" + + "[sys][mic]amix=inputs=2:duration=longest:dropout_transition=0[aout]"); + args.Add("-map"); + args.Add("0:v:0"); + args.Add("-map"); + args.Add("[aout]"); + } + else if (mic && !spec.MicOn) + { + // Every segment keeps the mic stream so a later concat does not see a different layout. + args.Add("-filter_complex"); + args.Add("[1:a]volume=0[aout]"); + args.Add("-map"); + args.Add("0:v:0"); + args.Add("-map"); + args.Add("[aout]"); + } + + args.Add("-c:v"); + args.Add("libx264"); + args.Add("-preset"); + args.Add("veryfast"); + args.Add("-crf"); + args.Add(Crf(spec.HighQuality).ToString(CultureInfo.InvariantCulture)); + args.Add("-pix_fmt"); + args.Add("yuv420p"); + args.Add("-movflags"); + args.Add("+faststart"); + + if (system || mic) + { + args.Add("-c:a"); + args.Add("aac"); + args.Add("-b:a"); + args.Add("192k"); + } + else args.Add("-an"); + + args.Add(spec.Output); + return args; + } + + static void AddPulse(List args, string source) + { + args.Add("-thread_queue_size"); + args.Add("1024"); + args.Add("-f"); + args.Add("pulse"); + args.Add("-i"); + args.Add(source); + } + + public static List ConcatArguments(string listFile, string output) => new() + { + "-hide_banner", "-loglevel", "error", "-y", + "-f", "concat", "-safe", "0", "-i", listFile, + "-c", "copy", "-movflags", "+faststart", + output, + }; + + public static string ConcatList(IReadOnlyList files) + { + var builder = new StringBuilder(); + foreach (var file in files) + { + builder.Append("file '"); + builder.Append((file ?? "").Replace("'", "'\\''", StringComparison.Ordinal)); + builder.Append("'\n"); + } + return builder.ToString(); + } + + public static string NewRecordingPath(string folder) + { + Directory.CreateDirectory(folder); + string stamp = DateTime.Now.ToString("yyyy-MM-dd HH.mm.ss", CultureInfo.InvariantCulture); + string path = Path.Combine(folder, "Recording " + stamp + ".mp4"); + int n = 2; + while (File.Exists(path)) + path = Path.Combine(folder, "Recording " + stamp + " (" + n++ + ").mp4"); + return path; + } +} diff --git a/linux/FileUri.cs b/linux/FileUri.cs new file mode 100644 index 0000000..7a2bdee --- /dev/null +++ b/linux/FileUri.cs @@ -0,0 +1,23 @@ +using System.Text; + +namespace OpenSnip; + +static class FileUri +{ + public static string FromPath(string path) + { + string full = Path.GetFullPath(path); + var builder = new StringBuilder("file://"); + foreach (byte b in Encoding.UTF8.GetBytes(full)) + { + bool safe = b == (byte)'/' + || (b >= (byte)'A' && b <= (byte)'Z') + || (b >= (byte)'a' && b <= (byte)'z') + || (b >= (byte)'0' && b <= (byte)'9') + || b == (byte)'-' || b == (byte)'.' || b == (byte)'_' || b == (byte)'~'; + if (safe) builder.Append((char)b); + else builder.Append('%').Append(b.ToString("X2")); + } + return builder.ToString(); + } +} diff --git a/linux/FramePump.cs b/linux/FramePump.cs new file mode 100644 index 0000000..7fe76d8 --- /dev/null +++ b/linux/FramePump.cs @@ -0,0 +1,209 @@ +using System.Diagnostics; +using System.Text; +using Avalonia; + +namespace OpenSnip; + +/// +/// Feeds BGRA frames to one ffmpeg process. Stopping closes ffmpeg's input so the MP4 is finalized. +/// Pause is a stop plus a new segment: a live PulseAudio input would keep running if the process stayed up. +/// +sealed class FramePump : IDisposable +{ + readonly PixelRect _area; + readonly EncodeSpec _spec; + readonly Func _exclude; + readonly object _gate = new(); + readonly StringBuilder _stderr = new(); + readonly ManualResetEventSlim _started = new(false); + Thread _thread; + Process _process; + Stream _input; + byte[] _latest; + string _error; + volatile bool _run; + volatile bool _failed; + bool _disposed; + + public FramePump(PixelRect area, EncodeSpec spec, Func exclude) + { + _area = area; + _spec = spec; + _exclude = exclude; + } + + public bool Failed => _failed; + public string Error => _error; + + 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 (_failed) + throw new InvalidOperationException(string.IsNullOrWhiteSpace(_error) ? "ffmpeg did not start." : _error); + } + + public CapturedFrame CopyLatest() + { + lock (_gate) + { + if (_latest == null) return null; + var copy = new byte[_latest.Length]; + Buffer.BlockCopy(_latest, 0, copy, 0, copy.Length); + return new CapturedFrame(_area.Width, _area.Height, copy); + } + } + + public void Stop() + { + _run = false; + if (_thread != null && !_thread.Join(6000)) + { + try { _process?.Kill(entireProcessTree: true); } catch { } + _thread.Join(2000); + } + WaitForExit(); + } + + public void Dispose() + { + if (_disposed) return; + _disposed = true; + try { Stop(); } catch { } + _started.Dispose(); + try { _process?.Dispose(); } catch { } + } + + void Run() + { + X11FrameSource source = null; + try + { + source = new X11FrameSource(_area.X, _area.Y, _area.Width, _area.Height); + var psi = new ProcessStartInfo("ffmpeg") + { + UseShellExecute = false, + RedirectStandardInput = true, + RedirectStandardOutput = true, + RedirectStandardError = true, + CreateNoWindow = true, + }; + foreach (var arg in FfmpegPlan.EncodeArguments(_spec)) psi.ArgumentList.Add(arg); + _process = Process.Start(psi); + if (_process == null) + { + Fail("ffmpeg did not start."); + return; + } + _process.OutputDataReceived += (_, _) => { }; + _process.ErrorDataReceived += (_, e) => + { + if (e.Data == null) return; + lock (_stderr) _stderr.AppendLine(e.Data); + }; + _process.BeginOutputReadLine(); + _process.BeginErrorReadLine(); + _input = _process.StandardInput.BaseStream; + + if (_process.WaitForExit(200)) + { + Fail(Stderr("ffmpeg failed.")); + return; + } + + var buffer = new byte[_area.Width * _area.Height * 4]; + _started.Set(); + long interval = Stopwatch.Frequency / Math.Max(1, _spec.Framerate); + long next = Stopwatch.GetTimestamp(); + while (_run) + { + long now = Stopwatch.GetTimestamp(); + if (now < next) + { + int wait = (int)((next - now) * 1000 / Stopwatch.Frequency); + if (wait > 2) Thread.Sleep(wait - 1); + while (_run && Stopwatch.GetTimestamp() < next) { } + if (!_run) break; + } + next += interval; + long after = Stopwatch.GetTimestamp(); + if (next < after) next = after + interval; + + long[] exclude = Array.Empty(); + try { exclude = _exclude?.Invoke() ?? exclude; } + catch { exclude = Array.Empty(); } + + if (!source.Grab(buffer, exclude, _spec.Cursor)) + { + Fail("Screen capture failed."); + break; + } + try + { + _input.Write(buffer, 0, buffer.Length); + _input.Flush(); + } + catch (Exception ex) + { + if (_run) Fail(Stderr(ex.Message)); + break; + } + lock (_gate) + { + _latest ??= new byte[buffer.Length]; + Buffer.BlockCopy(buffer, 0, _latest, 0, buffer.Length); + } + } + } + catch (Exception ex) + { + Fail(ex.Message); + Log.Error(ex); + } + finally + { + try { _input?.Close(); } catch { } + _started.Set(); + try { source?.Dispose(); } catch { } + } + } + + void Fail(string message) + { + if (string.IsNullOrWhiteSpace(_error)) _error = string.IsNullOrWhiteSpace(message) ? "Recording failed." : message; + _failed = true; + _run = false; + } + + string Stderr(string fallback) + { + string text; + lock (_stderr) text = _stderr.ToString().Trim(); + if (text.Length > 500) text = text[^500..]; + return string.IsNullOrWhiteSpace(text) ? fallback : text; + } + + void WaitForExit() + { + var process = _process; + if (process == null) return; + try + { + if (!process.HasExited && !process.WaitForExit(8000)) + { + try { process.Kill(entireProcessTree: true); } catch { } + process.WaitForExit(2000); + } + } + catch { } + try + { + if (process.HasExited && process.ExitCode != 0 && !_failed) + Fail(Stderr("ffmpeg failed.")); + } + catch { } + } +} diff --git a/linux/MessageDialog.cs b/linux/MessageDialog.cs index 39c3643..54e4300 100644 --- a/linux/MessageDialog.cs +++ b/linux/MessageDialog.cs @@ -12,12 +12,12 @@ public static async Task AlertAsync(Window owner, string message) await ShowAsync(owner, message, confirm: false); } - public static async Task ConfirmAsync(Window owner, string message) + public static async Task ConfirmAsync(Window owner, string message, string accept = "Reset") { - return await ShowAsync(owner, message, confirm: true); + return await ShowAsync(owner, message, confirm: true, accept); } - static async Task ShowAsync(Window owner, string message, bool confirm) + static async Task ShowAsync(Window owner, string message, bool confirm, string accept = "OK") { var result = false; var window = new Window @@ -52,7 +52,7 @@ static async Task ShowAsync(Window owner, string message, bool confirm) cancel.Click += (_, _) => window.Close(); buttons.Children.Add(cancel); } - var ok = new Button { Content = confirm ? "Reset" : "OK" }; + var ok = new Button { Content = confirm ? accept : "OK" }; ok.Click += (_, _) => { result = true; window.Close(); }; buttons.Children.Add(ok); diff --git a/linux/OpenSnip.Linux.csproj b/linux/OpenSnip.Linux.csproj index d785a18..4304530 100644 --- a/linux/OpenSnip.Linux.csproj +++ b/linux/OpenSnip.Linux.csproj @@ -27,4 +27,8 @@ + + + + diff --git a/linux/OverlayWindow.cs b/linux/OverlayWindow.cs index db230ce..2a82850 100644 --- a/linux/OverlayWindow.cs +++ b/linux/OverlayWindow.cs @@ -14,7 +14,7 @@ sealed class OverlayWindow : Window readonly PixelRect _virtualBounds; readonly CaptureCanvas _canvas; - public OverlayWindow(CapturedFrame frame, Settings settings, PixelRect[] windows = null) + public OverlayWindow(CapturedFrame frame, Settings settings, PixelRect[] windows = null, bool record = false) { var screens = Screens.All; PixelRect union = screens.Count > 0 ? screens[0].Bounds : new PixelRect(0, 0, frame.Width, frame.Height); @@ -38,7 +38,7 @@ public OverlayWindow(CapturedFrame frame, Settings settings, PixelRect[] windows Width = Math.Max(1, union.Width / scale); Height = Math.Max(1, union.Height / scale); - _canvas = new CaptureCanvas(frame, settings, union, windows, Complete); + _canvas = new CaptureCanvas(frame, settings, union, windows, Complete, record); Content = _canvas; Closed += (_, _) => _result.TrySetResult(null); } @@ -84,6 +84,9 @@ sealed class CaptureCanvas : Control readonly bool _windowsAlign; readonly Action _complete; readonly Typeface _typeface = new("Inter"); + readonly bool _record; + readonly IPen _framePen; + readonly IPen _hairPen; bool _pressing; bool _dragging; @@ -97,10 +100,8 @@ sealed class CaptureCanvas : Control static readonly IBrush DimBrush = new SolidColorBrush(Color.FromArgb(150, 0, 0, 0)); static readonly IBrush ReadoutBrush = new SolidColorBrush(Color.FromArgb(238, 38, 38, 44)); - static readonly IPen AccentPen = new Pen(AppTheme.Accent, 2); - static readonly IPen CrosshairPen = new Pen(AppTheme.Accent, 1); - public CaptureCanvas(CapturedFrame frame, Settings settings, PixelRect virtualBounds, PixelRect[] windows, Action complete) + public CaptureCanvas(CapturedFrame frame, Settings settings, PixelRect virtualBounds, PixelRect[] windows, Action complete, bool record = false) { _frame = frame; _bitmap = frame.ToBitmap(); @@ -109,6 +110,10 @@ public CaptureCanvas(CapturedFrame frame, Settings settings, PixelRect virtualBo _windows = windows ?? Array.Empty(); _windowsAlign = frame.Width == virtualBounds.Width && frame.Height == virtualBounds.Height; _complete = complete; + _record = record; + var color = record ? AppTheme.Record : AppTheme.Accent; + _framePen = new Pen(color, 2); + _hairPen = new Pen(color, 1); Focusable = true; ClipToBounds = true; } @@ -125,6 +130,11 @@ public bool HandleKey(KeyEventArgs e) else _complete(HitAt(CurrentCursor()).Image); return true; case Key.A: + if (_record) + { + _complete(ToImageRect(MonitorRect(CurrentCursor()))); + return true; + } _pressing = false; _dragging = false; _selection = new Rect(0, 0, Bounds.Width, Bounds.Height); @@ -133,6 +143,11 @@ public bool HandleKey(KeyEventArgs e) InvalidateVisual(); return true; case Key.F: + if (_record) + { + _complete(ToImageRect(MonitorRect(CurrentCursor()))); + return true; + } _pressing = false; _dragging = false; _selection = MonitorRect(CurrentCursor()); @@ -371,7 +386,7 @@ public override void Render(DrawingContext context) context.FillRectangle(DimBrush, bottom); context.FillRectangle(DimBrush, left); context.FillRectangle(DimBrush, right); - context.DrawRectangle(null, AccentPen, selection); + context.DrawRectangle(null, _framePen, selection); readout = DrawReadout(context, selection, _selection == null ? _hoverImage : null); } else @@ -383,8 +398,8 @@ public override void Render(DrawingContext context) { if (_keyboardCursor) { - context.DrawLine(CrosshairPen, new Point(_cursor.X - 8, _cursor.Y), new Point(_cursor.X + 8, _cursor.Y)); - context.DrawLine(CrosshairPen, new Point(_cursor.X, _cursor.Y - 8), new Point(_cursor.X, _cursor.Y + 8)); + context.DrawLine(_hairPen, new Point(_cursor.X - 8, _cursor.Y), new Point(_cursor.X + 8, _cursor.Y)); + context.DrawLine(_hairPen, new Point(_cursor.X, _cursor.Y - 8), new Point(_cursor.X, _cursor.Y + 8)); } if (_settings.ShowMagnifier) DrawMagnifier(context, readout); } @@ -493,7 +508,7 @@ void DrawMagnifier(DrawingContext context, Rect? readout) double squareX = box.X + (boxW - square) / 2; var dest = new Rect(squareX + pad, box.Y + pad, inner, inner); - context.DrawRectangle(ReadoutBrush, new Pen(AppTheme.Accent, 2), new Rect(box.X, box.Y, boxW, square + labelHeight), 7, 7); + context.DrawRectangle(ReadoutBrush, _framePen, new Rect(box.X, box.Y, boxW, square + labelHeight), 7, 7); // Keep the source centered on the cursor. Clamping it used to slide the // crosshair off the real pixel once the cursor reached the screen edge. @@ -518,8 +533,8 @@ void DrawMagnifier(DrawingContext context, Rect? readout) double cx = dest.X + (imageX - left + 0.5) * scale; double cy = dest.Y + (imageY - top + 0.5) * scale; - context.DrawLine(CrosshairPen, new Point(cx - 7, cy), new Point(cx + 7, cy)); - context.DrawLine(CrosshairPen, new Point(cx, cy - 7), new Point(cx, cy + 7)); + context.DrawLine(_hairPen, new Point(cx - 7, cy), new Point(cx + 7, cy)); + context.DrawLine(_hairPen, new Point(cx, cy - 7), new Point(cx, cy + 7)); context.DrawText(label, new Point(box.X + (boxW - label.Width) / 2, box.Y + square + 2)); } diff --git a/linux/RecordGeometry.cs b/linux/RecordGeometry.cs new file mode 100644 index 0000000..d156c05 --- /dev/null +++ b/linux/RecordGeometry.cs @@ -0,0 +1,105 @@ +using Avalonia; + +namespace OpenSnip; + +/// +/// Recording regions cover one monitor and H.264 wants even dimensions. +/// The control bar prefers a spot that does not cover the recorded pixels. +/// +static class RecordGeometry +{ + public const int MinSize = 16; + + public static bool TryNormalize(PixelRect selection, IReadOnlyList monitors, out PixelRect area) + { + area = default; + if (monitors == null || monitors.Count == 0) return false; + if (selection.Width <= 0 || selection.Height <= 0) return false; + + int best = -1; + var monitor = default(PixelRect); + foreach (var candidate in monitors) + { + int overlap = OverlapArea(selection, candidate); + if (overlap > best) + { + best = overlap; + monitor = candidate; + } + } + if (best <= 0) return false; + + var clipped = Intersect(selection, monitor); + int width = clipped.Width & ~1; + int height = clipped.Height & ~1; + if (width < MinSize || height < MinSize) return false; + area = new PixelRect(clipped.X, clipped.Y, width, height); + return true; + } + + /// Red bars drawn on the inside edge of so a full-monitor selection still shows a frame. + public static PixelRect[] Outline(PixelRect area, int thickness) + { + int t = Math.Max(1, thickness); + if (area.Width <= t * 2 || area.Height <= t * 2) return Array.Empty(); + return new[] + { + new PixelRect(area.X, area.Y, area.Width, t), + new PixelRect(area.X, area.Bottom - t, area.Width, t), + new PixelRect(area.X, area.Y, t, area.Height), + new PixelRect(area.Right - t, area.Y, t, area.Height), + }; + } + + /// + /// Places the bar just outside the recording when the monitor has room, + /// then inside it. Outside means a failed window-exclusion still leaves the controls out of the file. + /// + public static PixelRect PlaceBar(PixelRect area, PixelRect work, int barWidth, int barHeight, int gap) + { + barWidth = Math.Max(1, barWidth); + barHeight = Math.Max(1, barHeight); + gap = Math.Max(0, gap); + int x = Math.Clamp(area.X + (area.Width - barWidth) / 2, work.X, Math.Max(work.X, work.Right - barWidth)); + + PixelRect At(int y) => new(x, y, barWidth, barHeight); + bool Fits(PixelRect rect) => Contains(work, rect) && !Overlaps(rect, area); + + var below = At(area.Bottom + gap); + if (Fits(below)) return below; + var above = At(area.Y - gap - barHeight); + if (Fits(above)) return above; + + int sideY = Math.Clamp(area.Y + (area.Height - barHeight) / 2, work.Y, Math.Max(work.Y, work.Bottom - barHeight)); + var right = new PixelRect(area.Right + gap, sideY, barWidth, barHeight); + if (Contains(work, right) && !Overlaps(right, area)) return right; + var left = new PixelRect(area.X - gap - barWidth, sideY, barWidth, barHeight); + if (Contains(work, left) && !Overlaps(left, area)) return left; + + int insideY = Math.Clamp(area.Bottom - gap - barHeight, work.Y, Math.Max(work.Y, work.Bottom - barHeight)); + return At(insideY); + } + + public static bool Overlaps(PixelRect a, PixelRect b) => + a.Width > 0 && a.Height > 0 && b.Width > 0 && b.Height > 0 && + a.X < b.Right && b.X < a.Right && a.Y < b.Bottom && b.Y < a.Bottom; + + public static bool Contains(PixelRect outer, PixelRect inner) => + inner.X >= outer.X && inner.Y >= outer.Y && inner.Right <= outer.Right && inner.Bottom <= outer.Bottom; + + public static PixelRect Intersect(PixelRect a, PixelRect b) + { + int x = Math.Max(a.X, b.X); + int y = Math.Max(a.Y, b.Y); + int right = Math.Min(a.Right, b.Right); + int bottom = Math.Min(a.Bottom, b.Bottom); + if (right <= x || bottom <= y) return default; + return new PixelRect(x, y, right - x, bottom - y); + } + + static int OverlapArea(PixelRect a, PixelRect b) + { + var hit = Intersect(a, b); + return Math.Max(0, hit.Width) * Math.Max(0, hit.Height); + } +} diff --git a/linux/RecordingChrome.cs b/linux/RecordingChrome.cs new file mode 100644 index 0000000..930189f --- /dev/null +++ b/linux/RecordingChrome.cs @@ -0,0 +1,425 @@ +using System.Runtime.InteropServices; +using Avalonia; +using Avalonia.Controls; +using Avalonia.Input; +using Avalonia.Interactivity; +using Avalonia.Layout; +using Avalonia.Media; +using Avalonia.Threading; + +namespace OpenSnip; + +/// +/// Red outline around the recorded area and the pause / mic / stop / discard bar. +/// Both are real windows, and their ids are handed to the grabber so the pixels +/// underneath them are what gets written to the file. +/// +sealed class RecordingChrome +{ + readonly RecordingSession _session; + readonly Window _bar; + readonly StackPanel _controls; + readonly StackPanel _countdownPanel; + readonly TextBlock _countdownText; + readonly TextBlock _dot; + readonly TextBlock _time; + readonly Button _pause; + readonly Button _mic; + readonly Border _timeHost; + readonly DispatcherTimer _tick; + DispatcherTimer _count; + readonly List _outlines = new(); + IntPtr _display; + long[] _ids = Array.Empty(); + int _countdown; + Action _after; + bool _countdownArmed; + bool _drag; + PixelPoint _dragScreen; + PixelPoint _dragOrigin; + bool _closed; + + public RecordingChrome(RecordingSession session) + { + _session = session; + _dot = new TextBlock + { + Text = "●", + FontSize = 11, + Foreground = AppTheme.Record, + VerticalAlignment = VerticalAlignment.Center, + }; + _time = new TextBlock + { + Text = "00:00", + FontSize = 14, + FontWeight = FontWeight.SemiBold, + MinWidth = 52, + VerticalAlignment = VerticalAlignment.Center, + }; + var timeRow = new StackPanel + { + Orientation = Orientation.Horizontal, + Spacing = 6, + VerticalAlignment = VerticalAlignment.Center, + }; + timeRow.Children.Add(_dot); + timeRow.Children.Add(_time); + _timeHost = new Border + { + Padding = new Thickness(12, 6, 10, 6), + Cursor = new Cursor(StandardCursorType.SizeAll), + Child = timeRow, + }; + _timeHost.PointerPressed += OnDragPressed; + _timeHost.PointerMoved += OnDragMoved; + _timeHost.PointerReleased += OnDragReleased; + + _pause = BarButton("Pause", (_, _) => _session.TogglePause()); + _mic = _session.HasMic ? BarButton("Mic on", (_, _) => _session.ToggleMic()) : null; + if (_mic != null) _mic.Foreground = AppTheme.Good; + var stop = BarButton("Stop", (_, _) => _session.Stop()); + stop.Foreground = AppTheme.Record; + var discard = BarButton("✕", async (_, _) => await ConfirmDiscard()); + discard.Foreground = AppTheme.Muted; + + _controls = new StackPanel { Orientation = Orientation.Horizontal, VerticalAlignment = VerticalAlignment.Center }; + _controls.Children.Add(_timeHost); + _controls.Children.Add(_pause); + if (_mic != null) _controls.Children.Add(_mic); + _controls.Children.Add(stop); + _controls.Children.Add(discard); + + _countdownText = new TextBlock + { + Text = "Recording starts in 3…", + FontSize = 14, + FontWeight = FontWeight.SemiBold, + VerticalAlignment = VerticalAlignment.Center, + Margin = new Thickness(14, 0, 8, 0), + }; + var cancel = BarButton("Cancel", (_, _) => _session.Discard()); + _countdownPanel = new StackPanel { Orientation = Orientation.Horizontal, IsVisible = false }; + _countdownPanel.Children.Add(_countdownText); + _countdownPanel.Children.Add(cancel); + + var stack = new StackPanel(); + stack.Children.Add(_controls); + stack.Children.Add(_countdownPanel); + + _bar = new Window + { + Title = "OpenSnip", + SystemDecorations = SystemDecorations.None, + CanResize = false, + ShowInTaskbar = false, + ShowActivated = false, + Topmost = true, + SizeToContent = SizeToContent.WidthAndHeight, + WindowStartupLocation = WindowStartupLocation.Manual, + Background = AppTheme.Back, + Content = new Border + { + Background = AppTheme.Back, + BorderBrush = AppTheme.Border, + BorderThickness = new Thickness(1), + Child = stack, + }, + }; + _bar.Opened += (_, _) => Dispatcher.UIThread.Post(() => + { + if (_closed) return; + Place(); + RefreshIds(); + }, DispatcherPriority.Loaded); + _bar.Closed += (_, _) => _closed = true; + + _tick = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(250) }; + _tick.Tick += (_, _) => + { + if (_closed) return; + _session.Poll(); + if (_closed) return; + UpdateTime(); + }; + } + + public void StartCountdown(int seconds, Action then) + { + _countdown = Math.Max(1, seconds); + _after = then; + _countdownArmed = true; + _countdownText.Text = $"Recording starts in {_countdown}…"; + _controls.IsVisible = false; + _countdownPanel.IsVisible = true; + if (_bar.IsVisible) StartCountTimer(); + } + + public void Show() + { + CreateOutlines(); + var work = X11Monitors.WorkArea(_session.Area); + _bar.Position = RecordGeometry.PlaceBar(_session.Area, work, 360, 48, 10).Position; + _bar.Show(); + if (_countdownArmed) StartCountTimer(); + _tick.Start(); + RefreshIds(); + } + + public void Close() + { + if (_closed) return; + _closed = true; + _tick.Stop(); + _count?.Stop(); + DestroyOutlines(); + try + { + if (_bar.IsVisible) _bar.Close(); + } + catch { } + } + + public void Refresh() + { + if (_closed) return; + if (!Dispatcher.UIThread.CheckAccess()) + { + Dispatcher.UIThread.Post(Refresh); + return; + } + _pause.Content = _session.Paused ? "Resume" : "Pause"; + if (_mic != null) + { + _mic.Content = _session.MicOn ? "Mic on" : "Mic off"; + _mic.Foreground = _session.MicOn ? AppTheme.Good : AppTheme.Muted; + } + UpdateTime(); + } + + /// Ids captured on the UI thread. The grabber reads this from its own thread. + public long[] WindowIds() => Volatile.Read(ref _ids); + + void StartCountTimer() + { + if (_count != null) return; + _count = new DispatcherTimer { Interval = TimeSpan.FromSeconds(1) }; + _count.Tick += (_, _) => + { + if (_closed) return; + _countdown--; + if (_countdown > 0) + { + _countdownText.Text = $"Recording starts in {_countdown}…"; + return; + } + _count.Stop(); + _countdownArmed = false; + _countdownPanel.IsVisible = false; + _controls.IsVisible = true; + Place(); + RefreshIds(); + var go = _after; + _after = null; + go?.Invoke(); + }; + _count.Start(); + } + + void UpdateTime() + { + var elapsed = _session.Elapsed; + _time.Text = elapsed.TotalHours >= 1 ? elapsed.ToString(@"h\:mm\:ss") : elapsed.ToString(@"mm\:ss"); + bool on = _session.Paused || DateTime.Now.Millisecond < 600; + _dot.Foreground = on ? (_session.Paused ? AppTheme.Muted : AppTheme.Record) : Brushes.Transparent; + } + + async Task ConfirmDiscard() + { + if (_closed) return; + bool wasPaused = _session.Paused; + if (!wasPaused) _session.TogglePause(); + if (_closed) return; + bool yes = false; + try + { + yes = await MessageDialog.ConfirmAsync(_bar, "Throw away this recording?", "Throw away"); + } + catch (Exception ex) + { + Log.Error(ex); + } + if (_closed) return; + if (yes) _session.Discard(); + else if (!wasPaused) _session.TogglePause(); + } + + void Place() + { + if (_closed) return; + double scale = _bar.RenderScaling <= 0 ? 1 : _bar.RenderScaling; + int width = Math.Max(1, (int)Math.Ceiling(_bar.Bounds.Width * scale)); + int height = Math.Max(1, (int)Math.Ceiling(_bar.Bounds.Height * scale)); + if (width < 8 || height < 8) return; + var spot = RecordGeometry.PlaceBar(_session.Area, X11Monitors.WorkArea(_session.Area), width, height, 10); + _bar.Position = spot.Position; + } + + void RefreshIds() + { + var ids = new List(_outlines.Count + 1); + foreach (var outline in _outlines) + if (outline != IntPtr.Zero) ids.Add(outline.ToInt64()); + long bar = XidOf(_bar); + if (bar != 0) ids.Add(bar); + Volatile.Write(ref _ids, ids.ToArray()); + } + + static long XidOf(Window window) + { + try + { + var handle = window.TryGetPlatformHandle(); + if (handle == null || handle.Handle == IntPtr.Zero) return 0; + return handle.Handle.ToInt64(); + } + catch { return 0; } + } + + void OnDragPressed(object sender, PointerPressedEventArgs e) + { + if (!e.GetCurrentPoint(_timeHost).Properties.IsLeftButtonPressed) return; + _drag = true; + _dragScreen = _bar.PointToScreen(e.GetPosition(_bar)); + _dragOrigin = _bar.Position; + e.Pointer.Capture(_timeHost); + e.Handled = true; + } + + void OnDragMoved(object sender, PointerEventArgs e) + { + if (!_drag) return; + var now = _bar.PointToScreen(e.GetPosition(_bar)); + _bar.Position = new PixelPoint( + _dragOrigin.X + (now.X - _dragScreen.X), + _dragOrigin.Y + (now.Y - _dragScreen.Y)); + RefreshIds(); + } + + void OnDragReleased(object sender, PointerReleasedEventArgs e) + { + if (!_drag) return; + _drag = false; + e.Pointer.Capture(null); + RefreshIds(); + e.Handled = true; + } + + static Button BarButton(string text, EventHandler click) + { + var button = new Button + { + Content = text, + Padding = new Thickness(10, 6), + Margin = new Thickness(0, 4, 4, 4), + MinWidth = 0, + }; + button.Click += click; + return button; + } + + void CreateOutlines() + { + try + { + _display = XOpenDisplay(null); + if (_display == IntPtr.Zero) return; + XSetErrorHandler(IgnoreError); + int screen = XDefaultScreen(_display); + IntPtr root = XRootWindow(_display, screen); + IntPtr pixel = AllocColor(_display, screen, 0xF0F0, 0x4444, 0x3838); + foreach (var rect in RecordGeometry.Outline(_session.Area, 3)) + { + var window = XCreateSimpleWindow(_display, root, rect.X, rect.Y, (uint)rect.Width, (uint)rect.Height, 0, pixel, pixel); + if (window == IntPtr.Zero) continue; + SetOverrideRedirect(_display, window); + try { XShapeCombineRectangles(_display, window, ShapeInput, 0, 0, IntPtr.Zero, 0, ShapeSet, Unsorted); } + catch (Exception ex) { Log.Error(ex); } + XMapWindow(_display, window); + _outlines.Add(window); + } + XFlush(_display); + } + catch (Exception ex) + { + Log.Error(ex); + } + } + + void DestroyOutlines() + { + if (_display == IntPtr.Zero) return; + try + { + foreach (var window in _outlines) + try { XDestroyWindow(_display, window); } catch { } + XFlush(_display); + XCloseDisplay(_display); + } + catch { } + _outlines.Clear(); + _display = IntPtr.Zero; + } + + static IntPtr AllocColor(IntPtr display, int screen, ushort red, ushort green, ushort blue) + { + var color = new XColor { Red = red, Green = green, Blue = blue, Flags = 7 }; + IntPtr colormap = XDefaultColormap(display, screen); + if (colormap != IntPtr.Zero && XAllocColor(display, colormap, ref color) != 0) + return (IntPtr)(long)color.Pixel; + return (IntPtr)0x00F04438; + } + + static void SetOverrideRedirect(IntPtr display, IntPtr window) + { + var bytes = new byte[112]; + bytes[88] = 1; + var pin = GCHandle.Alloc(bytes, GCHandleType.Pinned); + try { XChangeWindowAttributes(display, window, 512, pin.AddrOfPinnedObject()); } + finally { pin.Free(); } + } + + const int ShapeInput = 2; + const int ShapeSet = 0; + const int Unsorted = 0; + + [StructLayout(LayoutKind.Sequential)] + struct XColor + { + public nuint Pixel; + public ushort Red; + public ushort Green; + public ushort Blue; + public byte Flags; + public byte Pad; + } + + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + delegate int XErrorHandler(IntPtr display, IntPtr error); + + static readonly XErrorHandler IgnoreError = (_, _) => 0; + + [DllImport("libX11")] static extern IntPtr XOpenDisplay(string name); + [DllImport("libX11")] static extern int XCloseDisplay(IntPtr display); + [DllImport("libX11")] static extern IntPtr XSetErrorHandler(XErrorHandler handler); + [DllImport("libX11")] static extern int XDefaultScreen(IntPtr display); + [DllImport("libX11")] static extern IntPtr XRootWindow(IntPtr display, int screen); + [DllImport("libX11")] static extern IntPtr XDefaultColormap(IntPtr display, int screen); + [DllImport("libX11")] static extern int XAllocColor(IntPtr display, IntPtr colormap, ref XColor color); + [DllImport("libX11")] static extern IntPtr XCreateSimpleWindow(IntPtr display, IntPtr parent, int x, int y, uint width, uint height, uint borderWidth, IntPtr border, IntPtr background); + [DllImport("libX11")] static extern int XChangeWindowAttributes(IntPtr display, IntPtr window, ulong valueMask, IntPtr attributes); + [DllImport("libX11")] static extern int XMapWindow(IntPtr display, IntPtr window); + [DllImport("libX11")] static extern int XDestroyWindow(IntPtr display, IntPtr window); + [DllImport("libX11")] static extern int XFlush(IntPtr display); + [DllImport("libXext.so.6")] static extern void XShapeCombineRectangles(IntPtr display, IntPtr window, int kind, int xOff, int yOff, IntPtr rectangles, int count, int operation, int ordering); +} diff --git a/linux/RecordingSession.cs b/linux/RecordingSession.cs new file mode 100644 index 0000000..fb130f5 --- /dev/null +++ b/linux/RecordingSession.cs @@ -0,0 +1,282 @@ +using Avalonia; + +namespace OpenSnip; + +/// One recording: outline, control bar, and the encoder. The outline and bar are removed from the frames. +sealed class RecordingSession +{ + public event Action Saved; + public event Action Failed; + public event Action Ended; + + readonly Settings _settings; + readonly string _system; + readonly string _mic; + readonly string _output; + readonly string _temp; + readonly List _segments = new(); + readonly System.Diagnostics.Stopwatch _clock = new(); + FramePump _pump; + RecordingChrome _chrome; + string _current; + bool _paused; + bool _stopping; + bool _discard; + bool _ended; + bool _micOn; + + public PixelRect Area { get; } + public bool Paused => _paused; + public bool HasMic => _mic != null; + public bool MicOn => _micOn; + public TimeSpan Elapsed => _clock.Elapsed; + + public RecordingSession(PixelRect area, Settings settings, string systemSource, string micSource) + { + Area = area; + _settings = settings; + _system = systemSource; + _mic = micSource; + _micOn = micSource != null; + _output = FfmpegPlan.NewRecordingPath(settings.FolderFor(settings.VideoFolder)); + _temp = Path.Combine(Path.GetTempPath(), "opensnip-rec-" + Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(_temp); + } + + public void Begin() + { + _chrome = new RecordingChrome(this); + if (_settings.RecordCountdown) _chrome.StartCountdown(3, StartEncoder); + _chrome.Show(); + if (!_settings.RecordCountdown) StartEncoder(); + } + + public void Poll() + { + if (_stopping) return; + if (_pump != null && _pump.Failed) + Fail(_pump.Error); + } + + public void TogglePause() + { + if (_pump == null || _stopping) return; + try + { + if (_paused) Resume(); + else Pause(); + } + catch (Exception ex) + { + Log.Error(ex); + Fail(ex.Message); + } + _chrome?.Refresh(); + } + + public void ToggleMic() + { + if (_mic == null || _stopping) return; + _micOn = !_micOn; + try + { + if (_pump != null && !_paused) + { + FinishSegment(); + if (!_stopping) StartEncoder(); + } + } + catch (Exception ex) + { + Log.Error(ex); + Fail(ex.Message); + } + _chrome?.Refresh(); + } + + public void Stop() => Finish(false); + public void Discard() => Finish(true); + + void Pause() + { + _paused = true; + _clock.Stop(); + FinishSegment(); + } + + void Resume() + { + _paused = false; + StartEncoder(); + } + + void StartEncoder() + { + if (_stopping) return; + try + { + _current = Path.Combine(_temp, _segments.Count + ".mp4"); + var spec = new EncodeSpec + { + Width = Area.Width, + Height = Area.Height, + Framerate = FfmpegPlan.NormalizeFramerate(_settings.RecordFramerate), + HighQuality = _settings.RecordHighQuality, + SystemSource = _system, + MicSource = _mic, + MicOn = _micOn, + Cursor = _settings.RecordCursor, + Output = _current, + }; + var pump = new FramePump(Area, spec, () => _chrome?.WindowIds() ?? Array.Empty()); + pump.Start(); + _pump = pump; + if (!_clock.IsRunning) _clock.Start(); + _chrome?.Refresh(); + } + catch (Exception ex) + { + Log.Error(ex); + Fail(ex.Message); + } + } + + void Finish(bool discard) + { + if (_stopping) return; + _stopping = true; + _discard = discard; + _clock.Stop(); + CapturedFrame preview = null; + try + { + if (!discard) preview = _pump?.CopyLatest(); + FinishSegment(); + } + catch (Exception ex) + { + Log.Error(ex); + try { _chrome?.Close(); } catch { } + _chrome = null; + if (!discard) Fail(ex.Message); + else End(); + return; + } + + try { _chrome?.Close(); } catch { } + _chrome = null; + + if (discard || _segments.Count == 0) + { + DeleteTemp(); + if (!discard && _segments.Count == 0) + { + // Stopped during the countdown, or ffmpeg never produced a file. + if (preview == null) { End(); return; } + } + End(); + return; + } + + try + { + string final = Assemble(); + if (final == null) + { + Failed?.Invoke("The recording was empty."); + End(); + return; + } + Saved?.Invoke(final, preview); + } + catch (Exception ex) + { + Log.Error(ex); + Failed?.Invoke(ex.Message); + } + End(); + } + + void Fail(string message) + { + if (_ended) return; + if (!_stopping) + { + _discard = true; + _stopping = true; + _clock.Stop(); + try { FinishSegment(); } catch (Exception ex) { Log.Error(ex); } + try { _chrome?.Close(); } catch { } + _chrome = null; + DeleteTemp(); + } + if (!string.IsNullOrWhiteSpace(message)) Failed?.Invoke(message); + End(); + } + + void FinishSegment() + { + var pump = _pump; + _pump = null; + if (pump == null) return; + try { pump.Stop(); } + catch (Exception ex) { Log.Error(ex); } + try + { + if (!string.IsNullOrEmpty(_current) && File.Exists(_current) && new FileInfo(_current).Length > 32) + _segments.Add(_current); + } + catch (Exception ex) { Log.Error(ex); } + try { pump.Dispose(); } catch { } + if (pump.Failed) + throw new InvalidOperationException(string.IsNullOrWhiteSpace(pump.Error) ? "ffmpeg failed." : pump.Error); + } + + string Assemble() + { + if (_segments.Count == 0) return null; + if (_segments.Count == 1) + { + File.Move(_segments[0], _output, true); + return _output; + } + string list = Path.Combine(_temp, "list.txt"); + File.WriteAllText(list, FfmpegPlan.ConcatList(_segments)); + var psi = new System.Diagnostics.ProcessStartInfo("ffmpeg") + { + UseShellExecute = false, + RedirectStandardError = true, + RedirectStandardOutput = true, + CreateNoWindow = true, + }; + foreach (var arg in FfmpegPlan.ConcatArguments(list, _output)) psi.ArgumentList.Add(arg); + using var process = System.Diagnostics.Process.Start(psi); + if (process == null) throw new InvalidOperationException("ffmpeg did not start."); + var stderr = process.StandardError.ReadToEndAsync(); + if (!process.WaitForExit(20000)) + { + try { process.Kill(entireProcessTree: true); } catch { } + throw new InvalidOperationException("Saving the recording timed out."); + } + if (process.ExitCode != 0 || !File.Exists(_output)) + { + string detail = stderr.GetAwaiter().GetResult().Trim(); + if (detail.Length > 300) detail = detail[^300..]; + throw new InvalidOperationException(string.IsNullOrWhiteSpace(detail) ? "Could not finish the recording." : detail); + } + return _output; + } + + void DeleteTemp() + { + try { if (Directory.Exists(_temp)) Directory.Delete(_temp, true); } catch { } + } + + void End() + { + if (_ended) return; + _ended = true; + DeleteTemp(); + Ended?.Invoke(); + } +} diff --git a/linux/SettingsDefaults.cs b/linux/SettingsDefaults.cs index a16acd7..5cbe315 100644 --- a/linux/SettingsDefaults.cs +++ b/linux/SettingsDefaults.cs @@ -18,9 +18,27 @@ public static string PicturesFolder public static string DefaultSaveFolder => Path.Combine(PicturesFolder, "OpenSnip"); + public static string VideosFolder + { + get + { + string videos = Environment.GetFolderPath(Environment.SpecialFolder.MyVideos); + if (!string.IsNullOrWhiteSpace(videos)) return videos; + + string home = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile); + if (string.IsNullOrWhiteSpace(home)) home = Environment.GetEnvironmentVariable("HOME"); + if (string.IsNullOrWhiteSpace(home)) home = "/tmp"; + return Path.Combine(home, "Videos"); + } + } + + public static string DefaultVideoFolder => Path.Combine(VideosFolder, "OpenSnip"); + public static void ApplyLinux(Settings settings) { if (string.IsNullOrWhiteSpace(settings.SaveFolder) || !Path.IsPathRooted(settings.SaveFolder)) settings.SaveFolder = DefaultSaveFolder; + if (string.IsNullOrWhiteSpace(settings.VideoFolder) || !Path.IsPathRooted(settings.VideoFolder)) + settings.VideoFolder = DefaultVideoFolder; } } diff --git a/linux/SettingsWindow.cs b/linux/SettingsWindow.cs index 5b10667..9a1c451 100644 --- a/linux/SettingsWindow.cs +++ b/linux/SettingsWindow.cs @@ -34,6 +34,17 @@ sealed class SettingsWindow : Window ComboBox _format; CheckBox _monthly; CheckBox _startOnLogin; + TextBox _videoFolderBox; + CheckBox _systemAudio; + CheckBox _recordMic; + ComboBox _micBox; + ComboBox _fps; + ComboBox _quality; + CheckBox _recordCursor; + CheckBox _recordCountdown; + CheckBox _copyVideo; + bool _filling; + List _mics = new() { new MicItem("", "Default") }; CheckBox _printScreen; TextBlock _shortcutStatus; readonly List _shortcuts = new(); @@ -92,6 +103,7 @@ public SettingsWindow(App app, string startPage = "Capture") AddPage("Capture", BuildCapture()); AddPage("Saving", BuildSaving()); + AddPage("Recording", BuildRecording()); AddPage("Shortcuts", BuildShortcuts()); AddPage("General", BuildGeneral()); ShowPage(startPage); @@ -277,6 +289,14 @@ Control BuildSaving() }; panel.Children.Add(Row("Format", _format)); + panel.Children.Add(Heading("Recordings")); + _videoFolderBox = new TextBox { Text = _s.VideoFolder, IsReadOnly = true, MinWidth = 200 }; + var videoBrowse = new Button { Content = "Browse…" }; + videoBrowse.Click += async (_, _) => await BrowseFolderAsync(path => _s.VideoFolder = path, _videoFolderBox); + var videoOpen = new Button { Content = "Open" }; + videoOpen.Click += (_, _) => OpenChosenFolder(_s.VideoFolder); + panel.Children.Add(Row("Folder", FolderControls(_videoFolderBox, videoBrowse, videoOpen))); + panel.Children.Add(Heading("Organizing")); _monthly = Check("Sort into monthly subfolders", _s.MonthlyFolders, v => _s.MonthlyFolders = v); panel.Children.Add(_monthly); @@ -285,12 +305,111 @@ Control BuildSaving() { _autoSave.IsChecked = _s.AutoSave; _folderBox.Text = _s.SaveFolder; + _videoFolderBox.Text = _s.VideoFolder; _format.SelectedIndex = string.Equals(_s.SaveFormat, "jpg", StringComparison.OrdinalIgnoreCase) ? 1 : 0; _monthly.IsChecked = _s.MonthlyFolders; }); return panel; } + Control BuildRecording() + { + var panel = Page("Recording"); + panel.Children.Add(Heading("Sound")); + _systemAudio = Check("Record system sound", _s.RecordSystemAudio, v => _s.RecordSystemAudio = v); + panel.Children.Add(_systemAudio); + _recordMic = Check("Record my microphone", _s.RecordMicrophone, v => + { + _s.RecordMicrophone = v; + if (_micBox != null) _micBox.IsEnabled = v; + }); + panel.Children.Add(_recordMic); + + _micBox = new ComboBox { MinWidth = 220, IsEnabled = _s.RecordMicrophone }; + FillMics(); + _micBox.SelectionChanged += (_, _) => + { + if (_filling || _micBox.SelectedItem is not MicItem item) return; + _s.MicrophoneDevice = item.Id; + Save(); + }; + panel.Children.Add(Row("Microphone", _micBox)); + + panel.Children.Add(Heading("Video")); + _fps = IntCombo(_s.RecordFramerate, new[] { 30, 60 }, n => $"{n} fps", v => _s.RecordFramerate = v); + panel.Children.Add(Row("Frame rate", _fps)); + + _quality = new ComboBox + { + ItemsSource = new[] { "High", "Standard" }, + SelectedIndex = _s.RecordHighQuality ? 0 : 1, + MinWidth = 160, + }; + _quality.SelectionChanged += (_, _) => + { + if (_filling || _quality.SelectedIndex < 0) return; + _s.RecordHighQuality = _quality.SelectedIndex == 0; + Save(); + }; + panel.Children.Add(Row("Quality", _quality)); + + _recordCursor = Check("Show the mouse cursor", _s.RecordCursor, v => _s.RecordCursor = v); + panel.Children.Add(_recordCursor); + _recordCountdown = Check("Count down before recording", _s.RecordCountdown, v => _s.RecordCountdown = v); + panel.Children.Add(_recordCountdown); + _copyVideo = Check("Copy the video to the clipboard", _s.CopyRecordingToClipboard, v => _s.CopyRecordingToClipboard = v); + panel.Children.Add(_copyVideo); + + _refresh.Add(() => + { + _filling = true; + _systemAudio.IsChecked = _s.RecordSystemAudio; + _recordMic.IsChecked = _s.RecordMicrophone; + _micBox.IsEnabled = _s.RecordMicrophone; + FillMics(); + SetComboValue(_fps, _s.RecordFramerate); + _quality.SelectedIndex = _s.RecordHighQuality ? 0 : 1; + _recordCursor.IsChecked = _s.RecordCursor; + _recordCountdown.IsChecked = _s.RecordCountdown; + _copyVideo.IsChecked = _s.CopyRecordingToClipboard; + _filling = false; + }); + + _ = LoadMicrophonesAsync(); + return panel; + } + + async Task LoadMicrophonesAsync() + { + AudioDevices audio; + try { audio = await Task.Run(AudioDevices.Discover); } + catch (Exception ex) + { + Log.Error(ex); + return; + } + if (!IsVisible && _micBox == null) return; + var items = new List { new("", "Default") }; + foreach (var mic in audio.Microphones) + items.Add(new MicItem(mic.Name, mic.Description)); + _mics = items; + if (!_mics.Any(item => item.Id == _s.MicrophoneDevice)) _s.MicrophoneDevice = ""; + await Dispatcher.UIThread.InvokeAsync(() => + { + if (_micBox == null) return; + _filling = true; + FillMics(); + _filling = false; + }); + } + + void FillMics() + { + _micBox.ItemsSource = _mics.ToList(); + int index = _mics.FindIndex(item => item.Id == _s.MicrophoneDevice); + _micBox.SelectedIndex = index >= 0 ? index : 0; + } + Control BuildShortcuts() { var panel = Page("Shortcuts"); @@ -322,6 +441,7 @@ Control BuildShortcuts() panel.Children.Add(CommandRow("Delayed snip", PlatformInfo.Command("--snip-delay"))); panel.Children.Add(CommandRow("Repeat last region", PlatformInfo.Command("--repeat"))); panel.Children.Add(CommandRow("Pin clipboard image", PlatformInfo.Command("--pin"))); + panel.Children.Add(CommandRow("Record video", PlatformInfo.Command("--record"))); } return panel; @@ -413,6 +533,15 @@ void ResetToDefaults() _s.PreviewSeconds = 6; _s.ShowMagnifier = true; _s.DelaySeconds = 3; + _s.VideoFolder = SettingsDefaults.DefaultVideoFolder; + _s.RecordSystemAudio = true; + _s.RecordMicrophone = false; + _s.MicrophoneDevice = ""; + _s.RecordFramerate = 30; + _s.RecordHighQuality = true; + _s.RecordCursor = true; + _s.RecordCountdown = true; + _s.CopyRecordingToClipboard = true; _s.SnipHotkey = "Win+Shift+S"; _s.DelayHotkey = ""; _s.RepeatHotkey = ""; @@ -421,7 +550,9 @@ void ResetToDefaults() foreach (var refresh in _refresh) refresh(); } - async Task BrowseFolderAsync() + async Task BrowseFolderAsync() => await BrowseFolderAsync(path => _s.SaveFolder = path, _folderBox); + + async Task BrowseFolderAsync(Action set, TextBox box) { try { @@ -433,8 +564,8 @@ async Task BrowseFolderAsync() if (result.Count == 0) return; var local = result[0].TryGetLocalPath(); if (string.IsNullOrEmpty(local)) return; - _s.SaveFolder = local; - _folderBox.Text = local; + set(local); + box.Text = local; Save(); } catch (Exception ex) @@ -443,11 +574,13 @@ async Task BrowseFolderAsync() } } - void OpenFolder() + void OpenFolder() => OpenChosenFolder(_s.SaveFolder); + + void OpenChosenFolder(string root) { try { - string folder = _s.FolderFor(_s.SaveFolder); + string folder = _s.FolderFor(root); Directory.CreateDirectory(folder); PlatformInfo.Open(folder); } @@ -457,6 +590,35 @@ void OpenFolder() } } + static Grid FolderControls(TextBox box, Button browse, Button open) + { + var grid = new Grid + { + ColumnDefinitions = new ColumnDefinitions("*,Auto,Auto"), + ColumnSpacing = 8, + }; + grid.Children.Add(box); + Grid.SetColumn(box, 0); + grid.Children.Add(browse); + Grid.SetColumn(browse, 1); + grid.Children.Add(open); + Grid.SetColumn(open, 2); + return grid; + } + + sealed class MicItem + { + public MicItem(string id, string label) + { + Id = id ?? ""; + Label = string.IsNullOrWhiteSpace(label) ? "Default" : label; + } + + public string Id { get; } + public string Label { get; } + public override string ToString() => Label; + } + void Save() { _s.Save(); diff --git a/linux/SingleInstance.cs b/linux/SingleInstance.cs index abd1b4a..a32b035 100644 --- a/linux/SingleInstance.cs +++ b/linux/SingleInstance.cs @@ -31,6 +31,7 @@ public static string Format(LaunchAction action, string argument) LaunchAction.SnipDelay => "snip-delay", LaunchAction.Repeat => "repeat", LaunchAction.Settings => "settings", + LaunchAction.Record => "record", _ => "snip", }; } @@ -40,6 +41,7 @@ public static string Format(LaunchAction action, string argument) "snip-delay" => LaunchAction.SnipDelay, "repeat" => LaunchAction.Repeat, "settings" => LaunchAction.Settings, + "record" => LaunchAction.Record, "pin" => LaunchAction.Pin, _ => LaunchAction.Snip, }; diff --git a/linux/Theme.cs b/linux/Theme.cs index e39aa0c..55b3c23 100644 --- a/linux/Theme.cs +++ b/linux/Theme.cs @@ -16,6 +16,8 @@ static class AppTheme public static readonly Color AccentHoverColor = Color.Parse("#8D73FF"); public static readonly Color BorderColor = Color.Parse("#3A3A46"); public static readonly Color NavSelectedColor = Color.Parse("#483A8C"); + public static readonly Color RecordColor = Color.Parse("#F04438"); + public static readonly Color GoodColor = Color.Parse("#78DC8C"); public static readonly IBrush Back = new SolidColorBrush(BackColor); public static readonly IBrush Panel = new SolidColorBrush(PanelColor); @@ -24,6 +26,8 @@ static class AppTheme public static readonly IBrush Accent = new SolidColorBrush(AccentColor); public static readonly IBrush Border = new SolidColorBrush(BorderColor); public static readonly IBrush NavSelected = new SolidColorBrush(NavSelectedColor); + public static readonly IBrush Record = new SolidColorBrush(RecordColor); + public static readonly IBrush Good = new SolidColorBrush(GoodColor); public static void Apply(Application app) { diff --git a/linux/ThumbnailWindow.cs b/linux/ThumbnailWindow.cs index 5ccdbae..1b83ba4 100644 --- a/linux/ThumbnailWindow.cs +++ b/linux/ThumbnailWindow.cs @@ -6,6 +6,7 @@ using Avalonia.Media.Imaging; using Avalonia.Platform.Storage; using Avalonia.Threading; +using Shapes = Avalonia.Controls.Shapes; namespace OpenSnip; @@ -18,7 +19,7 @@ sealed class ThumbnailWindow : Window bool _pressed; bool _dragged; - public ThumbnailWindow(CapturedFrame frame, string savedPath, int seconds) + public ThumbnailWindow(CapturedFrame frame, string savedPath, int seconds, bool play = false) { _frame = frame; _path = savedPath; @@ -53,13 +54,16 @@ public ThumbnailWindow(CapturedFrame frame, string savedPath, int seconds) HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center, }; + var picture = new Grid(); + picture.Children.Add(image); + if (play) picture.Children.Add(PlayBadge()); Content = new Border { Background = AppTheme.Panel, BorderBrush = AppTheme.Border, BorderThickness = new Thickness(1), Padding = new Thickness(3), - Child = image, + Child = picture, }; _timer = new DispatcherTimer { Interval = TimeSpan.FromSeconds(Math.Max(1, seconds)) }; @@ -80,6 +84,35 @@ public ThumbnailWindow(CapturedFrame frame, string savedPath, int seconds) PointerReleased += OnReleased; } + static Control PlayBadge() + { + var points = new Points(); + points.Add(new Point(0, 0)); + points.Add(new Point(0, 18)); + points.Add(new Point(16, 9)); + return new Border + { + Width = 46, + Height = 46, + CornerRadius = new CornerRadius(23), + Background = new SolidColorBrush(Color.FromArgb(176, 20, 20, 24)), + HorizontalAlignment = HorizontalAlignment.Center, + VerticalAlignment = VerticalAlignment.Center, + IsHitTestVisible = false, + Child = new Shapes.Polygon + { + Points = points, + Fill = Brushes.White, + Width = 16, + Height = 18, + Stretch = Stretch.Fill, + HorizontalAlignment = HorizontalAlignment.Center, + VerticalAlignment = VerticalAlignment.Center, + Margin = new Thickness(3, 0, 0, 0), + }, + }; + } + void PlaceBottomRight() { var screen = Screens.Primary diff --git a/linux/X11FrameSource.cs b/linux/X11FrameSource.cs new file mode 100644 index 0000000..233d7f4 --- /dev/null +++ b/linux/X11FrameSource.cs @@ -0,0 +1,500 @@ +using System.Buffers.Binary; +using System.Numerics; +using System.Runtime.InteropServices; + +namespace OpenSnip; + +/// +/// One BGRA frame of an X11 rectangle. Windows in exclude are painted out: +/// the root image includes them, so those rectangles are rebuilt from the wallpaper +/// and the windows underneath. That is what keeps the outline and the control bar +/// out of the file while they stay on screen. +/// +sealed class X11FrameSource : IDisposable +{ + const string X11 = "libX11"; + const int ZPixmap = 2; + const ulong AllPlanes = ~0UL; + const int IsViewable = 2; + const int InputOutput = 1; + + readonly int _x, _y, _width, _height; + IntPtr _display; + IntPtr _root; + IntPtr _shmImage; + IntPtr _shmAddress; + int _shmId = -1; + bool _shmReady; + IntPtr _wallpaper; + bool _wallpaperChecked; + byte[] _row = Array.Empty(); + bool _disposed; + static int _sawError; + static readonly XErrorHandler ErrorDelegate = OnError; + + public int Width => _width; + public int Height => _height; + + public X11FrameSource(int x, int y, int width, int height) + { + if (width <= 0 || height <= 0) throw new ArgumentException("Invalid frame size"); + _x = x; + _y = y; + _width = width; + _height = height; + _display = XOpenDisplay(null); + if (_display == IntPtr.Zero) throw new InvalidOperationException("Cannot open the X11 display."); + XSetErrorHandler(ErrorDelegate); + _root = XDefaultRootWindow(_display); + TryAttachShm(); + } + + public bool Grab(byte[] destination, IReadOnlyList exclude, bool cursor) + { + if (_disposed || destination == null || destination.Length < _width * _height * 4) return false; + if (!ReadRoot(destination)) return false; + if (exclude != null && exclude.Count > 0) RemoveChrome(destination, exclude); + if (cursor) DrawCursor(destination); + return true; + } + + public void Dispose() + { + if (_disposed) return; + _disposed = true; + DetachShm(); + if (_display != IntPtr.Zero) + { + try { XCloseDisplay(_display); } catch { } + _display = IntPtr.Zero; + } + } + + bool ReadRoot(byte[] destination) + { + if (_shmReady && XShmGetImage(_display, _root, _shmImage, _x, _y, AllPlanes)) + { + var header = Marshal.PtrToStructure(_shmImage); + Convert(header.data == IntPtr.Zero ? _shmAddress : header.data, header, _width, _height, destination, 0, 0); + return true; + } + + IntPtr image = XGetImage(_display, _root, _x, _y, (uint)_width, (uint)_height, AllPlanes, ZPixmap); + if (image == IntPtr.Zero) return false; + try + { + var header = Marshal.PtrToStructure(image); + if (header.data == IntPtr.Zero) return false; + Convert(header.data, header, header.width, header.height, destination, 0, 0); + return true; + } + finally { XDestroyImage(image); } + } + + void RemoveChrome(byte[] destination, IReadOnlyList exclude) + { + var skip = new HashSet(); + var holes = new List(); + foreach (long id in exclude) + { + if (id == 0) continue; + skip.Add(id); + if (!TryBounds((IntPtr)id, out var bounds)) continue; + var hole = RecordGeometry.Intersect(bounds, new Avalonia.PixelRect(_x, _y, _width, _height)); + if (hole.Width > 0 && hole.Height > 0) holes.Add(hole); + } + if (holes.Count == 0) return; + + var windows = new List(); + Collect(_root, windows, skip); + + foreach (var hole in holes) + { + BlitWallpaper(destination, hole); + foreach (var window in windows) + { + var overlap = RecordGeometry.Intersect(window.Interior, hole); + if (overlap.Width <= 0 || overlap.Height <= 0) continue; + BlitWindow(destination, window.Id, window.Interior, overlap); + } + } + } + + void Collect(IntPtr window, List windows, HashSet skip) + { + if (XQueryTree(_display, window, out _, out _, out IntPtr children, out uint count) == 0 || children == IntPtr.Zero) + return; + try + { + for (int i = 0; i < count; i++) + { + var child = Marshal.ReadIntPtr(children, i * IntPtr.Size); + long id = child.ToInt64(); + if (skip.Contains(id)) continue; + if (TrySlice(child, out var slice)) windows.Add(slice); + Collect(child, windows, skip); + } + } + finally { XFree(children); } + } + + bool TrySlice(IntPtr window, out WindowSlice slice) + { + slice = default; + if (!TryAttributes(window, out int klass, out int mapState)) return false; + if (klass != InputOutput || mapState != IsViewable) return false; + if (XGetGeometry(_display, window, out _, out _, out _, out uint width, out uint height, out uint border, out _) == 0) + return false; + if (width == 0 || height == 0) return false; + if (!XTranslateCoordinates(_display, window, _root, 0, 0, out int x, out int y, out _)) return false; + int b = (int)border; + slice = new WindowSlice + { + Id = window, + Interior = new Avalonia.PixelRect(x, y, (int)width, (int)height), + Bounds = new Avalonia.PixelRect(x - b, y - b, (int)width + b * 2, (int)height + b * 2), + }; + return true; + } + + bool TryBounds(IntPtr window, out Avalonia.PixelRect bounds) + { + bounds = default; + if (!TrySlice(window, out var slice)) return false; + bounds = slice.Bounds; + return true; + } + + bool TryAttributes(IntPtr window, out int klass, out int mapState) + { + klass = 0; + mapState = 0; + var attributes = new XWindowAttributes(); + if (XGetWindowAttributes(_display, window, ref attributes) == 0) return false; + klass = attributes.Class; + mapState = attributes.MapState; + return true; + } + + void BlitWallpaper(byte[] destination, Avalonia.PixelRect hole) + { + IntPtr pixmap = Wallpaper(); + if (pixmap == IntPtr.Zero) return; + BlitDrawable(pixmap, hole.X, hole.Y, hole, destination); + } + + void BlitWindow(byte[] destination, IntPtr window, Avalonia.PixelRect interior, Avalonia.PixelRect overlap) + { + _sawError = 0; + IntPtr pixmap = XCompositeNameWindowPixmap(_display, window); + XSync(_display, false); + if (_sawError != 0 || pixmap == IntPtr.Zero) return; + try + { + BlitDrawable(pixmap, overlap.X - interior.X, overlap.Y - interior.Y, overlap, destination); + } + finally + { + try { XFreePixmap(_display, pixmap); } catch { } + } + } + + void BlitDrawable(IntPtr drawable, int srcX, int srcY, Avalonia.PixelRect destRoot, byte[] destination) + { + if (srcX < 0 || srcY < 0 || destRoot.Width <= 0 || destRoot.Height <= 0) return; + _sawError = 0; + IntPtr image = XGetImage(_display, drawable, srcX, srcY, (uint)destRoot.Width, (uint)destRoot.Height, AllPlanes, ZPixmap); + XSync(_display, false); + if (_sawError != 0 || image == IntPtr.Zero) return; + try + { + var header = Marshal.PtrToStructure(image); + if (header.data == IntPtr.Zero) return; + Convert(header.data, header, header.width, header.height, destination, destRoot.X - _x, destRoot.Y - _y); + } + finally { XDestroyImage(image); } + } + + IntPtr Wallpaper() + { + if (_wallpaperChecked) return _wallpaper; + _wallpaperChecked = true; + IntPtr atom = XInternAtom(_display, "_XROOTPMAP_ID", true); + if (atom == IntPtr.Zero) return IntPtr.Zero; + int status = XGetWindowProperty(_display, _root, atom, 0, 1, false, (IntPtr)20, out _, out _, out nuint count, out _, out IntPtr prop); + if (status != 0 || prop == IntPtr.Zero || count < 1) return IntPtr.Zero; + try { _wallpaper = (IntPtr)Marshal.ReadInt64(prop); } + finally { XFree(prop); } + return _wallpaper; + } + + void DrawCursor(byte[] destination) + { + IntPtr image = XFixesGetCursorImage(_display); + if (image == IntPtr.Zero) return; + try + { + var cursor = Marshal.PtrToStructure(image); + if (cursor.Pixels == IntPtr.Zero || cursor.Width == 0 || cursor.Height == 0) return; + int left = cursor.X - cursor.XHot; + int top = cursor.Y - cursor.YHot; + for (int row = 0; row < cursor.Height; row++) + { + int destY = top + row - _y; + if (destY < 0 || destY >= _height) continue; + for (int col = 0; col < cursor.Width; col++) + { + int destX = left + col - _x; + if (destX < 0 || destX >= _width) continue; + IntPtr pixel = IntPtr.Add(cursor.Pixels, (row * cursor.Width + col) * IntPtr.Size); + uint argb = (uint)Marshal.ReadInt32(pixel); + byte a = (byte)(argb >> 24); + if (a == 0) continue; + byte r = (byte)(argb >> 16); + byte g = (byte)(argb >> 8); + byte b = (byte)argb; + int offset = (destY * _width + destX) * 4; + if (a == 255) + { + destination[offset] = b; + destination[offset + 1] = g; + destination[offset + 2] = r; + destination[offset + 3] = 255; + continue; + } + int inv = 255 - a; + destination[offset] = (byte)(b + destination[offset] * inv / 255); + destination[offset + 1] = (byte)(g + destination[offset + 1] * inv / 255); + destination[offset + 2] = (byte)(r + destination[offset + 2] * inv / 255); + destination[offset + 3] = 255; + } + } + } + finally { XFree(image); } + } + + void TryAttachShm() + { + try + { + if (!XShmQueryExtension(_display)) return; + int screen = XDefaultScreen(_display); + var info = new XShmSegmentInfo(); + IntPtr image = XShmCreateImage(_display, XDefaultVisual(_display, screen), (uint)XDefaultDepth(_display, screen), + ZPixmap, IntPtr.Zero, ref info, (uint)_width, (uint)_height); + if (image == IntPtr.Zero) return; + var header = Marshal.PtrToStructure(image); + int bytes = header.bytes_per_line * Math.Max(1, header.height); + if (bytes <= 0) + { + XDestroyImage(image); + return; + } + info.ShmId = shmget(0, (nuint)bytes, 512 | 384); + if (info.ShmId < 0) + { + XDestroyImage(image); + return; + } + info.ShmAddress = shmat(info.ShmId, IntPtr.Zero, 0); + if (info.ShmAddress == new IntPtr(-1)) + { + shmctl(info.ShmId, 0, IntPtr.Zero); + XDestroyImage(image); + return; + } + Marshal.WriteIntPtr(image, 16, info.ShmAddress); + info.ReadOnly = 0; + _sawError = 0; + bool attached = XShmAttach(_display, ref info); + XSync(_display, false); + if (!attached || _sawError != 0) + { + Marshal.WriteIntPtr(image, 16, IntPtr.Zero); + XDestroyImage(image); + shmdt(info.ShmAddress); + shmctl(info.ShmId, 0, IntPtr.Zero); + return; + } + shmctl(info.ShmId, 0, IntPtr.Zero); + _shmImage = image; + _shmAddress = info.ShmAddress; + _shmId = info.ShmId; + _shmReady = true; + } + catch (DllNotFoundException) { } + catch (EntryPointNotFoundException) { } + } + + void DetachShm() + { + if (_shmImage == IntPtr.Zero) return; + try + { + var info = new XShmSegmentInfo { ShmId = _shmId, ShmAddress = _shmAddress }; + XShmDetach(_display, ref info); + Marshal.WriteIntPtr(_shmImage, 16, IntPtr.Zero); + XDestroyImage(_shmImage); + if (_shmAddress != IntPtr.Zero) shmdt(_shmAddress); + } + catch { } + _shmImage = IntPtr.Zero; + _shmReady = false; + } + + struct WindowSlice + { + public IntPtr Id; + public Avalonia.PixelRect Interior; + public Avalonia.PixelRect Bounds; + } + + [StructLayout(LayoutKind.Explicit, Size = 136)] + struct XWindowAttributes + { + [FieldOffset(40)] public int Class; + [FieldOffset(92)] public int MapState; + } + + [StructLayout(LayoutKind.Sequential)] + struct XImageHeader + { + public int width; + public int height; + public int xoffset; + public int format; + public IntPtr data; + public int byte_order; + public int bitmap_unit; + public int bitmap_bit_order; + public int bitmap_pad; + public int depth; + public int bytes_per_line; + public int bits_per_pixel; + public IntPtr red_mask; + public IntPtr green_mask; + public IntPtr blue_mask; + } + + [StructLayout(LayoutKind.Sequential)] + struct XShmSegmentInfo + { + public ulong ShmSeg; + public int ShmId; + public IntPtr ShmAddress; + public int ReadOnly; + } + + [StructLayout(LayoutKind.Sequential)] + struct XFixesCursorImage + { + public short X, Y; + public ushort Width, Height; + public ushort XHot, YHot; + public ulong Serial; + public IntPtr Pixels; + public ulong Atom; + public IntPtr Name; + } + + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + delegate int XErrorHandler(IntPtr display, IntPtr errorEvent); + + static int OnError(IntPtr display, IntPtr errorEvent) + { + _sawError = 1; + return 0; + } + + void Convert(IntPtr data, XImageHeader header, int sourceWidth, int sourceHeight, byte[] destination, int destX, int destY) + { + if (data == IntPtr.Zero || sourceWidth <= 0 || sourceHeight <= 0) return; + int bpp = header.bits_per_pixel; + if (bpp < 16 || bpp > 32) return; + int bytesPerPixel = (bpp + 7) / 8; + int stride = Math.Abs(header.bytes_per_line); + if (stride < sourceWidth * bytesPerPixel) return; + + ulong redMask = (ulong)header.red_mask.ToInt64(); + ulong greenMask = (ulong)header.green_mask.ToInt64(); + ulong blueMask = (ulong)header.blue_mask.ToInt64(); + if (redMask == 0 && greenMask == 0 && blueMask == 0) + { + redMask = 0x00FF0000; + greenMask = 0x0000FF00; + blueMask = 0x000000FF; + } + bool bigEndian = header.byte_order == 1; + if (_row.Length < stride) _row = new byte[stride]; + var row = _row; + + for (int y = 0; y < sourceHeight; y++) + { + int destRow = destY + y; + if (destRow < 0 || destRow >= _height) continue; + Marshal.Copy(IntPtr.Add(data, y * stride), row, 0, stride); + for (int x = 0; x < sourceWidth; x++) + { + int destCol = destX + x; + if (destCol < 0 || destCol >= _width) continue; + int source = x * bytesPerPixel; + uint pixel = bytesPerPixel switch + { + 4 => bigEndian ? BinaryPrimitives.ReadUInt32BigEndian(row.AsSpan(source, 4)) : BinaryPrimitives.ReadUInt32LittleEndian(row.AsSpan(source, 4)), + 3 => bigEndian + ? (uint)((row[source] << 16) | (row[source + 1] << 8) | row[source + 2]) + : (uint)(row[source] | (row[source + 1] << 8) | (row[source + 2] << 16)), + 2 => bigEndian ? BinaryPrimitives.ReadUInt16BigEndian(row.AsSpan(source, 2)) : BinaryPrimitives.ReadUInt16LittleEndian(row.AsSpan(source, 2)), + _ => 0u, + }; + int index = (destRow * _width + destCol) * 4; + destination[index] = Channel(pixel, blueMask); + destination[index + 1] = Channel(pixel, greenMask); + destination[index + 2] = Channel(pixel, redMask); + destination[index + 3] = 255; + } + } + } + + static byte Channel(uint pixel, ulong mask) + { + if (mask == 0) return 0; + int shift = BitOperations.TrailingZeroCount(mask); + ulong max = mask >> shift; + ulong value = ((ulong)pixel & mask) >> shift; + return (byte)Math.Round(value * 255.0 / max); + } + + [DllImport(X11)] static extern IntPtr XOpenDisplay(string name); + [DllImport(X11)] static extern int XCloseDisplay(IntPtr display); + [DllImport(X11)] static extern IntPtr XSetErrorHandler(XErrorHandler handler); + [DllImport(X11)] static extern IntPtr XDefaultRootWindow(IntPtr display); + [DllImport(X11)] static extern int XDefaultScreen(IntPtr display); + [DllImport(X11)] static extern int XDefaultDepth(IntPtr display, int screen); + [DllImport(X11)] static extern IntPtr XDefaultVisual(IntPtr display, int screen); + [DllImport(X11)] static extern int XSync(IntPtr display, bool discard); + [DllImport(X11)] static extern int XGetGeometry(IntPtr display, IntPtr drawable, out IntPtr root, out int x, out int y, out uint width, out uint height, out uint border, out uint depth); + [DllImport(X11)] static extern int XGetWindowAttributes(IntPtr display, IntPtr window, ref XWindowAttributes attributes); + [DllImport(X11)] static extern bool XTranslateCoordinates(IntPtr display, IntPtr src, IntPtr dest, int srcX, int srcY, out int destX, out int destY, out IntPtr child); + [DllImport(X11)] static extern int XQueryTree(IntPtr display, IntPtr window, out IntPtr root, out IntPtr parent, out IntPtr children, out uint count); + [DllImport(X11)] static extern IntPtr XGetImage(IntPtr display, IntPtr drawable, int x, int y, uint width, uint height, ulong planeMask, int format); + [DllImport(X11)] static extern int XDestroyImage(IntPtr image); + [DllImport(X11)] static extern int XFree(IntPtr data); + [DllImport(X11)] static extern int XFreePixmap(IntPtr display, IntPtr pixmap); + [DllImport(X11)] static extern IntPtr XInternAtom(IntPtr display, string name, bool onlyIfExists); + [DllImport(X11)] static extern int XGetWindowProperty(IntPtr display, IntPtr window, IntPtr atom, long offset, long length, bool delete, IntPtr type, out IntPtr actualType, out int actualFormat, out nuint count, out nuint bytesAfter, out IntPtr prop); + + [DllImport("libXext")] static extern bool XShmQueryExtension(IntPtr display); + [DllImport("libXext")] static extern IntPtr XShmCreateImage(IntPtr display, IntPtr visual, uint depth, int format, IntPtr data, ref XShmSegmentInfo info, uint width, uint height); + [DllImport("libXext")] static extern bool XShmAttach(IntPtr display, ref XShmSegmentInfo info); + [DllImport("libXext")] static extern bool XShmGetImage(IntPtr display, IntPtr drawable, IntPtr image, int x, int y, ulong planeMask); + [DllImport("libXext")] static extern bool XShmDetach(IntPtr display, ref XShmSegmentInfo info); + + [DllImport("libXcomposite.so.1")] static extern IntPtr XCompositeNameWindowPixmap(IntPtr display, IntPtr window); + [DllImport("libXfixes")] static extern IntPtr XFixesGetCursorImage(IntPtr display); + + [DllImport("libc")] static extern int shmget(int key, nuint size, int flags); + [DllImport("libc")] static extern IntPtr shmat(int id, IntPtr address, int flags); + [DllImport("libc")] static extern int shmdt(IntPtr address); + [DllImport("libc")] static extern int shmctl(int id, int command, IntPtr buffer); +} diff --git a/linux/X11Monitors.cs b/linux/X11Monitors.cs new file mode 100644 index 0000000..65dfb5b --- /dev/null +++ b/linux/X11Monitors.cs @@ -0,0 +1,138 @@ +using System.Runtime.InteropServices; +using Avalonia; + +namespace OpenSnip; + +/// Monitor rectangles in X11 root coordinates, matching a full-root capture. +static class X11Monitors +{ + const string X11 = "libX11"; + + public static IReadOnlyList Query() + { + IntPtr display = IntPtr.Zero; + try + { + display = XOpenDisplay(null); + if (display == IntPtr.Zero) return Array.Empty(); + var monitors = QueryXinerama(display); + if (monitors.Count > 0) return monitors; + return new[] { Root(display) }; + } + catch (DllNotFoundException) { return Array.Empty(); } + finally + { + if (display != IntPtr.Zero) { try { XCloseDisplay(display); } catch { } } + } + } + + /// The work area of the monitor that contains most of . + public static PixelRect WorkArea(PixelRect area) + { + var monitors = Query(); + PixelRect monitor = default; + int best = -1; + foreach (var candidate in monitors) + { + var hit = RecordGeometry.Intersect(area, candidate); + int overlap = Math.Max(0, hit.Width) * Math.Max(0, hit.Height); + if (overlap > best) + { + best = overlap; + monitor = candidate; + } + } + if (best <= 0) return area; + + IntPtr display = IntPtr.Zero; + try + { + display = XOpenDisplay(null); + if (display == IntPtr.Zero) return monitor; + if (!TryWorkArea(display, out var work)) return monitor; + var clipped = RecordGeometry.Intersect(work, monitor); + return clipped.Width > 0 && clipped.Height > 0 ? clipped : monitor; + } + catch (DllNotFoundException) { return monitor; } + finally + { + if (display != IntPtr.Zero) { try { XCloseDisplay(display); } catch { } } + } + } + + static List QueryXinerama(IntPtr display) + { + var list = new List(); + try + { + if (!XineramaQueryExtension(display, out _, out _) || !XineramaIsActive(display)) return list; + IntPtr info = XineramaQueryScreens(display, out int count); + if (info == IntPtr.Zero || count <= 0) return list; + try + { + int size = Marshal.SizeOf(); + for (int i = 0; i < count; i++) + { + var screen = Marshal.PtrToStructure(IntPtr.Add(info, i * size)); + if (screen.Width > 0 && screen.Height > 0) + list.Add(new PixelRect(screen.X, screen.Y, screen.Width, screen.Height)); + } + } + finally { XFree(info); } + } + catch (DllNotFoundException) { } + catch (EntryPointNotFoundException) { } + return list; + } + + static PixelRect Root(IntPtr display) + { + IntPtr root = XDefaultRootWindow(display); + if (XGetGeometry(display, root, out _, out _, out _, out uint width, out uint height, out _, out _) == 0) + return default; + return new PixelRect(0, 0, (int)width, (int)height); + } + + static bool TryWorkArea(IntPtr display, out PixelRect area) + { + area = default; + IntPtr atom = XInternAtom(display, "_NET_WORKAREA", true); + if (atom == IntPtr.Zero) return false; + IntPtr root = XDefaultRootWindow(display); + int status = XGetWindowProperty(display, root, atom, 0, 4, false, (IntPtr)6, out _, out _, out nuint count, out _, out IntPtr prop); + if (status != 0 || prop == IntPtr.Zero || count < 4) return false; + try + { + // Format 32 is returned as an array of C longs. + long x = Marshal.ReadInt64(prop, 0); + long y = Marshal.ReadInt64(prop, 8); + long width = Marshal.ReadInt64(prop, 16); + long height = Marshal.ReadInt64(prop, 24); + if (width <= 0 || height <= 0) return false; + area = new PixelRect((int)x, (int)y, (int)width, (int)height); + return true; + } + finally { XFree(prop); } + } + + [StructLayout(LayoutKind.Sequential, Pack = 4)] + struct XineramaScreen + { + public int ScreenNumber; + public short X; + public short Y; + public short Width; + public short Height; + } + + [DllImport(X11)] static extern IntPtr XOpenDisplay(string name); + [DllImport(X11)] static extern int XCloseDisplay(IntPtr display); + [DllImport(X11)] static extern IntPtr XDefaultRootWindow(IntPtr display); + [DllImport(X11)] static extern IntPtr XInternAtom(IntPtr display, string name, bool onlyIfExists); + [DllImport(X11)] static extern int XGetGeometry(IntPtr display, IntPtr drawable, out IntPtr root, out int x, out int y, out uint width, out uint height, out uint border, out uint depth); + [DllImport(X11)] static extern int XGetWindowProperty(IntPtr display, IntPtr window, IntPtr atom, long offset, long length, bool delete, IntPtr type, out IntPtr actualType, out int actualFormat, out nuint count, out nuint bytesAfter, out IntPtr prop); + [DllImport(X11)] static extern int XFree(IntPtr data); + [DllImport("libXinerama.so.1")] static extern bool XineramaQueryExtension(IntPtr display, out int eventBase, out int errorBase); + [DllImport("libXinerama.so.1")] static extern bool XineramaIsActive(IntPtr display); + [DllImport("libXinerama.so.1")] static extern IntPtr XineramaQueryScreens(IntPtr display, out int count); +} diff --git a/tests/OpenSnip.Recording.Tests/CliTests.cs b/tests/OpenSnip.Recording.Tests/CliTests.cs new file mode 100644 index 0000000..e30f41d --- /dev/null +++ b/tests/OpenSnip.Recording.Tests/CliTests.cs @@ -0,0 +1,28 @@ +namespace OpenSnip.Recording.Tests; + +public class CliTests +{ + [Fact] + public void Record_IsItsOwnAction() + { + var options = Cli.Parse(new[] { "--record" }); + Assert.Equal(LaunchAction.Record, options.Action); + Assert.Contains("--record", Cli.Usage); + Assert.Throws(() => Cli.Parse(new[] { "--record", "--snip" })); + Assert.Throws(() => Cli.Parse(new[] { "--record", "--capture", "a.png" })); + } + + [Fact] + public void ApplyLinux_ReplacesAnUnrootedVideoFolder() + { + var settings = new Settings + { + SaveFolder = "/tmp/snips", + VideoFolder = "C:\\Users\\x\\Videos\\OpenSnip", + }; + SettingsDefaults.ApplyLinux(settings); + Assert.Equal("/tmp/snips", settings.SaveFolder); + Assert.Equal(SettingsDefaults.DefaultVideoFolder, settings.VideoFolder); + Assert.True(Path.IsPathRooted(settings.VideoFolder)); + } +} diff --git a/tests/OpenSnip.Recording.Tests/LiveRecordingTests.cs b/tests/OpenSnip.Recording.Tests/LiveRecordingTests.cs new file mode 100644 index 0000000..05c9cb3 --- /dev/null +++ b/tests/OpenSnip.Recording.Tests/LiveRecordingTests.cs @@ -0,0 +1,351 @@ +using System.Diagnostics; +using System.Runtime.InteropServices; +using Avalonia; +using Avalonia.Controls; +using Avalonia.Controls.ApplicationLifetimes; +using Avalonia.Threading; + +namespace OpenSnip.Recording.Tests; + +[Collection("x11")] +public class LiveRecordingTests +{ + [Fact] + public void Grab_PaintsOutAnExcludedWindow() + { + if (!HasDisplay()) return; + using var red = XWin.Open(48, 48, 220, 160, 65535, 0, 0); + using var blue = XWin.Open(90, 80, 80, 60, 0, 0, 65535); + Thread.Sleep(150); + using var source = new X11FrameSource(48, 48, 220, 160); + var buffer = new byte[220 * 160 * 4]; + + Assert.True(source.Grab(buffer, null, false)); + var covered = Pixel(buffer, 220, 70, 50); + Assert.True(covered.B > 200 && covered.R < 30, $"blue window was {covered}"); + + Assert.True(source.Grab(buffer, new[] { blue.Id }, false)); + var rebuilt = Pixel(buffer, 220, 70, 50); + Assert.True(rebuilt.R > 200 && rebuilt.B < 30, $"excluded window stayed {rebuilt}"); + + Assert.True(source.Grab(buffer, new[] { blue.Id }, false)); + var again = Pixel(buffer, 220, 70, 50); + Assert.True(again.R > 200 && again.B < 30, $"second grab was {again}"); + + Assert.True(source.Grab(buffer, new[] { blue.Id }, cursor: true)); + } + + [Fact] + public void FramePump_RecordsARedWindow() + { + if (!HasDisplay() || !FfmpegPlan.Available) return; + using var red = XWin.Open(70, 70, 160, 120, 65535, 0, 0); + Thread.Sleep(100); + string dir = Path.Combine(Path.GetTempPath(), "opensnip-live-" + Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(dir); + string output = Path.Combine(dir, "clip.mp4"); + var pump = new FramePump(new PixelRect(70, 70, 160, 120), new EncodeSpec + { + Width = 160, + Height = 120, + Framerate = 10, + HighQuality = true, + Cursor = false, + Output = output, + }, () => Array.Empty()); + try + { + pump.Start(); + Thread.Sleep(800); + pump.Stop(); + Assert.False(pump.Failed, pump.Error); + Assert.True(new FileInfo(output).Length > 32); + var rgb = ExtractFrame(output); + int pixels = rgb.Length / 3; + int reds = 0; + for (int i = 0; i < pixels; i++) + { + if (rgb[i * 3] > 180 && rgb[i * 3 + 1] < 50 && rgb[i * 3 + 2] < 50) reds++; + } + Assert.True(reds > pixels / 2, $"red pixels {reds} of {pixels}"); + } + finally + { + pump.Dispose(); + try { Directory.Delete(dir, true); } catch { } + } + } + + [Fact] + public async Task Concat_JoinsTwoSegments() + { + if (!HasDisplay() || !FfmpegPlan.Available) return; + using var red = XWin.Open(80, 80, 64, 48, 65535, 0, 0); + string dir = Path.Combine(Path.GetTempPath(), "opensnip-concat-" + Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(dir); + try + { + string first = Path.Combine(dir, "0.mp4"); + string second = Path.Combine(dir, "1.mp4"); + RecordClip(new PixelRect(80, 80, 64, 48), first); + RecordClip(new PixelRect(80, 80, 64, 48), second); + string list = Path.Combine(dir, "list.txt"); + File.WriteAllText(list, FfmpegPlan.ConcatList(new[] { first, second })); + string output = Path.Combine(dir, "all.mp4"); + var psi = new ProcessStartInfo("ffmpeg") + { + UseShellExecute = false, + RedirectStandardError = true, + RedirectStandardOutput = true, + CreateNoWindow = true, + }; + foreach (var arg in FfmpegPlan.ConcatArguments(list, output)) psi.ArgumentList.Add(arg); + using var process = Process.Start(psi); + var stderr = process.StandardError.ReadToEndAsync(); + process.StandardOutput.ReadToEnd(); + Assert.True(process.WaitForExit(15000)); + Assert.True(process.ExitCode == 0 && new FileInfo(output).Length > 32, await stderr); + } + finally + { + try { Directory.Delete(dir, true); } catch { } + } + } + + static void RecordClip(PixelRect area, string output) + { + var pump = new FramePump(area, new EncodeSpec + { + Width = area.Width, + Height = area.Height, + Framerate = 10, + HighQuality = false, + Cursor = false, + Output = output, + }, () => Array.Empty()); + try + { + pump.Start(); + Thread.Sleep(400); + pump.Stop(); + Assert.False(pump.Failed, pump.Error); + } + finally { pump.Dispose(); } + } + + [Fact] + public async Task Session_SavesAClipFromTheControlBar() + { + if (!HasDisplay() || !FfmpegPlan.Available) return; + using var red = XWin.Open(120, 120, 96, 64, 65535, 0, 0); + Thread.Sleep(80); + string dir = Path.Combine(Path.GetTempPath(), "opensnip-session-" + Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(dir); + var done = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var thread = new Thread(() => SessionHost.Run(dir, done)) { IsBackground = true, Name = "OpenSnip session test" }; + thread.Start(); + var finished = await Task.WhenAny(done.Task, Task.Delay(20000)); + Assert.Same(done.Task, finished); + string path = await done.Task; + try + { + Assert.True(new FileInfo(path).Length > 32); + var rgb = ExtractFrame(path); + int pixels = rgb.Length / 3; + int reds = 0; + for (int i = 0; i < pixels; i++) + if (rgb[i * 3] > 180 && rgb[i * 3 + 1] < 50 && rgb[i * 3 + 2] < 50) reds++; + Assert.True(reds > pixels / 2, $"red pixels {reds} of {pixels}"); + } + finally + { + try { Directory.Delete(dir, true); } catch { } + } + } + + [Fact] + public void Monitors_Query_ReturnsAScreen() + { + if (!HasDisplay()) return; + var monitors = X11Monitors.Query(); + Assert.NotEmpty(monitors); + Assert.True(monitors[0].Width >= 16 && monitors[0].Height >= 16); + var work = X11Monitors.WorkArea(monitors[0]); + Assert.True(work.Width >= 16 && work.Height >= 16); + } + + static bool HasDisplay() => !string.IsNullOrWhiteSpace(Environment.GetEnvironmentVariable("DISPLAY")); + + static (byte B, byte G, byte R) Pixel(byte[] bgra, int width, int x, int y) + { + int i = (y * width + x) * 4; + return (bgra[i], bgra[i + 1], bgra[i + 2]); + } + + static byte[] ExtractFrame(string path) + { + var psi = new ProcessStartInfo("ffmpeg") + { + UseShellExecute = false, + RedirectStandardOutput = true, + RedirectStandardError = true, + CreateNoWindow = true, + }; + foreach (var arg in new[] { "-hide_banner", "-loglevel", "error", "-ss", "0.2", "-i", path, "-frames:v", "1", "-f", "rawvideo", "-pix_fmt", "rgb24", "-" }) + psi.ArgumentList.Add(arg); + using var process = Process.Start(psi); + var stderr = process.StandardError.ReadToEndAsync(); + using var memory = new MemoryStream(); + process.StandardOutput.BaseStream.CopyTo(memory); + if (!process.WaitForExit(8000)) + { + try { process.Kill(entireProcessTree: true); } catch { } + throw new InvalidOperationException("Reading the recording back timed out."); + } + string error = stderr.GetAwaiter().GetResult(); + if (process.ExitCode != 0 || memory.Length < 3) + throw new InvalidOperationException("Could not read the recording back: " + error); + return memory.ToArray(); + } + + sealed class XWin : IDisposable + { + IntPtr _display; + public long Id { get; } + + XWin(IntPtr display, long id) + { + _display = display; + Id = id; + } + + public static XWin Open(int x, int y, int width, int height, ushort red, ushort green, ushort blue) + { + var display = XOpenDisplay(null); + if (display == IntPtr.Zero) throw new InvalidOperationException("Cannot open the X11 display."); + XSetErrorHandler(Ignore); + int screen = XDefaultScreen(display); + var color = new XColor { Red = red, Green = green, Blue = blue, Flags = 7 }; + IntPtr pixel = (IntPtr)0x00FF0000; + if (XAllocColor(display, XDefaultColormap(display, screen), ref color) != 0) + pixel = (IntPtr)(long)color.Pixel; + var window = XCreateSimpleWindow(display, XRootWindow(display, screen), x, y, (uint)width, (uint)height, 0, pixel, pixel); + var bytes = new byte[112]; + bytes[88] = 1; + var pin = GCHandle.Alloc(bytes, GCHandleType.Pinned); + try { XChangeWindowAttributes(display, window, 512, pin.AddrOfPinnedObject()); } + finally { pin.Free(); } + XMapWindow(display, window); + XFlush(display); + XSync(display, false); + return new XWin(display, window.ToInt64()); + } + + public void Dispose() + { + if (_display == IntPtr.Zero) return; + try { XDestroyWindow(_display, (IntPtr)Id); XFlush(_display); XCloseDisplay(_display); } + catch { } + _display = IntPtr.Zero; + } + + [StructLayout(LayoutKind.Sequential)] + struct XColor + { + public nuint Pixel; + public ushort Red, Green, Blue; + public byte Flags, Pad; + } + + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + delegate int XErrorHandler(IntPtr display, IntPtr error); + static readonly XErrorHandler Ignore = (_, _) => 0; + + [DllImport("libX11")] static extern IntPtr XOpenDisplay(string name); + [DllImport("libX11")] static extern int XCloseDisplay(IntPtr display); + [DllImport("libX11")] static extern IntPtr XSetErrorHandler(XErrorHandler handler); + [DllImport("libX11")] static extern int XDefaultScreen(IntPtr display); + [DllImport("libX11")] static extern IntPtr XRootWindow(IntPtr display, int screen); + [DllImport("libX11")] static extern IntPtr XDefaultColormap(IntPtr display, int screen); + [DllImport("libX11")] static extern int XAllocColor(IntPtr display, IntPtr colormap, ref XColor color); + [DllImport("libX11")] static extern IntPtr XCreateSimpleWindow(IntPtr display, IntPtr parent, int x, int y, uint width, uint height, uint border, IntPtr borderPixel, IntPtr background); + [DllImport("libX11")] static extern int XChangeWindowAttributes(IntPtr display, IntPtr window, ulong mask, IntPtr attributes); + [DllImport("libX11")] static extern int XMapWindow(IntPtr display, IntPtr window); + [DllImport("libX11")] static extern int XDestroyWindow(IntPtr display, IntPtr window); + [DllImport("libX11")] static extern int XFlush(IntPtr display); + [DllImport("libX11")] static extern int XSync(IntPtr display, bool discard); + } +} + +[CollectionDefinition("x11", DisableParallelization = true)] +public class X11Collection { } + +static class SessionHost +{ + public static void Run(string folder, TaskCompletionSource done) + { + try + { + var lifetime = new ClassicDesktopStyleApplicationLifetime { ShutdownMode = ShutdownMode.OnExplicitShutdown }; + SessionApp.Start(lifetime, folder, done); + AppBuilder.Configure() + .UsePlatformDetect() + .SetupWithLifetime(lifetime); + if (!done.Task.IsCompleted) lifetime.Start(Array.Empty()); + if (!done.Task.IsCompleted) + done.TrySetException(new InvalidOperationException("The recording window closed without a file.")); + } + catch (Exception ex) + { + done.TrySetException(ex); + } + } +} + +sealed class SessionApp : Application +{ + static ClassicDesktopStyleApplicationLifetime _lifetime; + static string _folder; + static TaskCompletionSource _done; + + public static void Start(ClassicDesktopStyleApplicationLifetime lifetime, string folder, TaskCompletionSource done) + { + _lifetime = lifetime; + _folder = folder; + _done = done; + } + + public override void OnFrameworkInitializationCompleted() + { + var settings = new Settings + { + VideoFolder = _folder, + MonthlyFolders = false, + RecordCountdown = false, + RecordSystemAudio = false, + RecordMicrophone = false, + RecordCursor = false, + CopyRecordingToClipboard = false, + ShowThumbnail = false, + RecordHighQuality = false, + RecordFramerate = 10, + }; + var session = new RecordingSession(new PixelRect(120, 120, 96, 64), settings, null, null); + session.Saved += (path, _) => _done.TrySetResult(path); + session.Failed += message => _done.TrySetException(new InvalidOperationException(string.IsNullOrWhiteSpace(message) ? "Recording failed." : message)); + session.Ended += () => + { + if (!_done.Task.IsCompleted) _done.TrySetException(new InvalidOperationException("Recording ended without a file.")); + _lifetime.Shutdown(); + }; + session.Begin(); + var timer = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(700) }; + timer.Tick += (_, _) => + { + timer.Stop(); + session.Stop(); + }; + timer.Start(); + base.OnFrameworkInitializationCompleted(); + } +} diff --git a/tests/OpenSnip.Recording.Tests/OpenSnip.Recording.Tests.csproj b/tests/OpenSnip.Recording.Tests/OpenSnip.Recording.Tests.csproj new file mode 100644 index 0000000..bb8b685 --- /dev/null +++ b/tests/OpenSnip.Recording.Tests/OpenSnip.Recording.Tests.csproj @@ -0,0 +1,25 @@ + + + + net9.0 + enable + disable + false + OpenSnip.Recording.Tests + + + + + + + + + + + + + + + + + diff --git a/tests/OpenSnip.Recording.Tests/PlanTests.cs b/tests/OpenSnip.Recording.Tests/PlanTests.cs new file mode 100644 index 0000000..4695d73 --- /dev/null +++ b/tests/OpenSnip.Recording.Tests/PlanTests.cs @@ -0,0 +1,187 @@ +using Avalonia; + +namespace OpenSnip.Recording.Tests; + +public class PlanTests +{ + [Fact] + public void Normalize_ClipsToTheMonitorWithTheMostOverlap_AndEvensTheSize() + { + var monitors = new[] + { + new PixelRect(0, 0, 1920, 1080), + new PixelRect(1920, 0, 1280, 1024), + }; + var selection = new PixelRect(1800, 100, 400, 301); + Assert.True(RecordGeometry.TryNormalize(selection, monitors, out var area)); + Assert.Equal(new PixelRect(1920, 100, 280, 300), area); + } + + [Fact] + public void Normalize_RejectsATinyArea() + { + var monitors = new[] { new PixelRect(0, 0, 800, 600) }; + Assert.False(RecordGeometry.TryNormalize(new PixelRect(0, 0, 15, 40), monitors, out _)); + Assert.False(RecordGeometry.TryNormalize(new PixelRect(10, 10, 0, 40), monitors, out _)); + } + + [Fact] + public void PlaceBar_PrefersBelow_ThenAbove_ThenInside() + { + var area = new PixelRect(100, 100, 400, 300); + var work = new PixelRect(0, 0, 800, 600); + var below = RecordGeometry.PlaceBar(area, work, 120, 40, 10); + Assert.Equal(new PixelRect(240, 410, 120, 40), below); + + var shortWork = new PixelRect(0, 0, 800, 420); + var above = RecordGeometry.PlaceBar(area, shortWork, 120, 40, 10); + Assert.Equal(new PixelRect(240, 50, 120, 40), above); + + var full = new PixelRect(0, 0, 400, 300); + var inside = RecordGeometry.PlaceBar(full, full, 120, 40, 10); + Assert.True(RecordGeometry.Overlaps(inside, full)); + Assert.Equal(250, inside.Y); + } + + [Fact] + public void Outline_SitsOnTheInsideEdge() + { + var bars = RecordGeometry.Outline(new PixelRect(10, 20, 100, 80), 3); + Assert.Equal(4, bars.Length); + Assert.Equal(new PixelRect(10, 20, 100, 3), bars[0]); + Assert.Equal(new PixelRect(10, 97, 100, 3), bars[1]); + Assert.Equal(new PixelRect(10, 20, 3, 80), bars[2]); + Assert.Equal(new PixelRect(107, 20, 3, 80), bars[3]); + Assert.Empty(RecordGeometry.Outline(new PixelRect(0, 0, 4, 4), 3)); + } + + [Fact] + public void Pactl_Verbose_PicksTheSinkMonitor_AndKeepsMicrophones() + { + string text = """ + Source #0 + Name: alsa_output.pci.analog-stereo.monitor + Description: Monitor of Built-in Audio + Properties: + device.vendor.name = "Example" + Source #1 + Name: alsa_input.pci.analog-stereo + Description: Built-in Microphone + Source #2 + Name: bluez_source.headset + Description: Headset + """; + var audio = AudioDevices.ParsePactl(text, "alsa_output.pci.analog-stereo", "alsa_input.pci.analog-stereo"); + Assert.Equal("alsa_output.pci.analog-stereo.monitor", audio.SystemSource); + Assert.Equal(2, audio.Microphones.Count); + Assert.Equal("alsa_input.pci.analog-stereo", audio.DefaultMicrophone); + Assert.Equal("bluez_source.headset", audio.ResolveMicrophone("bluez_source.headset")); + Assert.Equal("alsa_input.pci.analog-stereo", audio.ResolveMicrophone("missing")); + Assert.Equal("alsa_input.pci.analog-stereo", audio.ResolveMicrophone("")); + } + + [Fact] + public void Pactl_Short_UsesTheFirstMonitorWhenTheSinkIsUnknown() + { + string text = "0\talsp_output.monitor\tmodule\tRUNNING\n1\talsp_input.mic\tmodule\tRUNNING\n"; + var audio = AudioDevices.ParsePactl(text, "other-sink", "nope"); + Assert.Equal("alsp_output.monitor", audio.SystemSource); + Assert.Equal("alsp_input.mic", audio.DefaultMicrophone); + Assert.Single(audio.Microphones); + } + + [Fact] + public void Encode_VideoOnly_UsesCrfAndNoAudio() + { + var args = FfmpegPlan.EncodeArguments(new EncodeSpec + { + Width = 640, + Height = 480, + Framerate = 30, + HighQuality = true, + Output = "/tmp/out.mp4", + }); + Assert.Contains("libx264", args); + Assert.Equal("18", args[args.IndexOf("-crf") + 1]); + Assert.Contains("-an", args); + Assert.DoesNotContain("pulse", args); + Assert.Equal("/tmp/out.mp4", args[^1]); + Assert.Equal("640x480", args[args.IndexOf("-video_size") + 1]); + } + + [Fact] + public void Encode_MutesTheMicWithoutDroppingTheStream() + { + var on = FfmpegPlan.EncodeArguments(Spec(micOn: true, high: false, fps: 99)); + var off = FfmpegPlan.EncodeArguments(Spec(micOn: false, high: false, fps: 0)); + string onFilter = on[on.IndexOf("-filter_complex") + 1]; + string offFilter = off[off.IndexOf("-filter_complex") + 1]; + Assert.Contains("volume=1", onFilter); + Assert.Contains("volume=0", offFilter); + Assert.Contains("amix=inputs=2", onFilter); + Assert.Equal("28", off[off.IndexOf("-crf") + 1]); + Assert.Equal("30", off[off.IndexOf("-framerate") + 1]); + Assert.Equal("60", on[on.IndexOf("-framerate") + 1]); + Assert.Contains("192k", on); + } + + [Fact] + public void Encode_SystemOnly_MapsThatInput() + { + var args = FfmpegPlan.EncodeArguments(new EncodeSpec + { + Width = 16, + Height = 16, + Framerate = 30, + HighQuality = true, + SystemSource = "speakers.monitor", + Output = "a.mp4", + }); + Assert.Equal(1, args.Count(arg => arg == "pulse")); + Assert.Contains("speakers.monitor", args); + Assert.DoesNotContain("-filter_complex", args); + Assert.Contains("aac", args); + } + + [Fact] + public void ConcatList_QuotesSingleQuotes() + { + string list = FfmpegPlan.ConcatList(new[] { "/tmp/a'b.mp4", "/tmp/c.mp4" }); + Assert.Equal("file '/tmp/a'\\''b.mp4'\nfile '/tmp/c.mp4'\n", list); + var args = FfmpegPlan.ConcatArguments("list.txt", "out.mp4"); + Assert.Contains("concat", args); + Assert.Equal("out.mp4", args[^1]); + } + + [Fact] + public void NewRecordingPath_AvoidsACollision() + { + string dir = Path.Combine(Path.GetTempPath(), "opensnip-name-" + Guid.NewGuid().ToString("N")); + string first = FfmpegPlan.NewRecordingPath(dir); + Assert.EndsWith(".mp4", first); + Assert.Contains("Recording ", Path.GetFileName(first)); + File.WriteAllBytes(first, new byte[] { 1 }); + string second = FfmpegPlan.NewRecordingPath(dir); + Assert.NotEqual(first, second); + Directory.Delete(dir, true); + } + + [Fact] + public void FileUri_PercentEncodes() + { + Assert.Equal("file:///tmp/a%20b.mp4", FileUri.FromPath("/tmp/a b.mp4")); + Assert.Contains("file:///", FileUri.FromPath("/tmp/opensnip.mp4")); + } + + static EncodeSpec Spec(bool micOn, bool high, int fps) => new() + { + Width = 32, + Height = 32, + Framerate = fps, + HighQuality = high, + SystemSource = "sys.monitor", + MicSource = "mic", + MicOn = micOn, + Output = "out.mp4", + }; +} diff --git a/tests/OpenSnip.Tests/CliTests.cs b/tests/OpenSnip.Tests/CliTests.cs index 2f8fe88..014cf32 100644 --- a/tests/OpenSnip.Tests/CliTests.cs +++ b/tests/OpenSnip.Tests/CliTests.cs @@ -22,6 +22,15 @@ public void Capture_requires_a_file_and_cannot_be_combined() Assert.Throws(() => Cli.Parse(new[] { "--nope" })); } + [Fact] + public void Record_command_round_trips_to_the_running_instance() + { + Assert.Equal(LaunchAction.Record, Cli.Parse(new[] { "--record" }).Action); + var line = RemoteCommand.Format(LaunchAction.Record, null); + Assert.Equal("record", line); + Assert.Equal(LaunchAction.Record, RemoteCommand.Parse(line).Action); + } + [Fact] public void Single_actions_parse() {