Preview replay frames while dragging the desktop slider

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
This commit is contained in:
Paul Schneider 2026-11-16 13:39:34 +00:00
commit 762fc35b9c
Signed by: notazof
GPG key ID: AD4B9B545FBD7D12
5 changed files with 134 additions and 8 deletions

View file

@ -206,6 +206,86 @@ public sealed class PodcastReplayTests
Assert.Equal("1:01:02", ReplayControlsState.FormatTime(3662000));
}
[Fact]
public void Drag_preview_keeps_only_the_latest_new_position()
{
var state = new ReplayControlsState();
Assert.False(state.TryTakePreview(out _));
state.RequestPreview(1000);
state.RequestPreview(2000);
Assert.True(state.TryTakePreview(out var time));
Assert.Equal(2000, time);
Assert.False(state.TryTakePreview(out _));
state.RequestPreview(2000);
Assert.False(state.TryTakePreview(out _));
state.EndPreview();
state.RequestPreview(2000);
Assert.True(state.TryTakePreview(out time));
Assert.Equal(2000, time);
}
public static bool HasFfmpeg => (Environment.GetEnvironmentVariable("PATH") ?? "")
.Split(Path.PathSeparator).Any(dir => File.Exists(Path.Combine(dir, "ffmpeg")));
[Fact(Skip = "Install ffmpeg and LibVLC.", SkipUnless = nameof(HasFfmpeg))]
public async Task LibVLC_shows_the_exact_frame_after_seeking_while_paused()
{
const int Fps = 25, Size = 64;
var path = Path.Combine(Path.GetTempPath(), $"postit-frames-{Guid.NewGuid():N}.mp4");
try
{
// Each frame N has luma 2N; keyframes every 2 s so seeks land between keyframes.
var source = "color=black:s=" + Size + "x" + Size + ":r=" + Fps + ":d=4,format=yuv420p,geq=lum='N*2':cb=128:cr=128";
var start = new System.Diagnostics.ProcessStartInfo("ffmpeg");
foreach (var argument in new[] { "-v", "error", "-f", "lavfi", "-i", source,
"-c:v", "libx264", "-qp", "0", "-g", "50", "-pix_fmt", "yuv420p", path })
start.ArgumentList.Add(argument);
using (var ffmpeg = System.Diagnostics.Process.Start(start))
{
Assert.NotNull(ffmpeg);
await ffmpeg.WaitForExitAsync(_ct);
Assert.Equal(0, ffmpeg.ExitCode);
}
var frame = -1;
var buffer = Marshal.AllocHGlobal(Size * Size * 4);
try
{
using var vlc = new LibVLC("--no-audio");
using var player = new MediaPlayer(vlc);
using var media = new Media(vlc, path, FromType.FromPath);
player.SetVideoFormat("RV32", Size, Size, Size * 4);
player.SetVideoCallbacks((_, planes) => { Marshal.WriteIntPtr(planes, buffer); return IntPtr.Zero; }, null,
(_, _) =>
{
// Undo the limited-range YUV to RGB conversion on the red channel.
var red = Marshal.ReadByte(buffer, (Size * (Size / 2) + Size / 2) * 4 + 2);
Volatile.Write(ref frame, (int)Math.Round((red * 219.0 / 255 + 16) / 2));
});
Assert.True(player.Play(media));
await WaitFor(() => player.IsPlaying && Volatile.Read(ref frame) >= 0);
player.SetPause(true);
await WaitFor(() => !player.IsPlaying);
foreach (var target in new[] { 37, 73, 12, 61 })
{
player.Time = target * 1000L / Fps + 20;
await WaitFor(() => Volatile.Read(ref frame) == target);
Assert.Equal(target, Volatile.Read(ref frame));
Assert.False(player.IsPlaying);
}
player.Stop();
}
finally { Marshal.FreeHGlobal(buffer); }
}
finally { File.Delete(path); }
async Task WaitFor(Func<bool> condition)
{
for (var i = 0; i < 100 && !condition(); i++) await Task.Delay(50, _ct);
}
}
private sealed class Clock : TimeProvider
{
public DateTimeOffset Now { get; set; } = DateTimeOffset.UtcNow;

View file

@ -14,6 +14,7 @@ public partial class ReplayControls : UserControl
{
private readonly ReplayControlsState _state = new();
private readonly DispatcherTimer _timer = new() { Interval = TimeSpan.FromMilliseconds(250) };
private readonly DispatcherTimer _previewTimer = new() { Interval = TimeSpan.FromMilliseconds(60) };
private MediaPlayer? _player;
private bool _updating;
@ -21,6 +22,7 @@ public partial class ReplayControls : UserControl
{
InitializeComponent();
_timer.Tick += Update;
_previewTimer.Tick += (_, _) => ApplyPreview();
PointerMoved += (_, _) => _state.Show();
PointerPressed += (_, _) => _state.Show();
KeyDown += (_, _) => _state.Show();
@ -54,6 +56,7 @@ public partial class ReplayControls : UserControl
protected override void OnDetachedFromVisualTree(VisualTreeAttachmentEventArgs e)
{
_timer.Stop();
_previewTimer.Stop();
base.OnDetachedFromVisualTree(e);
}
@ -76,12 +79,21 @@ public partial class ReplayControls : UserControl
{
_state.IsInteracting = true;
_state.Show();
_previewTimer.Start();
}
private void EndSeek(object? sender, PointerReleasedEventArgs e) => CommitSeek();
private void ApplyPreview()
{
if (_player is { IsSeekable: true } player && _state.TryTakePreview(out var time))
player.Time = time;
}
private void CommitSeek()
{
_previewTimer.Stop();
_state.EndPreview();
if (_player is { IsSeekable: true } player) player.Time = (long)PositionSlider.Value;
_state.IsInteracting = false;
_state.Show();
@ -89,7 +101,9 @@ public partial class ReplayControls : UserControl
private void Position_Changed(object? sender, RangeBaseValueChangedEventArgs e)
{
if (!_updating && !_state.IsInteracting) CommitSeek();
if (_updating) return;
if (_state.IsInteracting) _state.RequestPreview((long)e.NewValue);
else CommitSeek();
}
private void Toggle_Click(object? sender, RoutedEventArgs e)

View file

@ -6,8 +6,25 @@ public sealed class ReplayControlsState(TimeProvider? clock = null)
{
private readonly TimeProvider _clock = clock ?? TimeProvider.System;
private DateTimeOffset _lastInteraction = (clock ?? TimeProvider.System).GetUtcNow();
private long? _pendingPreview;
private long? _appliedPreview;
public bool IsInteracting { get; set; }
public void Show() => _lastInteraction = _clock.GetUtcNow();
/// <summary>Records the latest position requested while dragging; older requests are dropped.</summary>
public void RequestPreview(long milliseconds) => _pendingPreview = Math.Max(0, milliseconds);
/// <summary>Returns the latest unapplied preview position, if any.</summary>
public bool TryTakePreview(out long milliseconds)
{
milliseconds = _pendingPreview ?? 0;
var take = _pendingPreview is { } pending && pending != _appliedPreview;
_pendingPreview = null;
if (take) _appliedPreview = milliseconds;
return take;
}
public void EndPreview() => _pendingPreview = _appliedPreview = null;
public bool IsVisible(bool playing, bool focused)
=> !playing || focused || IsInteracting || _clock.GetUtcNow() - _lastInteraction < TimeSpan.FromSeconds(3);