Porter l'éditeur du replay sur Android

En portrait, le panneau des marques et des plages passe sous la vidéo
native. La barre native du replay affiche l'image pendant le glissement
(dernière position, au plus toutes les 60 ms). Les miniatures des marques
sont copiées depuis la surface native avec PixelCopy via la nouvelle
interface IVideoFrameCapture, l'instantané LibVLC ne lisant pas le
décodage matériel.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
This commit is contained in:
Paul Schneider 2026-11-16 17:21:38 +00:00
commit 852f684d82
Signed by: notazof
GPG key ID: AD4B9B545FBD7D12
7 changed files with 157 additions and 16 deletions

View file

@ -1,4 +1,6 @@
using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using Avalonia.Android;
using Avalonia.Controls;
@ -14,7 +16,8 @@ using Button = Android.Widget.Button;
namespace PostIt.Android.Services;
internal sealed class AndroidVideoSurface(MediaPlayer player, bool replay, bool showControls = false, Action? playbackFailed = null) : NativeControlHost, IDisposable
internal sealed class AndroidVideoSurface(MediaPlayer player, bool replay, bool showControls = false, Action? playbackFailed = null)
: NativeControlHost, IDisposable, IVideoFrameCapture
{
private VideoView? _video;
private ReplayLayout? _layout;
@ -71,6 +74,30 @@ internal sealed class AndroidVideoSurface(MediaPlayer player, bool replay, bool
if (_video is not null) _video.MediaPlayer = null;
}
/// <summary>Copies the displayed frame with <see cref="PixelCopy"/>, which also reads hardware-decoded video.</summary>
public async Task<Avalonia.Media.Imaging.Bitmap?> CaptureFrameAsync(int width, CancellationToken ct)
{
if (!OperatingSystem.IsAndroidVersionAtLeast(24) || _disposed
|| _video is not { Width: > 0, Height: > 0, Holder.Surface.IsValid: true } video) return null;
var height = Math.Max(1, (int)Math.Round(width * (double)video.Height / video.Width));
using var bitmap = global::Android.Graphics.Bitmap.CreateBitmap(width, height, global::Android.Graphics.Bitmap.Config.Argb8888!);
using var listener = new PixelCopyListener();
using var registration = ct.Register(() => listener.Result.TrySetCanceled(ct));
using var handler = new Handler(Looper.MainLooper!);
PixelCopy.Request(video, bitmap, listener, handler);
if (await listener.Result.Task != (int)PixelCopyResult.Success) return null;
using var png = new MemoryStream();
if (!bitmap.Compress(global::Android.Graphics.Bitmap.CompressFormat.Png!, 100, png)) return null;
png.Position = 0;
return new Avalonia.Media.Imaging.Bitmap(png);
}
private sealed class PixelCopyListener : Java.Lang.Object, PixelCopy.IOnPixelCopyFinishedListener
{
public TaskCompletionSource<int> Result { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
public void OnPixelCopyFinished(int copyResult) => Result.TrySetResult(copyResult);
}
private void OnPlaybackChanged(object? sender, EventArgs e)
=> Avalonia.Threading.Dispatcher.UIThread.Post(UpdateScreenAwake);
@ -106,6 +133,7 @@ internal sealed class AndroidVideoSurface(MediaPlayer player, bool replay, bool
private readonly ReplayControlsState _state = new();
private readonly Handler _handler = new(Looper.MainLooper!);
private readonly Java.Lang.Runnable _tick;
private readonly Java.Lang.Runnable _preview;
private readonly LinearLayout _bar;
private readonly Button _toggle;
private readonly SeekBar _seek;
@ -137,6 +165,7 @@ internal sealed class AndroidVideoSurface(MediaPlayer player, bool replay, bool
_seek.StopTrackingTouch += EndSeek;
_seek.ProgressChanged += ProgressChanged;
_tick = new Java.Lang.Runnable(Update);
_preview = new Java.Lang.Runnable(ApplyPreview);
_handler.Post(_tick);
}
@ -168,19 +197,37 @@ internal sealed class AndroidVideoSurface(MediaPlayer player, bool replay, bool
_state.Show();
}
private void BeginSeek(object? sender, SeekBar.StartTrackingTouchEventArgs e) => _state.IsInteracting = true;
private void BeginSeek(object? sender, SeekBar.StartTrackingTouchEventArgs e)
{
_state.IsInteracting = true;
_handler.PostDelayed(_preview, 60);
}
private void EndSeek(object? sender, SeekBar.StopTrackingTouchEventArgs e)
{
_handler.RemoveCallbacks(_preview);
_state.EndPreview();
Seek();
_state.IsInteracting = false;
}
private void ProgressChanged(object? sender, SeekBar.ProgressChangedEventArgs e)
{
if (e.FromUser && !_state.IsInteracting) Seek();
if (!e.FromUser) return;
if (_state.IsInteracting) _state.RequestPreview(PositionOf(_seek.Progress));
else Seek();
}
/// <summary>Shows the frame under the thumb while dragging: only the latest position is sent, at most every 60 ms.</summary>
private void ApplyPreview()
{
if (_stopped || !_state.IsInteracting) return;
if (_player.IsSeekable && _state.TryTakePreview(out var time)) _player.Time = time;
_handler.PostDelayed(_preview, 60);
}
private long PositionOf(int progress) => (long)(_player.Length * (progress / 10000d));
private void Seek()
{
if (_player.IsSeekable) _player.Time = (long)(_player.Length * (_seek.Progress / 10000d));
if (_player.IsSeekable) _player.Time = PositionOf(_seek.Progress);
_state.Show();
}
@ -189,11 +236,13 @@ internal sealed class AndroidVideoSurface(MediaPlayer player, bool replay, bool
if (_stopped) return;
_stopped = true;
_handler.RemoveCallbacks(_tick);
_handler.RemoveCallbacks(_preview);
_toggle.Click -= Toggle;
_seek.StartTrackingTouch -= BeginSeek;
_seek.StopTrackingTouch -= EndSeek;
_seek.ProgressChanged -= ProgressChanged;
_tick.Dispose();
_preview.Dispose();
_handler.Dispose();
}
}

View file

@ -1,5 +1,8 @@
using System.Net;
using Avalonia.Controls;
using Avalonia.Threading;
using PostIt.ViewModels;
using PostIt.Views.Blogs;
using Yavsc.Abstract.Streaming;
using Yavsc.Api.Client;
@ -178,6 +181,40 @@ public sealed class ReplayEditorTests(AvaloniaUiFixture ui)
return Task.CompletedTask;
}, TestContext.Current.CancellationToken);
[Fact]
public Task The_editor_stacks_its_panel_under_the_video_in_portrait()
=> ui.RunAsync(async () =>
{
var api = new DraftApi();
// Without a draft source the page skips the native player.
api.Podcast = api.Podcast with { Draft = api.Podcast.Draft! with { SourceBytes = 0 } };
var page = new ReplayEditorPage { DataContext = Editor(api) };
var nav = new NavigationPage();
await nav.PushAsync(page);
var window = new Window { Width = 360, Height = 800, Content = nav };
try
{
window.Show();
foreach (var (width, height) in new[] { (360, 800), (1000, 500), (360, 800) })
{
window.Width = width;
window.Height = height;
Dispatcher.UIThread.RunJobs();
window.UpdateLayout();
var wide = width >= height;
var grid = page.FindControl<Grid>("EditorGrid")!;
var panel = page.FindControl<ScrollViewer>("EditPanel")!;
Assert.Equal(wide ? 2 : 1, grid.ColumnDefinitions.Count);
Assert.Equal(wide ? 1 : 0, Grid.GetColumn(panel));
Assert.Equal(wide ? 1 : 4, Grid.GetRow(panel));
Assert.True(panel.Bounds.Top >= (wide ? 0 : page.FindControl<Border>("VideoBorder")!.Bounds.Bottom));
}
Assert.Contains("source du brouillon", page.FindControl<TextBlock>("PlaybackStatus")!.Text);
}
finally { window.Close(); }
}, TestContext.Current.CancellationToken);
private static ReplayEditorPageViewModel Editor(DraftApi api)
=> new(new PodcastApiClient(api, () => "https://api.example/"), api.Podcast);

View file

@ -0,0 +1,15 @@
using System.Threading;
using System.Threading.Tasks;
using Avalonia.Media.Imaging;
namespace PostIt.Services;
/// <summary>
/// Copies the frame displayed by a native video surface, for platforms where the LibVLC snapshot cannot read
/// hardware-decoded output. The image stays in memory.
/// </summary>
public interface IVideoFrameCapture
{
/// <summary>Returns the displayed frame scaled to <paramref name="width"/> pixels, or null when no frame is available.</summary>
Task<Bitmap?> CaptureFrameAsync(int width, CancellationToken ct);
}

View file

@ -5,21 +5,21 @@
xmlns:vm="using:PostIt.ViewModels"
xmlns:abs="using:Yavsc.Abstract.Streaming"
x:DataType="vm:ReplayEditorPageViewModel">
<Grid ColumnDefinitions="2*,*" RowDefinitions="Auto,*,Auto,Auto" Margin="16" ColumnSpacing="16" RowSpacing="8">
<TextBlock Grid.ColumnSpan="2" Text="{Binding Title}" FontSize="22" TextWrapping="Wrap" />
<Border Grid.Row="1" Background="Black" BorderThickness="1" BorderBrush="Green" MinHeight="240">
<Grid x:Name="EditorGrid" ColumnDefinitions="2*,*" RowDefinitions="Auto,*,Auto,Auto" Margin="16" ColumnSpacing="16" RowSpacing="8">
<TextBlock x:Name="EditorTitle" Grid.ColumnSpan="2" Text="{Binding Title}" FontSize="22" TextWrapping="Wrap" />
<Border x:Name="VideoBorder" Grid.Row="1" Background="Black" BorderThickness="1" BorderBrush="Green" MinHeight="240">
<ContentControl x:Name="VideoSurface" />
</Border>
<WrapPanel Grid.Row="2">
<WrapPanel x:Name="PlaybackCommands" Grid.Row="2">
<Button Content="◀ Image precedente" Click="PreviousFrame_Click" Margin="0,0,8,8"
AutomationProperties.Name="Reculer d'une image" />
<Button Content="Image suivante ▶" Click="NextFrame_Click" Margin="0,0,8,8"
AutomationProperties.Name="Avancer d'une image" />
<Button Content="Ajouter une marque (Ctrl+M)" Command="{Binding AddMarkCommand}" HotKey="Ctrl+M" Margin="0,0,8,8" />
<Button x:Name="AddMarkButton" Content="Ajouter une marque (Ctrl+M)" Command="{Binding AddMarkCommand}" HotKey="Ctrl+M" Margin="0,0,8,8" />
<TextBlock Text="{Binding CurrentTime, StringFormat='Position : {0}'}" VerticalAlignment="Center" />
</WrapPanel>
<TextBlock x:Name="PlaybackStatus" Grid.Row="3" TextWrapping="Wrap" />
<ScrollViewer Grid.Row="1" Grid.RowSpan="3" Grid.Column="1">
<ScrollViewer x:Name="EditPanel" Grid.Row="1" Grid.RowSpan="3" Grid.Column="1">
<StackPanel Spacing="8">
<TextBlock Text="{Binding DraftState}" TextWrapping="Wrap" />
<TextBlock Text="{Binding DurationSummary}" TextWrapping="Wrap" />

View file

@ -2,6 +2,7 @@ using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Interactivity;
using Avalonia.Media.Imaging;
@ -22,10 +23,13 @@ public partial class ReplayEditorPage : ContentPage
private ReplayEditorPageViewModel? _vm;
private string? _snapshotDirectory;
private Task _snapshot = Task.CompletedTask;
private bool? _isWideLayout;
public ReplayEditorPage()
{
InitializeComponent();
if (OperatingSystem.IsAndroid()) AddMarkButton.Content = "Ajouter une marque";
SizeChanged += (_, _) => UpdateResponsiveLayout();
_positionTimer.Tick += (_, _) =>
{
if (_player is { } player && _vm is { } vm) vm.CurrentTimeMs = Math.Max(0, player.Time);
@ -35,9 +39,30 @@ public partial class ReplayEditorPage : ContentPage
protected override void OnNavigatedTo(NavigatedToEventArgs e)
{
base.OnNavigatedTo(e);
UpdateResponsiveLayout();
InitializePlayer();
}
/// <summary>Keeps the video and the edit panel side by side in landscape, and stacks them on a portrait phone.</summary>
private void UpdateResponsiveLayout()
{
var size = TopLevel.GetTopLevel(this)?.ClientSize ?? Bounds.Size;
if (size.Width <= 0 || size.Height <= 0) return;
var isWide = size.Width >= size.Height;
if (_isWideLayout == isWide) return;
_isWideLayout = isWide;
EditorGrid.ColumnDefinitions = new ColumnDefinitions(isWide ? "2*,*" : "*");
// The native video surface stays out of the scroll viewer: only the edit panel scrolls.
EditorGrid.RowDefinitions = new RowDefinitions(isWide ? "Auto,*,Auto,Auto" : "Auto,2*,Auto,Auto,3*");
EditorGrid.Margin = new Thickness(isWide ? 16 : 8);
EditorTitle.FontSize = isWide ? 22 : 18;
VideoBorder.MinHeight = isWide ? 240 : 160;
Grid.SetColumnSpan(EditorTitle, isWide ? 2 : 1);
Grid.SetColumn(EditPanel, isWide ? 1 : 0);
Grid.SetRow(EditPanel, isWide ? 1 : 4);
Grid.SetRowSpan(EditPanel, isWide ? 3 : 1);
}
protected override void OnNavigatedFrom(NavigatedFromEventArgs e)
{
ReleasePlayer();
@ -148,11 +173,13 @@ public partial class ReplayEditorPage : ContentPage
private void NextFrame_Click(object? sender, RoutedEventArgs e) => _player?.NextFrame();
/// <summary>
/// Snapshots the displayed frame into a private temporary file, loads it in memory and deletes the file:
/// Copies the frame from a native surface able to do it (Android), otherwise
/// snapshots the displayed frame into a private temporary file, loads it in memory and deletes the file:
/// thumbnails of the private source never reach a shared cache.
/// </summary>
private async Task<Bitmap?> CaptureThumbnailAsync(CancellationToken ct)
{
if (VideoSurface.Content is IVideoFrameCapture surface) return await surface.CaptureFrameAsync(160, ct);
if (_player is not { } player || _snapshotDirectory is not { } directory) return null;
Directory.CreateDirectory(directory);
var path = Path.Combine(directory, Guid.NewGuid().ToString("N") + ".png");