feat/calls #62

Open
notazof wants to merge 104 commits from feat/calls into main
7 changed files with 157 additions and 16 deletions
Showing only changes of commit 852f684d82 - Show all commits

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>
Paul Schneider 2026-11-16 17:21:38 +00:00
Signed by: notazof
GPG key ID: AD4B9B545FBD7D12

View file

@ -6,6 +6,8 @@
### Added
* [PostIt/Android] Port the replay draft editor to Android: the page stacks the mark and range panel under the native video in portrait, the native replay seek bar previews the dragged position (latest position only, at most every 60 ms, shared `ReplayControlsState`), and mark thumbnails are copied from the native surface with `PixelCopy` through the new `IVideoFrameCapture`, since the LibVLC snapshot cannot read hardware-decoded output.
* [Podcasts] Publish named marks as replay chapters: the draft stores optional mark titles (`Chapters`, at most 120 characters, a title's time is also a mark, titles of removed marks are dropped). Publication converts their times to the published timeline, embeds them in the MP4 with an FFmpeg stream copy (titles only go through an escaped metadata file) and exposes them in `PodcastResponse.Chapters`. The PostIt editor names marks, and the PostIt replay player and the web podcasts page list the chapters as buttons that seek the replay.
* [PostIt/Podcasts] Add the desktop replay draft editor: from the refinement panel, the owner plays the private draft source, steps frame by frame, adds marks at the current time (Ctrl+M) with local thumbnails, picks start and end marks to remove ranges, restores ranges, then saves with the read revision (a conflict keeps local edits and asks for a reload) or publishes after saving pending edits. `ReplayEditPlan` moves to `Yavsc.Abstract` so the editor merges and validates ranges like the server.

View file

@ -65,8 +65,8 @@ Le lecteur de direct utilise les segments et rejoint le flux près du direct.
Sur ordinateur, les contrôles du lecteur sont des contrôles Avalonia. Sur
Android, la surface vidéo et ses commandes sont natives. Sur desktop, le
curseur de replay met à jour l'image pendant son déplacement (voir le résultat
du prototype ci-dessous) ; sur Android, la recherche n'est encore validée qu'au
relâchement.
du prototype ci-dessous) ; la barre native Android fait de même, avec la même
coalescence des positions (voir « Éditeur Android »).
Les captures PostIt desktop et Android n'utilisent pas le même pipeline média.
@ -308,9 +308,20 @@ Le brouillon privé est implémenté côté serveur, et son éditeur sur PostIt
copie de la source. `PodcastResponse.Chapters` expose les chapitres publiés
à tous les auditeurs ; le site web les affiche en boutons sous le lecteur du
MP4 et PostIt dans le lecteur du replay, chacun positionnant la lecture.
- **Éditeur Android** : la même page et le même modèle de vue s'ouvrent
depuis les podcasts Android, sur la surface vidéo native. En portrait, le
panneau des marques et des plages passe sous la vidéo et défile seul (la
surface native reste hors du défilement) ; en paysage, il reste à droite.
Pendant le glissement, la barre native n'envoie au lecteur que la dernière
position demandée, au plus toutes les 60 ms (`ReplayControlsState`, partagé
avec desktop), et applique la position finale au relâchement. L'instantané
LibVLC ne lit pas la sortie du décodage matériel : la surface Android
implémente `IVideoFrameCapture` et copie l'image affichée avec `PixelCopy`
(Android 7 et plus ; sans miniature avant), directement en mémoire.
- **Reste à faire** : miniatures des marques rechargées depuis le serveur
(elles ne sont créées qu'à la pose), éditeur Android et validation sur de
vrais médias.
(elles ne sont créées qu'à la pose), validation sur de vrais médias et
essais de l'éditeur Android sur appareil (réactivité du glissement sur un
long replay distant, précision du pas image par image).
Une émission interrompue doit rester récupérable par son auteur. Lorsqu'un
direct programmé s'arrête après le délai « Direct interrompu », ou qu'un
@ -414,7 +425,7 @@ différent de celui annoncé à l'auteur.
4. Valider la finalisation sur de vrais médias synthétiques et conserver le
comportement existant pour les émissions sans raffinage.
5. Porter l'éditeur sur Android (surface native), en réutilisant l'API et le
traitement serveur.
traitement serveur (fait, essais sur appareil à mener).
6. Étudier la composition live, d'abord sur desktop puis sur Android, avant
d'engager les génériques et les incrustations.

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");