screen orientation and awake

This commit is contained in:
Paul Schneider 2026-11-05 10:44:19 +00:00
commit fa8038c676
Signed by: notazof
GPG key ID: AD4B9B545FBD7D12
25 changed files with 941 additions and 110 deletions

View file

@ -27,7 +27,8 @@ public sealed class AndroidCameraFrameRotationTestActivity : Activity
{
foreach (var rotation in new[] { 0, 90, 180, 270 })
await VerifyRotationAsync(rotation);
File.WriteAllText(resultPath, "PASS\nrotations=0,90,180,270\nformat=MPEG-TS\npreview=RGBA,detach,reattach,letterbox\nsource=synthetic");
await VerifyPreviewOnlyAsync();
File.WriteAllText(resultPath, "PASS\nrotations=0,90,180,270\nformat=MPEG-TS\npreview=RGBA,detach,reattach,letterbox,without-encoder,dynamic-rotation\nsource=synthetic");
}
catch (Exception ex)
{
@ -36,6 +37,59 @@ public sealed class AndroidCameraFrameRotationTestActivity : Activity
finally { Finish(); }
}
private async Task VerifyPreviewOnlyAsync()
{
const int width = 640, height = 480;
using var reader = ImageReader.NewInstance(640, 640, (ImageFormatType)Format.Rgba8888, 3)
?? throw new InvalidOperationException("Preview reader unavailable.");
Exception? failure = null;
using var rotator = await AndroidCameraFrameRotator.CreateAsync(null, width, height, 0,
error => failure = error);
await rotator.SetPreviewAsync(reader.Surface, reader.Width, reader.Height, error => failure = error);
await rotator.StartAsync();
using var paint = new Paint();
Color[] colors = [Color.Red, Color.Green, Color.Blue, Color.Yellow];
foreach (var rotation in new[] { 0, 90, 180, 270 })
{
await rotator.SetRotationAsync(rotation);
var verified = 0;
for (var frame = 0; frame < 20; frame++)
{
if (failure is not null) throw failure;
var canvas = rotator.CameraSurface.LockCanvas(null)
?? throw new InvalidOperationException("Synthetic preview canvas unavailable.");
try
{
for (var index = 0; index < colors.Length; index++)
{
paint.Color = colors[index];
var x = index % 2 * width / 2;
var y = index / 2 * height / 2;
canvas.DrawRect(x, y, x + width / 2, y + height / 2, paint);
}
}
finally
{
rotator.CameraSurface.UnlockCanvasAndPost(canvas);
canvas.Dispose();
}
await Task.Delay(34);
using var image = reader.AcquireLatestImage();
if (image is null) continue;
try
{
if (frame < 3) continue;
VerifyPreview(image, rotation, rotation is 90 or 270 ? height : width,
rotation is 90 or 270 ? width : height);
verified++;
}
finally { image.Close(); }
}
if (verified < 3) throw new InvalidOperationException($"Preview-only rotation {rotation}: insufficient frames.");
}
await rotator.SetPreviewAsync(null);
}
private async Task VerifyRotationAsync(int rotation)
{
const int width = 640;

View file

@ -0,0 +1,118 @@
#if ANDROID
using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Views;
using Avalonia.Controls;
using Avalonia.Threading;
using LibVLCSharp.Shared;
using PostIt.Android;
using PostIt.Android.Services;
using PostIt.Services;
namespace PostIt.Tests;
[Activity(Name = "fr.pschneider.postit.ScreenAwakeTestActivity", Exported = true)]
public sealed class AndroidScreenAwakeTestActivity : Activity
{
protected override async void OnCreate(Bundle? state)
{
base.OnCreate(state);
var result = Path.Combine(FilesDir!.AbsolutePath, "screen-awake-test-result.txt");
File.WriteAllText(result, "RUNNING");
try
{
using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(45));
await RunAsync(timeout.Token);
File.WriteAllText(result, "PASS\nplayback,pause,resume,stop,end,teardown,overlap,background,foreground");
}
catch (Exception ex) { File.WriteAllText(result, "FAIL\n" + ex); }
finally { Finish(); }
}
private async Task RunAsync(CancellationToken ct)
{
StartActivity(new Intent(this, typeof(MainActivity)).AddFlags(ActivityFlags.NewTask));
await WaitAsync(() => MainActivity.IsForeground && (Avalonia.Application.Current as App)?.View is not null, ct);
var fixture = Path.Combine(FilesDir!.AbsolutePath, "screen-awake-fixture.mp4");
if (!File.Exists(fixture)) throw new IOException("An explicit local video fixture is required.");
var app = (App)Avalonia.Application.Current!;
var navigation = app.View!.FindControl<NavigationPage>("NavRoot")
?? throw new InvalidOperationException("Main navigation unavailable.");
using var vlc = new LibVLC();
using var player = new MediaPlayer(vlc);
AndroidVideoSurface? surface = null;
IDisposable? capture = null;
var attached = false;
try
{
await Dispatcher.UIThread.InvokeAsync(async () =>
{
surface = new AndroidVideoSurface(player, false);
await navigation.PushAsync(new ContentPage { Content = surface });
attached = true;
});
await surface!.Ready.WaitAsync(ct);
await WaitAsync(() => !ScreenIsKeptOn(), ct);
using var repeated = new Media(vlc, fixture, FromType.FromPath);
repeated.AddOption(":input-repeat=100");
if (!player.Play(repeated)) throw new InvalidOperationException("Playback did not start.");
await WaitAsync(() => player.IsPlaying && ScreenIsKeptOn(), ct);
player.Pause();
await WaitAsync(() => !player.IsPlaying && !ScreenIsKeptOn(), ct);
if (!player.Play()) throw new InvalidOperationException("Playback did not resume.");
await WaitAsync(ScreenIsKeptOn, ct);
capture = Platform.ScreenAwake.Acquire();
player.Stop();
await WaitAsync(() => !player.IsPlaying && Platform.ScreenAwake.IsRequested && ScreenIsKeptOn(), ct);
capture.Dispose();
capture = null;
await WaitAsync(() => !ScreenIsKeptOn(), ct);
using var once = new Media(vlc, fixture, FromType.FromPath);
var ended = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
player.EndReached += (_, _) => ended.TrySetResult();
if (!player.Play(once)) throw new InvalidOperationException("Finite playback did not start.");
await WaitAsync(ScreenIsKeptOn, ct);
await ended.Task.WaitAsync(ct);
await WaitAsync(() => !ScreenIsKeptOn(), ct);
if (!player.Play(repeated)) throw new InvalidOperationException("Teardown playback did not start.");
await WaitAsync(ScreenIsKeptOn, ct);
await Dispatcher.UIThread.InvokeAsync(() => surface.Dispose());
await WaitAsync(() => !ScreenIsKeptOn() && !Platform.ScreenAwake.IsRequested, ct);
player.Stop();
capture = Platform.ScreenAwake.Acquire();
await WaitAsync(ScreenIsKeptOn, ct);
StartActivity(new Intent(Intent.ActionMain).AddCategory(Intent.CategoryHome).AddFlags(ActivityFlags.NewTask));
await WaitAsync(() => !MainActivity.IsForeground && !ScreenIsKeptOn(), ct);
StartActivity(new Intent(this, typeof(MainActivity)).AddFlags(ActivityFlags.NewTask));
await WaitAsync(() => MainActivity.IsForeground && ScreenIsKeptOn(), ct);
capture.Dispose();
capture = null;
await WaitAsync(() => !ScreenIsKeptOn(), ct);
}
finally
{
capture?.Dispose();
await Dispatcher.UIThread.InvokeAsync(() => surface?.Dispose());
player.Stop();
if (attached) await Dispatcher.UIThread.InvokeAsync(async () => await navigation.PopAsync());
}
}
private static bool ScreenIsKeptOn()
=> MainActivity.Current?.Window?.Attributes is { } attributes
&& (attributes.Flags & WindowManagerFlags.KeepScreenOn) != 0;
private static async Task WaitAsync(Func<bool> condition, CancellationToken ct)
{
while (!await Dispatcher.UIThread.InvokeAsync(condition))
await Task.Delay(50, ct);
}
}
#endif

View file

@ -26,26 +26,44 @@ public sealed class CameraFrameOrientationTests
public void Maps_output_corners_to_input_for_clockwise_rotation(int rotation, float[] expected)
=> Assert.Equal(expected, CameraFrameOrientation.GetTextureCoordinates(rotation));
[Theory]
[InlineData(90, 0, -1, 0)]
[InlineData(270, 0, 1, 0)]
[InlineData(180, -1, 0, 0)]
[InlineData(90, 1, 0, 90)]
[InlineData(270, 1, 0, 270)]
[InlineData(0, 0, -1, 270)]
[InlineData(180, 0, -1, 90)]
public void Does_not_repeat_rotation_already_in_surface_texture(
int desired, float x, float y, int expected)
[Fact]
public void Sensor_rotation_and_display_changes_map_corners_for_all_lens_orientations()
{
float[] matrix = [x, y, 0, 0, y, -x, 0, 0, 0, 0, 1, 0, 1, 1, 0, 1];
Assert.Equal(expected, CameraFrameOrientation.GetRemainingRotation(desired, matrix));
foreach (var sensor in new[] { 0, 90, 180, 270 })
foreach (var display in new[] { 0, 90, 180, 270 })
foreach (var front in new[] { false, true })
{
var rotation = CameraFrameOrientation.GetRotation(sensor, display, front);
var coordinates = CameraFrameOrientation.GetTextureCoordinates(rotation);
float[] expected = [0, 0, 1, 0, 0, 1, 1, 1];
var turns = (sensor / 90 + (front ? display / 90 : -display / 90) + 4) % 4;
for (var turn = 0; turn < turns; turn++)
for (var index = 0; index < expected.Length; index += 2)
(expected[index], expected[index + 1]) = (1 - expected[index + 1], expected[index]);
Assert.Equal(expected, coordinates);
}
}
[Theory]
[InlineData(new float[] { 1, 0, 0, 0, 0, -1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1 }, 90, 90)]
[InlineData(new float[] { 1, 0, 0, 0, 0, -1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1 }, 270, 270)]
// Measured on a real Android 15 phone in portrait (rear sensor 90°, front sensor 270°).
[InlineData(new float[] { 0, -1, 0, 0, -1, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 1 }, 90, 0)]
[InlineData(new float[] { 0, -1, 0, 0, -1, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 1 }, 0, 270)]
[InlineData(new float[] { 0, -1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1 }, 270, 0)]
[InlineData(new float[] { 0, -1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1 }, 0, 270)]
[InlineData(new float[] { 0, -1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1 }, 180, 90)]
public void Does_not_apply_the_rotation_already_in_the_texture_transform_twice(
float[] matrix, int rotation, int expected)
=> Assert.Equal(expected, CameraFrameOrientation.GetRemainingRotation(rotation, matrix));
[Fact]
public void Recognizes_the_measured_rear_camera_transform_even_with_cropping()
public void Rejects_invalid_texture_transforms()
{
float[] matrix = [0, -0.9f, 0, 0, -0.8f, 0, 0, 0, 0, 0, 1, 0, 0.9f, 0.95f, 0, 1];
Assert.Equal(0, CameraFrameOrientation.GetRemainingRotation(90, matrix));
Assert.Throws<ArgumentException>(() => CameraFrameOrientation.GetRemainingRotation(0, new float[15]));
Assert.Throws<ArgumentException>(() => CameraFrameOrientation.GetRemainingRotation(0, new float[16]));
var skewed = new float[] { 0.7f, -0.7f, 0, 0, -0.7f, -0.7f, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1 };
Assert.Throws<ArgumentException>(() => CameraFrameOrientation.GetRemainingRotation(0, skewed));
}
[Theory]

View file

@ -12,6 +12,172 @@ namespace PostIt.Tests;
public sealed class PodcastBroadcasterTests
{
[Theory]
[InlineData("stop")]
[InlineData("leave")]
[InlineData("logout")]
[InlineData("failure")]
[InlineData("broadcast")]
public Task Camera_can_be_previewed_without_creating_a_broadcast_and_is_released_before_next_capture(string action)
=> HeadlessUnitTestSession.GetOrStartForAssembly(typeof(PodcastBroadcasterTests).Assembly).Dispatch(async () =>
{
var path = Path.Combine(Path.GetTempPath(), $"postit-local-preview-{Guid.NewGuid():N}");
var previousDevices = Platform.GetPodcastCaptureDevices;
var previousPreview = Platform.CreatePodcastPreviewAsync;
var previousCapture = Platform.CreatePodcastCaptureAsync;
var previousPermissions = Platform.RequestPodcastPermissionsAsync;
var store = new TokenStore(path);
store.Save(new RefreshTokenRecord("access", "refresh", DateTimeOffset.UtcNow.AddHours(1)));
await using var api = new YavscApiClient(new Settings(path + ".settings"), store);
await using var transport = new Transport();
var preview = new PreviewCapture();
PodcastsPageViewModel? vm = null;
try
{
Platform.GetPodcastCaptureDevices = () => new([new("Camera", "camera")], [new("Mic", "microphone")]);
Platform.CreatePodcastPreviewAsync = (camera, _) =>
{
Assert.Equal("camera", camera);
return Task.FromResult<IPodcastCapture>(preview);
};
Platform.RequestPodcastPermissionsAsync = (_, _) => Task.CompletedTask;
Platform.CreatePodcastCaptureAsync = (_, microphone, directory, _) =>
{
Assert.True(preview.Disposed);
Assert.Equal("microphone", microphone);
return Task.FromResult<IPodcastCapture>(new FakeCapture(directory, new Border()));
};
var session = new SessionStatusViewModel { Api = api };
session.Refresh();
vm = new PodcastsPageViewModel(new PodcastApiClient(transport, () => "https://api.example/"), api, session);
vm.DetectDevicesCommand.Execute(null);
vm.Title = "";
vm.KeepScreenOnDuringCapture = true;
Assert.False(Platform.ScreenAwake.IsRequested);
Assert.True(vm.PreviewCommand.CanExecute(null));
Assert.False(vm.StartCommand.CanExecute(null));
await vm.PreviewCommand.ExecuteAsync(null);
Assert.True(vm.IsPreviewing);
Assert.True(Platform.ScreenAwake.IsRequested);
vm.KeepScreenOnDuringCapture = false;
Assert.False(Platform.ScreenAwake.IsRequested);
vm.KeepScreenOnDuringCapture = true;
Assert.True(Platform.ScreenAwake.IsRequested);
Assert.True(vm.IsCapturing);
Assert.False(vm.IsBroadcasting);
Assert.Same(preview.Preview, vm.CapturePreview);
Assert.False(vm.DetectDevicesCommand.CanExecute(null));
Assert.True(vm.StopPreviewCommand.CanExecute(null));
Assert.Equal(0, transport.CreateCount);
Assert.Empty(transport.Uploads);
var page = new PodcastsPage { DataContext = vm };
Assert.Same(preview.Preview, page.FindControl<ContentControl>("CapturePreviewHost")!.Content);
preview.OnDispose = () => Assert.Null(vm.CapturePreview);
switch (action)
{
case "stop": await vm.StopPreviewCommand.ExecuteAsync(null); break;
case "leave": await vm.DeactivateAsync(); break;
case "logout": await session.LogoutAsync(); break;
case "failure": preview.Fail(); break;
case "broadcast":
vm.Title = "Emission";
Assert.True(vm.StartCommand.CanExecute(null));
await vm.StartCommand.ExecuteAsync(null);
Assert.True(vm.IsBroadcasting);
Assert.True(Platform.ScreenAwake.IsRequested);
Assert.Equal(1, transport.CreateCount);
await vm.StopAsync();
break;
}
await WaitForUiAsync(() => preview.Disposed && !vm.IsPreviewing && !vm.IsBroadcasting);
Assert.True(preview.Disposed);
Assert.False(vm.IsPreviewing);
Assert.False(Platform.ScreenAwake.IsRequested);
Assert.Null(vm.CapturePreview);
if (action == "failure") Assert.Contains("Camera disconnected", vm.Status);
if (action != "broadcast") Assert.Equal(0, transport.CreateCount);
return true;
}
finally
{
if (vm is not null) await vm.DeactivateAsync();
Platform.GetPodcastCaptureDevices = previousDevices;
Platform.CreatePodcastPreviewAsync = previousPreview;
Platform.CreatePodcastCaptureAsync = previousCapture;
Platform.RequestPodcastPermissionsAsync = previousPermissions;
File.Delete(path);
File.Delete(path + ".settings");
}
}, TestContext.Current.CancellationToken);
[Fact]
public Task Leaving_the_page_during_preview_start_disposes_the_late_camera_without_showing_it()
=> HeadlessUnitTestSession.GetOrStartForAssembly(typeof(PodcastBroadcasterTests).Assembly).Dispatch(async () =>
{
var path = Path.Combine(Path.GetTempPath(), $"postit-preview-race-{Guid.NewGuid():N}");
var previous = Platform.CreatePodcastPreviewAsync;
var previousDevices = Platform.GetPodcastCaptureDevices;
var store = new TokenStore(path);
store.Save(new RefreshTokenRecord("access", "refresh", DateTimeOffset.UtcNow.AddHours(1)));
await using var api = new YavscApiClient(new Settings(path + ".settings"), store);
var preview = new PreviewCapture();
var pending = new TaskCompletionSource<IPodcastCapture>(TaskCreationOptions.RunContinuationsAsynchronously);
try
{
Platform.GetPodcastCaptureDevices = () => new([new("Camera", "camera")], []);
Platform.CreatePodcastPreviewAsync = (_, _) => pending.Task;
var session = new SessionStatusViewModel { Api = api };
session.Refresh();
var vm = new PodcastsPageViewModel(new PodcastApiClient(api, () => "https://api.example/"), api, session);
vm.DetectDevicesCommand.Execute(null);
var start = vm.PreviewCommand.ExecuteAsync(null);
var leave = vm.DeactivateAsync();
pending.SetResult(preview);
await WaitForUiAsync(() => start.IsCompleted && leave.IsCompleted);
await start;
await leave;
Assert.True(preview.Disposed);
Assert.Null(vm.CapturePreview);
Assert.False(vm.IsPreviewing);
return true;
}
finally
{
Platform.CreatePodcastPreviewAsync = previous;
Platform.GetPodcastCaptureDevices = previousDevices;
File.Delete(path);
File.Delete(path + ".settings");
}
}, TestContext.Current.CancellationToken);
private static async Task WaitForUiAsync(Func<bool> done)
{
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(TestContext.Current.CancellationToken);
timeout.CancelAfter(TimeSpan.FromSeconds(5));
while (!done())
{
Avalonia.Threading.Dispatcher.UIThread.RunJobs();
await Task.Delay(10, timeout.Token);
}
}
private sealed class PreviewCapture : IPodcastCapture
{
private readonly TaskCompletionSource _completion = new(TaskCreationOptions.RunContinuationsAsynchronously);
public Task Completion => _completion.Task;
public Control? Preview { get; } = new Border();
public bool Disposed { get; private set; }
public Action? OnDispose { get; set; }
public void Fail() => _completion.TrySetException(new IOException("Camera disconnected"));
public Task StopAsync() { _completion.TrySetResult(); return Task.CompletedTask; }
public async ValueTask DisposeAsync()
{
OnDispose?.Invoke();
await StopAsync();
Disposed = true;
}
}
[Fact]
public Task Shared_page_exposes_running_capture_preview_and_clears_it_before_disposal()
=> HeadlessUnitTestSession.GetOrStartForAssembly(typeof(PodcastBroadcasterTests).Assembly).Dispatch(async () =>

View file

@ -27,6 +27,8 @@ public sealed class PodcastPreferencesTests
vm.SelectedCamera = vm.Cameras[1];
vm.SelectedMicrophone = vm.Microphones[0];
vm.Title = "Mon emission habituelle";
Assert.False(vm.KeepScreenOnDuringCapture);
vm.KeepScreenOnDuringCapture = true;
vm.DetectDevicesCommand.Execute(null);
Assert.Equal("rear", vm.SelectedCamera?.Value);
Assert.Equal("", vm.SelectedMicrophone?.Value);
@ -38,6 +40,7 @@ public sealed class PodcastPreferencesTests
Assert.Equal("Mon emission habituelle", restored.PodcastDefaultTitle);
Assert.Equal("rear", restored.PodcastCameraId);
Assert.Equal("", restored.PodcastMicrophoneId);
Assert.True(restored.PodcastKeepScreenOn);
Platform.GetPodcastCaptureDevices = () => throw new InvalidOperationException("Must use saved devices.");
await using var otherApi = new PreferencesApi(restored, new TokenStore(path + ".tokens"));
var other = new PodcastsPageViewModel(new PodcastApiClient(otherApi, () => restored.ApiUrl), otherApi, session);
@ -46,11 +49,14 @@ public sealed class PodcastPreferencesTests
Assert.Equal("rear", other.SelectedCamera?.Value);
Assert.Equal("", other.SelectedMicrophone?.Value);
Assert.Equal(vm.Title, other.Title);
Assert.True(other.KeepScreenOnDuringCapture);
restored.PodcastCameraId = "front";
restored.PodcastMicrophoneId = "usb";
restored.PodcastKeepScreenOn = false;
await other.ActivateAsync();
Assert.Equal("front", other.SelectedCamera?.Value);
Assert.Equal("usb", other.SelectedMicrophone?.Value);
Assert.False(other.KeepScreenOnDuringCapture);
Platform.GetPodcastCaptureDevices = () => new([], []);
other.DetectDevicesCommand.Execute(null);

View file

@ -0,0 +1,23 @@
using PostIt.Services;
namespace PostIt.Tests;
public sealed class ScreenAwakeRequestsTests
{
[Fact]
public void Independent_requests_keep_the_screen_awake_until_all_are_released()
{
var requests = new ScreenAwakeRequests();
var states = new List<bool>();
requests.Changed += () => states.Add(requests.IsRequested);
Assert.False(requests.IsRequested);
var playback = requests.Acquire();
var capture = requests.Acquire();
playback.Dispose();
Assert.True(requests.IsRequested);
playback.Dispose();
capture.Dispose();
Assert.False(requests.IsRequested);
Assert.Equal(new[] { true, true, true, false }, states);
}
}