Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion PARITY.md
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ Status of each Windows feature on Linux. This file describes the tree it ships w
| 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` |
| Hardware H.264 | partial. Cached test encodes select NVENC, then VAAPI with a working render node; recording-size/quality validation falls back to libx264 (18 high, 28 standard). Failures after the recording process starts still end the recording. | `linux/FfmpegPlan.cs`, `linux/HardwareEncoder.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` |
Expand Down
1 change: 1 addition & 0 deletions linux/Diagnostics.cs
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ public static async Task<int> RunAsync(string file)
report.AppendLine("xdg-desktop-portal: " + (portal ? "available" : "unavailable"));
report.AppendLine("Tray host: " + (tray ? "available" : "unavailable"));
report.AppendLine("ffmpeg: " + (FfmpegPlan.Available ? "available" : "missing"));
report.AppendLine("H.264 encoder: " + (FfmpegPlan.Available ? HardwareEncoder.Default.Selected.Name : "unavailable"));
var audio = AudioDevices.Discover();
report.AppendLine("System audio: " + (audio.SystemSource ?? "none"));
report.AppendLine("Microphones: " + (audio.Microphones.Count == 0
Expand Down
18 changes: 9 additions & 9 deletions linux/FfmpegPlan.cs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,10 @@ public static int NormalizeFramerate(int value)
/// <summary>Windows quality 85 / 65, expressed as x264 CRF. Lower is sharper.</summary>
public static int Crf(bool highQuality) => highQuality ? 18 : 28;

public static List<string> EncodeArguments(EncodeSpec spec)
public static List<string> EncodeArguments(EncodeSpec spec) =>
EncodeArguments(spec, HardwareEncoder.Default.ForRecording(spec));

internal static List<string> EncodeArguments(EncodeSpec spec, EncoderChoice encoder)
{
int framerate = NormalizeFramerate(spec.Framerate);
var args = new List<string>
Expand All @@ -46,6 +49,10 @@ public static List<string> EncodeArguments(EncodeSpec spec)
"-i", "pipe:0",
};

var deviceArgs = new List<string>();
HardwareEncoder.AddDeviceArguments(deviceArgs, encoder);
args.InsertRange(4, deviceArgs);

bool system = !string.IsNullOrEmpty(spec.SystemSource);
bool mic = !string.IsNullOrEmpty(spec.MicSource);
if (system) AddPulse(args, spec.SystemSource);
Expand Down Expand Up @@ -74,14 +81,7 @@ public static List<string> EncodeArguments(EncodeSpec spec)
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");
HardwareEncoder.AddVideoArguments(args, encoder, spec.HighQuality);
args.Add("-movflags");
args.Add("+faststart");

Expand Down
132 changes: 132 additions & 0 deletions linux/HardwareEncoder.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
using System.Diagnostics;
using System.Globalization;

namespace OpenSnip;

sealed record EncoderChoice(string Name, string Device = null)
{
public static readonly EncoderChoice Software = new("libx264");
}

/// <summary>Successful test encodes, rather than ffmpeg's compiled-in encoder list, determine support.</summary>
sealed class HardwareEncoder
{
public static readonly HardwareEncoder Default = new(TestEncode, RenderNodes);
readonly Lazy<EncoderChoice> _selected;
readonly Func<EncoderChoice, EncodeSpec, bool> _probe;
readonly object _gate = new();
bool _disabled;
readonly HashSet<(int Width, int Height, int Framerate, bool HighQuality)> _validated = new();

public HardwareEncoder(Func<EncoderChoice, EncodeSpec, bool> probe, Func<IEnumerable<string>> renderNodes)
{
_probe = probe;
_selected = new Lazy<EncoderChoice>(() =>
{
var tiny = new EncodeSpec { Width = 128, Height = 128, Framerate = 30, HighQuality = true };
var nvenc = new EncoderChoice("h264_nvenc");
if (Works(nvenc, tiny)) return nvenc;
try
{
foreach (string node in renderNodes())
{
var vaapi = new EncoderChoice("h264_vaapi", node);
if (Works(vaapi, tiny)) return vaapi;
}
}
catch { /* Missing or inaccessible render nodes mean software encoding. */ }
return EncoderChoice.Software;
});
}

public EncoderChoice Selected
{
get { lock (_gate) return _disabled ? EncoderChoice.Software : _selected.Value; }
}

public EncoderChoice ForRecording(EncodeSpec spec)
{
lock (_gate)
{
var encoder = Selected;
if (encoder == EncoderChoice.Software) return encoder;
var key = (spec.Width, spec.Height, FfmpegPlan.NormalizeFramerate(spec.Framerate), spec.HighQuality);
if (_validated.Contains(key)) return encoder;
if (Works(encoder, spec))
{
_validated.Add(key);
return encoder;
}
// A driver/resource/size failure should not delay every subsequent segment.
_disabled = true;
return EncoderChoice.Software;
}
}

bool Works(EncoderChoice encoder, EncodeSpec spec)
{
try { return _probe(encoder, spec); }
catch { return false; }
}

static IEnumerable<string> RenderNodes() => Directory.Exists("/dev/dri")
? Directory.GetFiles("/dev/dri", "renderD*").OrderBy(path => path, StringComparer.Ordinal)
: Array.Empty<string>();

public static void AddDeviceArguments(List<string> args, EncoderChoice encoder)
{
if (encoder.Name == "h264_vaapi") args.AddRange(new[] { "-vaapi_device", encoder.Device });
}

public static void AddVideoArguments(List<string> args, EncoderChoice encoder, bool high)
{
string quality = FfmpegPlan.Crf(high).ToString(CultureInfo.InvariantCulture);
args.AddRange(new[] { "-c:v", encoder.Name });
switch (encoder.Name)
{
case "h264_nvenc":
args.AddRange(new[] { "-preset", "p4", "-rc", "vbr", "-cq", quality, "-b:v", "0", "-pix_fmt", "yuv420p" });
break;
case "h264_vaapi":
args.AddRange(new[] { "-vf", "format=nv12,hwupload", "-rc_mode", "CQP", "-qp", quality });
break;
default:
args.AddRange(new[] { "-preset", "veryfast", "-crf", quality, "-pix_fmt", "yuv420p" });
break;
}
}

internal static List<string> ProbeArguments(EncoderChoice encoder, EncodeSpec spec)
{
var args = new List<string> { "-hide_banner", "-loglevel", "error", "-nostdin" };
AddDeviceArguments(args, encoder);
// Exercise the same BGRA conversion/upload path as the recording input.
args.AddRange(new[] { "-f", "lavfi", "-i",
FormattableString.Invariant($"color=size={spec.Width}x{spec.Height}:rate={FfmpegPlan.NormalizeFramerate(spec.Framerate)},format=bgra"),
"-frames:v", "1", "-an" });
AddVideoArguments(args, encoder, spec.HighQuality);
args.AddRange(new[] { "-f", "null", "-" });
return args;
}

static bool TestEncode(EncoderChoice encoder, EncodeSpec spec)
{
var psi = new ProcessStartInfo("ffmpeg")
{
UseShellExecute = false, RedirectStandardError = true,
RedirectStandardOutput = true, CreateNoWindow = true,
};
foreach (string arg in ProbeArguments(encoder, spec)) psi.ArgumentList.Add(arg);
using var process = Process.Start(psi);
if (process == null) return false;
var error = process.StandardError.ReadToEndAsync();
var output = process.StandardOutput.ReadToEndAsync();
if (!process.WaitForExit(1500))
{
try { process.Kill(entireProcessTree: true); process.WaitForExit(); } catch { }
return false;
}
Task.WhenAll(error, output).GetAwaiter().GetResult();
return process.ExitCode == 0;
}
}
98 changes: 98 additions & 0 deletions tests/OpenSnip.Recording.Tests/HardwareEncoderTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
namespace OpenSnip.Recording.Tests;

public class HardwareEncoderTests
{
[Fact]
public void Selection_PrefersNvenc_AndCachesProbe()
{
int calls = 0;
var selector = new HardwareEncoder((encoder, _) => { calls++; return true; },
() => throw new InvalidOperationException());
Assert.Equal("h264_nvenc", selector.Selected.Name);
Assert.Equal(selector.Selected, selector.Selected);
Assert.Equal(1, calls);
}

[Fact]
public void Selection_TriesEachRenderNode_AndCachesSoftware()
{
var attempted = new List<EncoderChoice>();
var selector = new HardwareEncoder((encoder, _) =>
{
attempted.Add(encoder);
return encoder.Device == "/dev/dri/renderD129";
}, () => new[] { "/dev/dri/renderD128", "/dev/dri/renderD129" });
Assert.Equal(new EncoderChoice("h264_vaapi", "/dev/dri/renderD129"), selector.Selected);
Assert.Equal(3, attempted.Count);
var failed = new HardwareEncoder((_, _) => throw new IOException(), () => Array.Empty<string>());
Assert.Equal(EncoderChoice.Software, failed.Selected);
Assert.Equal(EncoderChoice.Software, failed.Selected);
}

[Fact]
public void RecordingValidation_FallsBackAndDisablesHardwareAfterFailure()
{
int calls = 0;
var selector = new HardwareEncoder((_, spec) => { calls++; return spec.Width == 128; },
() => Array.Empty<string>());
var spec = new EncodeSpec { Width = 1920, Height = 1080 };
Assert.Equal(EncoderChoice.Software, selector.ForRecording(spec));
Assert.Equal(EncoderChoice.Software, selector.ForRecording(spec));
Assert.Equal(EncoderChoice.Software, selector.Selected);
Assert.Equal(2, calls);
}

[Fact]
public void RecordingValidation_CachesEachSizeFramerateAndQuality()
{
int calls = 0;
var selector = new HardwareEncoder((_, _) => { calls++; return true; },
() => Array.Empty<string>());
var spec = new EncodeSpec { Width = 1920, Height = 1080, Framerate = 30 };
Assert.Equal("h264_nvenc", selector.ForRecording(spec).Name);
selector.ForRecording(spec);
Assert.Equal(2, calls); // Discovery and the first recording configuration.
spec.HighQuality = true;
selector.ForRecording(spec);
spec.Width = 1280;
selector.ForRecording(spec);
spec.Framerate = 60;
selector.ForRecording(spec);
Assert.Equal(5, calls);
}

[Fact]
public void Selection_FallsBackWhenRenderNodesAreInaccessible()
{
var selector = new HardwareEncoder((_, _) => false,
() => throw new UnauthorizedAccessException());
Assert.Equal(EncoderChoice.Software, selector.Selected);
}

[Theory]
[InlineData(true, "18")]
[InlineData(false, "28")]
public void Arguments_MapQualityAndUploadOnlyForVaapi(bool high, string quality)
{
var spec = new EncodeSpec { Width = 1920, Height = 1080, Framerate = 60,
HighQuality = high, SystemSource = "monitor", MicSource = "mic", Output = "clip.mp4" };
var nvenc = FfmpegPlan.EncodeArguments(spec, new EncoderChoice("h264_nvenc"));
Assert.Equal(quality, nvenc[nvenc.IndexOf("-cq") + 1]);
Assert.Contains("yuv420p", nvenc);
Assert.DoesNotContain("-crf", nvenc);
Assert.DoesNotContain("hwupload", nvenc);
var encoder = new EncoderChoice("h264_vaapi", "/dev/dri/renderD129");
var vaapi = FfmpegPlan.EncodeArguments(spec, encoder);
Assert.Equal(quality, vaapi[vaapi.IndexOf("-qp") + 1]);
Assert.Equal("/dev/dri/renderD129", vaapi[vaapi.IndexOf("-vaapi_device") + 1]);
Assert.True(vaapi.IndexOf("-vaapi_device") < vaapi.IndexOf("-i"));
Assert.Contains("format=nv12,hwupload", vaapi);
Assert.Contains("-filter_complex", vaapi);
Assert.DoesNotContain("-pix_fmt", vaapi);
Assert.Equal("clip.mp4", vaapi[^1]);
var probe = HardwareEncoder.ProbeArguments(encoder, spec);
Assert.Contains("color=size=1920x1080:rate=60,format=bgra", probe);
Assert.Equal(quality, probe[probe.IndexOf("-qp") + 1]);
Assert.Contains("format=nv12,hwupload", probe);
}
}
10 changes: 6 additions & 4 deletions tests/OpenSnip.Recording.Tests/PlanTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ public void Pactl_Short_UsesTheFirstMonitorWhenTheSinkIsUnknown()
[Fact]
public void Encode_VideoOnly_UsesCrfAndNoAudio()
{
var args = FfmpegPlan.EncodeArguments(new EncodeSpec
var args = SoftwareArguments(new EncodeSpec
{
Width = 640,
Height = 480,
Expand All @@ -112,8 +112,8 @@ public void Encode_VideoOnly_UsesCrfAndNoAudio()
[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));
var on = SoftwareArguments(Spec(micOn: true, high: false, fps: 99));
var off = SoftwareArguments(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);
Expand All @@ -128,7 +128,7 @@ public void Encode_MutesTheMicWithoutDroppingTheStream()
[Fact]
public void Encode_SystemOnly_MapsThatInput()
{
var args = FfmpegPlan.EncodeArguments(new EncodeSpec
var args = SoftwareArguments(new EncodeSpec
{
Width = 16,
Height = 16,
Expand Down Expand Up @@ -173,6 +173,8 @@ public void FileUri_PercentEncodes()
Assert.Contains("file:///", FileUri.FromPath("/tmp/opensnip.mp4"));
}

static List<string> SoftwareArguments(EncodeSpec spec) => FfmpegPlan.EncodeArguments(spec, EncoderChoice.Software);

static EncodeSpec Spec(bool micOn, bool high, int fps) => new()
{
Width = 32,
Expand Down
Loading