From 85f2c9ca7758e5c6f98ed70755691432b98bcd97 Mon Sep 17 00:00:00 2001 From: Daniel Sierpinski Date: Tue, 1 Dec 2026 16:02:45 +0100 Subject: [PATCH] Fix mirrored Android background masks after a flipped readback. Undo the post-readback Y flip before upload so a rotated portrait mask lines up with the camera. Co-authored-by: Cursor --- .../AndroidMlKitPersonSegmenter.cs | 182 +++++++++++++++++- .../PersonMaskOrientation.cs | 26 ++- .../Editor/PersonMaskOrientationTests.cs | 38 ++++ 3 files changed, 233 insertions(+), 13 deletions(-) diff --git a/Packages/StreamVideo/Runtime/Core/BackgroundFilters/AndroidMlKitPersonSegmenter.cs b/Packages/StreamVideo/Runtime/Core/BackgroundFilters/AndroidMlKitPersonSegmenter.cs index d5c60ec8..8467b577 100644 --- a/Packages/StreamVideo/Runtime/Core/BackgroundFilters/AndroidMlKitPersonSegmenter.cs +++ b/Packages/StreamVideo/Runtime/Core/BackgroundFilters/AndroidMlKitPersonSegmenter.cs @@ -16,8 +16,8 @@ namespace StreamVideo.Core.BackgroundFilters /// Input is scaled so the short side is (ML Kit's 256px floor) while /// keeping the camera aspect. The downscaled buffer is rotated upright for ML Kit, then the mask /// is rotated back so compositor UVs match WebCamTexture space. - /// Vulkan AsyncGPUReadback is Y-flipped once into the GLES/Bitmap y-down layout; GLES is not - /// flipped. Mask upload does not flip again. + /// Vulkan AsyncGPUReadback is Y-flipped once into the GLES/Bitmap y-down layout and the mask is + /// flipped back before upload; GLES is not flipped. /// only checks the ML Kit classpath. Segmentation.getClient /// runs on the first / . /// is non-blocking: an in-flight Java process releases its own resources @@ -90,6 +90,9 @@ public void RequestSegmentation(Texture source) _readbackCallback = CreateReadbackCallback(); } +#if STREAM_DEBUG_ENABLED && STREAM_LOG_BG_FILTER + _latency.OnReadbackRequested(); +#endif try { AsyncGPUReadback.Request(_downscaleRt, 0, TextureFormat.RGBA32, _readbackCallback); @@ -117,6 +120,9 @@ public void Pause() // A late callback from before the pause must not upload or clear a newer request's flag. _readbackCallback = null; _hasPendingRgba = false; +#if STREAM_DEBUG_ENABLED && STREAM_LOG_BG_FILTER + _latency.Reset(); +#endif #endif } @@ -181,9 +187,12 @@ public void PumpPendingMask() if (maskBytes != null && width > 0 && height > 0) { var packed = ToByteArray(maskBytes); - var webcamMask = PersonMaskOrientation.UnrotateClockwise(packed, width, height, 1, rotation, - out var webcamWidth, out var webcamHeight); + var webcamMask = PersonMaskOrientation.ToReadbackLayout(packed, width, height, rotation, + _submittedYFlipped, out var webcamWidth, out var webcamHeight); UploadMask(webcamMask, webcamWidth, webcamHeight); +#if STREAM_DEBUG_ENABLED && STREAM_LOG_BG_FILTER + _latency.OnMaskUploaded(_native.Call("isBusy")); +#endif } TrySubmitPending(); @@ -215,7 +224,12 @@ public void PumpPendingMask() private int _pendingWidth; private int _pendingHeight; private int _pendingRotation; + private bool _pendingYFlipped; private bool _hasPendingRgba; + private bool _submittedYFlipped; +#if STREAM_DEBUG_ENABLED && STREAM_LOG_BG_FILTER + private readonly MaskLatencyStats _latency = new MaskLatencyStats(); +#endif #endif private AndroidMlKitPersonSegmenter(ILogs logs) @@ -359,14 +373,18 @@ private void OnReadback(AsyncGPUReadbackRequest request, Action 0 && _pendingRgba.Length >= packedBytes - && PersonMaskOrientation.NeedsAsyncGpuReadbackYFlip(SystemInfo.graphicsUVStartsAtTop, isOpenGles)) + _pendingYFlipped = packedBytes > 0 && _pendingRgba.Length >= packedBytes + && PersonMaskOrientation.NeedsAsyncGpuReadbackYFlip(SystemInfo.graphicsUVStartsAtTop, isOpenGles); + if (_pendingYFlipped) { PersonMaskOrientation.FlipVertical(_pendingRgba, _pendingWidth, _pendingHeight, 4); } _pendingRotation = _lastSourceRotation; _hasPendingRgba = true; +#if STREAM_DEBUG_ENABLED && STREAM_LOG_BG_FILTER + _latency.OnReadbackCompleted(); +#endif TrySubmitPending(); } @@ -382,8 +400,11 @@ private void TrySubmitPending() return; } - SubmitRgba(_pendingRgba, _pendingWidth, _pendingHeight, _pendingRotation); + SubmitRgba(_pendingRgba, _pendingWidth, _pendingHeight, _pendingRotation, _pendingYFlipped); _hasPendingRgba = false; +#if STREAM_DEBUG_ENABLED && STREAM_LOG_BG_FILTER + _latency.OnSubmitted(); +#endif } private void ReadbackSynchronouslyAndProcess() @@ -408,16 +429,18 @@ private void ReadbackSynchronouslyAndProcess() RenderTexture.active = prev; // ReadPixels stores Texture2D bottom-up on every API; do not Y-flip this path. - SubmitRgba(_syncReadbackTexture.GetRawTextureData(), width, height, _lastSourceRotation); + SubmitRgba(_syncReadbackTexture.GetRawTextureData(), width, height, _lastSourceRotation, false); } - private void SubmitRgba(byte[] rgba, int width, int height, int rotationDegrees) + private void SubmitRgba(byte[] rgba, int width, int height, int rotationDegrees, bool yFlipped) { if (_disposed || rgba == null || _native == null) { return; } + _submittedYFlipped = yFlipped; + var rotation = PersonMaskOrientation.NormalizeClockwiseDegrees(rotationDegrees); var submitRgba = rgba; var submitWidth = width; @@ -487,7 +510,6 @@ private void UploadMask(byte[] mask, int width, int height) _maskTexture.SetPixelData(mask, 0); _maskTexture.Apply(false, false); _hasMask = true; - // Mask bytes stay in the GLES y-down layout (Vulkan readback was already flipped). #if STREAM_DEBUG_ENABLED && STREAM_LOG_BG_FILTER var hits = 0; @@ -672,5 +694,145 @@ private void DestroyTexture(ref Texture2D texture) texture = null; } + +#if UNITY_ANDROID && !UNITY_EDITOR && STREAM_DEBUG_ENABLED && STREAM_LOG_BG_FILTER + /// + /// Mask age = camera frame read for segmentation until its mask is uploaded. Split into readback, + /// waiting for ML Kit to be free, and ML Kit processing (includes up to one Unity frame of pickup). + /// Logs averages and maxima every . Grep logcat for BgFilterLatency. + /// + private sealed class MaskLatencyStats + { + public void OnReadbackRequested() => _requestTime = Now; + + public void OnReadbackCompleted() + { + var now = Now; + _pendingCaptureTime = _requestTime; + _pendingReadyTime = now; + _readback.Add(now - _requestTime); + } + + public void OnSubmitted() + { + _previous = _last; + _last = new Submission(_pendingCaptureTime, _pendingReadyTime, Now); + } + + /// A newer frame was submitted before this mask was picked up, + /// so the mask belongs to the previous submission. + public void OnMaskUploaded(bool nativeBusy) + { + var submission = nativeBusy ? _previous : _last; + if (!submission.IsValid) + { + return; + } + + var now = Now; + _age.Add(now - submission.CaptureTime); + _queued.Add(submission.SubmitTime - submission.ReadyTime); + _mlKit.Add(now - submission.SubmitTime); + + if (_windowStart <= 0) + { + _windowStart = now; + _windowStartFrame = Time.frameCount; + return; + } + + var window = now - _windowStart; + if (window < WindowSeconds) + { + return; + } + + var line = "[BgFilterLatency] masksPerSec=" + (_age.Count / window).ToString("0.0") + + " unityFps=" + ((Time.frameCount - _windowStartFrame) / window).ToString("0.0") + + " | ms avg/max: age=" + _age + " readback=" + _readback + " waitForMlKit=" + _queued + + " mlKit=" + _mlKit + + " | " + SystemInfo.graphicsDeviceType; + Debug.LogFormat(LogType.Warning, LogOption.NoStacktrace, null, "{0}", line); + + _age.Clear(); + _readback.Clear(); + _queued.Clear(); + _mlKit.Clear(); + _windowStart = now; + _windowStartFrame = Time.frameCount; + } + + public void Reset() + { + _last = default; + _previous = default; + _windowStart = 0; + _age.Clear(); + _readback.Clear(); + _queued.Clear(); + _mlKit.Clear(); + } + + private const double WindowSeconds = 2.0; + + private readonly Metric _age = new Metric(); + private readonly Metric _readback = new Metric(); + private readonly Metric _queued = new Metric(); + private readonly Metric _mlKit = new Metric(); + + private double _requestTime; + private double _pendingCaptureTime; + private double _pendingReadyTime; + private Submission _last; + private Submission _previous; + private double _windowStart; + private int _windowStartFrame; + + private static double Now => Time.realtimeSinceStartupAsDouble; + + private readonly struct Submission + { + public readonly double CaptureTime; + public readonly double ReadyTime; + public readonly double SubmitTime; + + public bool IsValid => SubmitTime > 0; + + public Submission(double captureTime, double readyTime, double submitTime) + { + CaptureTime = captureTime; + ReadyTime = readyTime; + SubmitTime = submitTime; + } + } + + private sealed class Metric + { + public int Count { get; private set; } + + public void Add(double seconds) + { + Count++; + _sum += seconds; + _max = Math.Max(_max, seconds); + } + + public void Clear() + { + Count = 0; + _sum = 0; + _max = 0; + } + + public override string ToString() + => Count == 0 + ? "n/a" + : (_sum / Count * 1000).ToString("0") + "/" + (_max * 1000).ToString("0"); + + private double _sum; + private double _max; + } + } +#endif } } diff --git a/Packages/StreamVideo/Runtime/Core/BackgroundFilters/PersonMaskOrientation.cs b/Packages/StreamVideo/Runtime/Core/BackgroundFilters/PersonMaskOrientation.cs index e0ee510f..f660bfc4 100644 --- a/Packages/StreamVideo/Runtime/Core/BackgroundFilters/PersonMaskOrientation.cs +++ b/Packages/StreamVideo/Runtime/Core/BackgroundFilters/PersonMaskOrientation.cs @@ -6,8 +6,8 @@ namespace StreamVideo.Core.BackgroundFilters /// Clockwise pixel-buffer rotation for native segmenter input and inverse mapping of the /// mask back to WebCamTexture UV space. Uses row-major layout with y increasing /// downward (Android Bitmap / GLES GPU readback). Vulkan and Metal AsyncGPUReadback are - /// flipped into this layout once. iOS Metal flips again on Texture2D upload so the mask - /// matches a regular 2D WebCamTexture; Android GLES does not. + /// flipped into this layout once and flipped back before the mask is uploaded + /// ( on Android, on iOS). /// internal static class PersonMaskOrientation { @@ -66,6 +66,26 @@ public static byte[] UnrotateClockwise(byte[] source, int width, int height, int return RotateClockwise(source, width, height, bytesPerPixel, inverse, out destWidth, out destHeight); } + /// + /// Maps an R8 mask computed from a rotated (and optionally Y-flipped) readback buffer back into + /// the readback layout, which matches Texture2D.SetPixelData on the same graphics API. + /// Every flip applied after readback must be undone here, otherwise the mask is mirrored against + /// the camera image (left/right after a 90° portrait rotation). May modify and return + /// . + /// + public static byte[] ToReadbackLayout(byte[] mask, int width, int height, int degreesClockwise, + bool readbackWasYFlipped, out int destWidth, out int destHeight) + { + var unrotated = UnrotateClockwise(mask, width, height, 1, degreesClockwise, out destWidth, + out destHeight); + if (unrotated != null && readbackWasYFlipped) + { + FlipVertical(unrotated, destWidth, destHeight, 1); + } + + return unrotated; + } + public static void RotateClockwise(byte[] source, int width, int height, int bytesPerPixel, int degreesClockwise, byte[] dest) { @@ -137,7 +157,7 @@ public static bool NeedsAsyncGpuReadbackYFlip(bool graphicsUvStartsAtTop, bool i /// /// Bitmap y-down row 0 is the top of the image. Texture2D.SetPixelData row 0 /// is the bottom. GLES OES WebCamTexture sampling matches y-down bytes in a - /// Texture2D, so Android does not flip on upload. iOS Metal WebCamTexture is a + /// Texture2D. Android uses instead. iOS Metal WebCamTexture is a /// regular 2D texture (UV y=0 = bottom), so the mask must be flipped on upload. /// Without that, a vertical mismatch in sensor space shows up as a left/right shift /// after a 90° portrait preview rotation and only lines up when the head is centered. diff --git a/Packages/StreamVideo/Tests/Editor/PersonMaskOrientationTests.cs b/Packages/StreamVideo/Tests/Editor/PersonMaskOrientationTests.cs index 6a0a9417..042c8108 100644 --- a/Packages/StreamVideo/Tests/Editor/PersonMaskOrientationTests.cs +++ b/Packages/StreamVideo/Tests/Editor/PersonMaskOrientationTests.cs @@ -75,6 +75,44 @@ public void When_mask_flipped_vertically_expect_rows_reversed() "Flipping twice must restore the original bytes."); } + [TestCase(0, false)] + [TestCase(90, false)] + [TestCase(180, false)] + [TestCase(270, false)] + [TestCase(0, true)] + [TestCase(90, true)] + [TestCase(180, true)] + [TestCase(270, true)] + public void When_mask_mapped_back_to_readback_layout_expect_it_lines_up_with_readback(int rotation, + bool readbackWasYFlipped) + { + // 3x2 readback, unique values. The fake segmenter returns its input, so the mapped mask must + // equal the readback byte for byte. + var readback = new byte[] { 10, 20, 30, 40, 50, 60 }; + const int width = 3; + const int height = 2; + + var input = (byte[])readback.Clone(); + if (readbackWasYFlipped) + { + PersonMaskOrientation.FlipVertical(input, width, height, 1); + } + + var segmenterInput = PersonMaskOrientation.RotateClockwise(input, width, height, 1, rotation, + out var inputWidth, out var inputHeight); + var mask = (byte[])segmenterInput.Clone(); + + var mapped = PersonMaskOrientation.ToReadbackLayout(mask, inputWidth, inputHeight, rotation, + readbackWasYFlipped, out var mappedWidth, out var mappedHeight); + + Assert.That(mappedWidth, Is.EqualTo(width), + "Mapped mask width must match the readback so compositor UVs line up."); + Assert.That(mappedHeight, Is.EqualTo(height), + "Mapped mask height must match the readback so compositor UVs line up."); + Assert.That(mapped, Is.EqualTo(readback), + "Mask must undo both the rotation and the readback Y-flip, otherwise it is mirrored against the camera."); + } + [Test] public void When_async_readback_on_gles_expect_no_y_flip() {