From 364d65217d6707130f3bc9604f7be975095234fb Mon Sep 17 00:00:00 2001 From: Daniel Sierpinski Date: Fri, 4 Dec 2026 11:17:40 +0100 Subject: [PATCH 1/2] Fix the Android blur cutout sticking on the first person. ML Kit was given a bottom-up camera buffer and a reused bitmap, so STREAM_MODE kept the first mask. Flip the buffer before rotation and submit a new bitmap per frame. Co-authored-by: Cursor --- .../AndroidMlKitPersonSegmenter.cs | 448 ++++++++++++++---- .../Core/BackgroundFilters/MaskFrameScale.cs | 59 +++ .../BackgroundFilters/MaskFrameScale.cs.meta | 11 + .../UnityMlKitPersonSegmenter.java | 57 ++- .../Tests/Editor/BackgroundCompositorTests.cs | 118 +++++ .../Tests/Editor/MaskFrameScaleTests.cs | 31 ++ .../Tests/Editor/MaskFrameScaleTests.cs.meta | 11 + .../Editor/PersonMaskOrientationTests.cs | 87 ++++ 8 files changed, 702 insertions(+), 120 deletions(-) create mode 100644 Packages/StreamVideo/Runtime/Core/BackgroundFilters/MaskFrameScale.cs create mode 100644 Packages/StreamVideo/Runtime/Core/BackgroundFilters/MaskFrameScale.cs.meta create mode 100644 Packages/StreamVideo/Tests/Editor/MaskFrameScaleTests.cs create mode 100644 Packages/StreamVideo/Tests/Editor/MaskFrameScaleTests.cs.meta diff --git a/Packages/StreamVideo/Runtime/Core/BackgroundFilters/AndroidMlKitPersonSegmenter.cs b/Packages/StreamVideo/Runtime/Core/BackgroundFilters/AndroidMlKitPersonSegmenter.cs index d5c60ec8..75e25f0b 100644 --- a/Packages/StreamVideo/Runtime/Core/BackgroundFilters/AndroidMlKitPersonSegmenter.cs +++ b/Packages/StreamVideo/Runtime/Core/BackgroundFilters/AndroidMlKitPersonSegmenter.cs @@ -2,22 +2,27 @@ using StreamVideo.Libs.Logs; using UnityEngine; #if UNITY_ANDROID && !UNITY_EDITOR -using UnityEngine.Rendering; +using UnityEngine.Experimental.Rendering; #endif using Object = UnityEngine.Object; namespace StreamVideo.Core.BackgroundFilters { /// - /// Android ML Kit selfie segmenter. Async process, last-mask reuse, downscaled input via AsyncGPUReadback. - /// GPU readback is pipelined with ML Kit: a new camera frame is read while the previous - /// processAsync is in flight, then submitted as soon as the segmenter is free. - /// Does not block OnUpdate and does not ReadPixels the publish texture. + /// Android ML Kit selfie segmenter. Async process, last-mask reuse. + /// The camera copy is a ReadPixels of a linear downscale, taken only when ML Kit is free. + /// AsyncGPUReadback of that target kept completing while the cutout stayed on the first person. + /// If that GPU copy is bit-identical for a while and WebCamTexture.GetPixels32 is not, + /// later frames come from the CPU buffer instead. Each submitted frame is a new Android bitmap. + /// The mask texture is reused. With STREAM_DEBUG_ENABLED and STREAM_LOG_BG_FILTER, + /// a log every two seconds reports whether the camera bytes and the mask bytes are changing. + /// Does not ReadPixels the publish texture. /// 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. + /// ReadPixels and GetPixels32 are bottom-up. Rotation treats row 0 as the top, matching + /// an Android bitmap, so those bytes are flipped before they are rotated upright. The mask is + /// flipped back before Texture2D.SetPixelData, where row 0 is the bottom. /// only checks the ML Kit classpath. Segmentation.getClient /// runs on the first / . /// is non-blocking: an in-flight Java process releases its own resources @@ -55,7 +60,7 @@ public static bool TryCreate(ILogs logs, out AndroidMlKitPersonSegmenter segment public void RequestSegmentation(Texture source) { - if (_disposed || _paused || source == null || _readbackInFlight || !EnsureCreated()) + if (_disposed || _paused || source == null || !EnsureCreated()) { return; } @@ -66,7 +71,21 @@ public void RequestSegmentation(Texture source) return; } - // Pipeline GPU readback with ML Kit so mask latency is max(readback, process), not the sum. +#if STREAM_DEBUG_ENABLED && STREAM_LOG_BG_FILTER + _lastSource = source; +#endif + if (_useCpuCamera && TrySubmitWebCamCpu(source as WebCamTexture)) + { + return; + } + + // ML Kit is the slow part. Copy the camera only when it can accept a frame, + // so ReadPixels does not flush the GPU on frames that would be dropped. + if (_native.Call("isBusy")) + { + return; + } + EnsureDownscaleRt(source); if (_downscaleRt == null) { @@ -74,50 +93,18 @@ public void RequestSegmentation(Texture source) } Graphics.Blit(source, _downscaleRt); -#if STREAM_DEBUG_ENABLED && STREAM_LOG_BG_FILTER - _lastSource = source; -#endif _lastSourceRotation = GetSourceRotationDegrees(source); #if STREAM_DEBUG_ENABLED && STREAM_LOG_BG_FILTER LogSubmitOrientation(source); #endif - - if (SystemInfo.supportsAsyncGPUReadback) - { - _readbackInFlight = true; - if (_readbackCallback == null) - { - _readbackCallback = CreateReadbackCallback(); - } - - try - { - AsyncGPUReadback.Request(_downscaleRt, 0, TextureFormat.RGBA32, _readbackCallback); - } - catch (Exception e) - { - _readbackInFlight = false; - _logs?.Warning("Background filter: mask input readback request failed: " + e.Message); - } - - return; - } - - // Last-resort: downscaled input only (never the publish RT). ReadbackSynchronouslyAndProcess(); + TryPromoteCpuCamera(source); #endif } public void Pause() { _paused = true; - // Suspended GPU readbacks may never callback; do not block Resume. - _readbackInFlight = false; -#if UNITY_ANDROID && !UNITY_EDITOR - // A late callback from before the pause must not upload or clear a newer request's flag. - _readbackCallback = null; - _hasPendingRgba = false; -#endif } public void Resume() @@ -128,6 +115,9 @@ public void Resume() } _paused = false; +#if UNITY_ANDROID && !UNITY_EDITOR && STREAM_DEBUG_ENABLED && STREAM_LOG_BG_FILTER + _nextPipelineLogAt = 0f; +#endif } public void Dispose() @@ -155,10 +145,14 @@ public void Dispose() public void ReleaseResources() { #if UNITY_ANDROID && !UNITY_EDITOR - _hasPendingRgba = false; - _pendingRgba = null; _uprightRgba = null; + _yDownRgba = null; _rgbaSbytes = null; + _cpuRgba = null; + _cpuPixels = null; + _useCpuCamera = false; + _hasInputHash = false; + _identicalInputStreak = 0; DestroyTexture(ref _syncReadbackTexture); #endif _hasMask = false; @@ -183,10 +177,14 @@ public void PumpPendingMask() var packed = ToByteArray(maskBytes); var webcamMask = PersonMaskOrientation.UnrotateClockwise(packed, width, height, 1, rotation, out var webcamWidth, out var webcamHeight); + // ML Kit's bitmap is y-down. SetPixelData is bottom-up, matching the camera texture. + PersonMaskOrientation.FlipVertical(webcamMask, webcamWidth, webcamHeight, 1); UploadMask(webcamMask, webcamWidth, webcamHeight); } - TrySubmitPending(); +#if STREAM_DEBUG_ENABLED && STREAM_LOG_BG_FILTER + LogPipelineHeartbeat(); +#endif #endif } @@ -197,25 +195,48 @@ public void PumpPendingMask() private bool _paused; private bool _hasMask; private bool _isSupported = true; - private bool _readbackInFlight; private Texture2D _maskTexture; private RenderTexture _downscaleRt; private int _lastSourceRotation; #if UNITY_ANDROID && !UNITY_EDITOR + private const int IdenticalFramePromoteInterval = 12; + private static readonly GraphicsFormat MaskInputFormat = GraphicsFormat.R8G8B8A8_UNorm; + + private int _lastInputHash; + private bool _hasInputHash; + private int _identicalInputStreak; + private bool _useCpuCamera; #if STREAM_DEBUG_ENABLED && STREAM_LOG_BG_FILTER + private const float PipelineLogIntervalSeconds = 2f; + + private float _nextPipelineLogAt; + private int _readbacksCompleted; + private int _masksUploaded; + private int _readbacksLogged; + private int _masksLogged; + private int _inputChanges; + private int _inputChangesLogged; + private int _maskChanges; + private int _maskChangesLogged; + private int _lastMaskHash; + private bool _hasMaskHash; + private int _lastCentroidX = -1; + private int _lastCentroidY = -1; + private int _centroidMinX; + private int _centroidMaxX; + private int _centroidMinY; + private int _centroidMaxY; + private bool _hasCentroidSpan; private Texture _lastSource; #endif private bool _createAttempted; private AndroidJavaObject _native; - private Action _readbackCallback; private Texture2D _syncReadbackTexture; private sbyte[] _rgbaSbytes; - private byte[] _pendingRgba; private byte[] _uprightRgba; - private int _pendingWidth; - private int _pendingHeight; - private int _pendingRotation; - private bool _hasPendingRgba; + private byte[] _yDownRgba; + private byte[] _cpuRgba; + private Color32[] _cpuPixels; #endif private AndroidMlKitPersonSegmenter(ILogs logs) @@ -315,75 +336,94 @@ private static AndroidJavaObject CreateNative() return new AndroidJavaObject(JavaClass); } - /// - /// Reused for every request until drops it, so a stale callback is detected by identity - /// without allocating per readback. - /// - private Action CreateReadbackCallback() + private bool TrySubmitWebCamCpu(WebCamTexture webcam) { - Action callback = null; - callback = request => OnReadback(request, callback); - return callback; + if (webcam == null) + { + return false; + } + + if (_native.Call("isBusy")) + { + return true; + } + + if (!TryCopyWebCam(webcam, out var rgba, out var width, out var height)) + { + return false; + } + + _lastSourceRotation = GetSourceRotationDegrees(webcam); +#if STREAM_DEBUG_ENABLED && STREAM_LOG_BG_FILTER + _readbacksCompleted++; +#endif + NoteInput(rgba, width * height * 4); + SubmitRgba(CopyAsYDown(rgba, width, height), width, height, _lastSourceRotation); + return true; } - private void OnReadback(AsyncGPUReadbackRequest request, Action callback) + private void TryPromoteCpuCamera(Texture source) { - if (callback != _readbackCallback) + if (_useCpuCamera || _identicalInputStreak < IdenticalFramePromoteInterval + || _identicalInputStreak % IdenticalFramePromoteInterval != 0) { return; } - _readbackInFlight = false; - - if (_disposed || _paused || _native == null) + var webcam = source as WebCamTexture; + if (!TryCopyWebCam(webcam, out var rgba, out var width, out var height)) { return; } - if (request.hasError) + var cpuHash = HashSample(rgba, width * height * 4); + if (cpuHash == _lastInputHash) { - _logs?.Warning("Background filter: mask input readback failed."); return; } - var data = request.GetData(); - var length = data.Length; - if (_pendingRgba == null || _pendingRgba.Length != length) + _useCpuCamera = true; + _logs?.Warning( + "Background filter: GPU camera copy is stuck; reading WebCamTexture pixels on the CPU. gfx=" + + SystemInfo.graphicsDeviceType); + } + + private bool TryCopyWebCam(WebCamTexture webcam, out byte[] rgba, out int width, out int height) + { + rgba = null; + width = 0; + height = 0; + if (webcam == null || !webcam.isReadable || webcam.width < 2 || webcam.height < 2) { - _pendingRgba = new byte[length]; + return false; } - data.CopyTo(_pendingRgba); - _pendingWidth = request.width; - _pendingHeight = request.height; - var packedBytes = _pendingWidth * _pendingHeight * 4; - var isOpenGles = SystemInfo.graphicsDeviceType == GraphicsDeviceType.OpenGLES2 - || SystemInfo.graphicsDeviceType == GraphicsDeviceType.OpenGLES3; - if (packedBytes > 0 && _pendingRgba.Length >= packedBytes - && PersonMaskOrientation.NeedsAsyncGpuReadbackYFlip(SystemInfo.graphicsUVStartsAtTop, isOpenGles)) + var count = webcam.width * webcam.height; + if (_cpuPixels == null || _cpuPixels.Length != count) { - PersonMaskOrientation.FlipVertical(_pendingRgba, _pendingWidth, _pendingHeight, 4); + _cpuPixels = new Color32[count]; } - _pendingRotation = _lastSourceRotation; - _hasPendingRgba = true; - TrySubmitPending(); - } - - private void TrySubmitPending() - { - if (_disposed || !_hasPendingRgba || _paused || _native == null) + try { - return; + _cpuPixels = webcam.GetPixels32(_cpuPixels); + } + catch (Exception e) + { + _logs?.Warning("Background filter: failed to read WebCamTexture pixels: " + e.Message); + return false; } - if (_native.Call("isBusy")) + GetMaskInputSize(webcam.width, webcam.height, out width, out height); + var needed = width * height * 4; + if (_cpuRgba == null || _cpuRgba.Length < needed) { - return; + _cpuRgba = new byte[needed]; } - SubmitRgba(_pendingRgba, _pendingWidth, _pendingHeight, _pendingRotation); - _hasPendingRgba = false; + MaskFrameScale.DownscaleNearest(_cpuPixels, webcam.width, webcam.height, _cpuRgba, width, height); + rgba = _cpuRgba; + return true; } private void ReadbackSynchronouslyAndProcess() @@ -407,8 +447,13 @@ private void ReadbackSynchronouslyAndProcess() _syncReadbackTexture.Apply(false, false); RenderTexture.active = prev; - // ReadPixels stores Texture2D bottom-up on every API; do not Y-flip this path. - SubmitRgba(_syncReadbackTexture.GetRawTextureData(), width, height, _lastSourceRotation); + // ReadPixels is bottom-up. Rotation and the Android bitmap treat row 0 as the top. + var rgba = _syncReadbackTexture.GetRawTextureData(); +#if STREAM_DEBUG_ENABLED && STREAM_LOG_BG_FILTER + _readbacksCompleted++; +#endif + NoteInput(rgba, width * height * 4); + SubmitRgba(CopyAsYDown(rgba, width, height), width, height, _lastSourceRotation); } private void SubmitRgba(byte[] rgba, int width, int height, int rotationDegrees) @@ -462,6 +507,23 @@ private static int GetSourceRotationDegrees(Texture source) return PersonMaskOrientation.NormalizeClockwiseDegrees(webcam.videoRotationAngle); } + /// + /// has row 0 at the bottom, like ReadPixels and + /// GetPixels32. The copy has row 0 at the top so clockwise rotation matches the bitmap. + /// + private byte[] CopyAsYDown(byte[] bottomUp, int width, int height) + { + var needed = width * height * 4; + if (_yDownRgba == null || _yDownRgba.Length < needed) + { + _yDownRgba = new byte[needed]; + } + + Buffer.BlockCopy(bottomUp, 0, _yDownRgba, 0, needed); + PersonMaskOrientation.FlipVertical(_yDownRgba, width, height, 4); + return _yDownRgba; + } + private void UploadMask(byte[] mask, int width, int height) { if (_disposed || mask == null || mask.Length < width * height) @@ -484,12 +546,13 @@ private void UploadMask(byte[] mask, int width, int height) }; } + // Caller flipped the y-down mask so row 0 is the bottom of the camera texture. _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 + _masksUploaded++; + NoteMask(mask, width, height); var hits = 0; var needed = width * height; for (var i = 0; i < needed; i++) @@ -511,6 +574,178 @@ private void UploadMask(byte[] mask, int width, int height) #endif } +#if STREAM_DEBUG_ENABLED && STREAM_LOG_BG_FILTER + private void LogPipelineHeartbeat() + { + var now = Time.realtimeSinceStartup; + if (_nextPipelineLogAt <= 0f) + { + _nextPipelineLogAt = now + PipelineLogIntervalSeconds; + return; + } + + if (now < _nextPipelineLogAt) + { + return; + } + + _nextPipelineLogAt = now + PipelineLogIntervalSeconds; + var readbacks = _readbacksCompleted - _readbacksLogged; + var masks = _masksUploaded - _masksLogged; + var inputChanged = _inputChanges - _inputChangesLogged; + var maskChanged = _maskChanges - _maskChangesLogged; + var spanX = _hasCentroidSpan ? _centroidMaxX - _centroidMinX : 0; + var spanY = _hasCentroidSpan ? _centroidMaxY - _centroidMinY : 0; + var status = string.Empty; + if (readbacks == 0) + { + status = " readback stopped"; + } + else if (inputChanged == 0) + { + status = " camera frame unchanged"; + } + else if (masks == 0) + { + status = " ML Kit stopped"; + } + else if (maskChanged == 0) + { + status = " mask unchanged"; + } + + _logs?.Info("Background filter: gfx=" + SystemInfo.graphicsDeviceType + + " cpuCamera=" + _useCpuCamera + + " readbacks completed=" + readbacks + + " masks uploaded=" + masks + + " inputChanged=" + inputChanged + + " maskChanged=" + maskChanged + + " rot=" + _lastSourceRotation + + " centroid=" + _lastCentroidX + "," + _lastCentroidY + + " centroidSpan=" + spanX + "," + spanY + + " (total " + _readbacksCompleted + "/" + _masksUploaded + ")" + + status); + _readbacksLogged = _readbacksCompleted; + _masksLogged = _masksUploaded; + _inputChangesLogged = _inputChanges; + _maskChangesLogged = _maskChanges; + _hasCentroidSpan = false; + } +#endif + + private void NoteInput(byte[] rgba, int length) + { + var hash = HashSample(rgba, length); + if (_hasInputHash) + { + if (hash == _lastInputHash) + { + _identicalInputStreak++; + } + else + { + _identicalInputStreak = 0; +#if STREAM_DEBUG_ENABLED && STREAM_LOG_BG_FILTER + _inputChanges++; +#endif + } + } + + _lastInputHash = hash; + _hasInputHash = true; + } + +#if STREAM_DEBUG_ENABLED && STREAM_LOG_BG_FILTER + private void NoteMask(byte[] mask, int width, int height) + { + var hash = HashSample(mask, width * height); + if (_hasMaskHash && hash != _lastMaskHash) + { + _maskChanges++; + } + + _lastMaskHash = hash; + _hasMaskHash = true; + + long sumX = 0; + long sumY = 0; + var hits = 0; + var count = width * height; + for (var i = 0; i < count; i++) + { + if (mask[i] <= 128) + { + continue; + } + + sumX += i % width; + sumY += i / width; + hits++; + } + + if (hits == 0) + { + _lastCentroidX = -1; + _lastCentroidY = -1; + return; + } + + _lastCentroidX = (int)(sumX / hits); + _lastCentroidY = (int)(sumY / hits); + if (!_hasCentroidSpan) + { + _centroidMinX = _centroidMaxX = _lastCentroidX; + _centroidMinY = _centroidMaxY = _lastCentroidY; + _hasCentroidSpan = true; + return; + } + + if (_lastCentroidX < _centroidMinX) + { + _centroidMinX = _lastCentroidX; + } + + if (_lastCentroidX > _centroidMaxX) + { + _centroidMaxX = _lastCentroidX; + } + + if (_lastCentroidY < _centroidMinY) + { + _centroidMinY = _lastCentroidY; + } + + if (_lastCentroidY > _centroidMaxY) + { + _centroidMaxY = _lastCentroidY; + } + } +#endif + + private static int HashSample(byte[] data, int length) + { + if (data == null || length <= 0) + { + return 0; + } + + if (length > data.Length) + { + length = data.Length; + } + + unchecked + { + var hash = 2166136261; + for (var i = 0; i < length; i++) + { + hash = (hash ^ data[i]) * 16777619; + } + + return (int)hash; + } + } + private static byte[] ToByteArray(sbyte[] source) { if (source == null) @@ -547,7 +782,8 @@ private void EnsureDownscaleRt(Texture source) } GetMaskInputSize(source.width, source.height, out var width, out var height); - if (_downscaleRt != null && _downscaleRt.width == width && _downscaleRt.height == height) + if (_downscaleRt != null && _downscaleRt.width == width && _downscaleRt.height == height + && _downscaleRt.graphicsFormat == MaskInputFormat) { if (!_downscaleRt.IsCreated()) { @@ -559,13 +795,26 @@ private void EnsureDownscaleRt(Texture source) ReleaseDownscaleRt(); - _downscaleRt = new RenderTexture(width, height, 0, RenderTextureFormat.ARGB32) + // Linear UNorm on both Vulkan and GLES. A default ARGB32 target is sRGB in a + // linear project, and the two APIs do not hand those bytes back the same way. + var descriptor = new RenderTextureDescriptor(width, height, MaskInputFormat, 0) + { + msaaSamples = 1, + useMipMap = false, + autoGenerateMips = false, + }; + _downscaleRt = new RenderTexture(descriptor) { name = "StreamBgFilterMaskInput", filterMode = FilterMode.Bilinear, wrapMode = TextureWrapMode.Clamp, }; _downscaleRt.Create(); + if (!_downscaleRt.IsCreated()) + { + _logs?.Warning("Background filter: failed to create the mask input texture."); + ReleaseDownscaleRt(); + } } private void DestroyNative() @@ -627,6 +876,7 @@ private static void GetMaskInputSize(int sourceWidth, int sourceHeight, out int width = Mathf.Max(2, Mathf.RoundToInt(sourceWidth * scale)); height = Mathf.Max(2, Mathf.RoundToInt(sourceHeight * scale)); } + #endif private void ReleaseDownscaleRt() diff --git a/Packages/StreamVideo/Runtime/Core/BackgroundFilters/MaskFrameScale.cs b/Packages/StreamVideo/Runtime/Core/BackgroundFilters/MaskFrameScale.cs new file mode 100644 index 00000000..f8fd156f --- /dev/null +++ b/Packages/StreamVideo/Runtime/Core/BackgroundFilters/MaskFrameScale.cs @@ -0,0 +1,59 @@ +using UnityEngine; + +namespace StreamVideo.Core.BackgroundFilters +{ + /// + /// Nearest-neighbor downscale of a bottom-up camera buffer into tightly packed RGBA. + /// Row 0 stays the bottom row, matching WebCamTexture.GetPixels32 and Texture2D.ReadPixels. + /// + internal static class MaskFrameScale + { + public static void DownscaleNearest(Color32[] source, int srcWidth, int srcHeight, byte[] dest, int dstWidth, + int dstHeight) + { + if (source == null) + { + throw new System.ArgumentNullException(nameof(source)); + } + + if (dest == null) + { + throw new System.ArgumentNullException(nameof(dest)); + } + + if (srcWidth <= 0 || srcHeight <= 0 || dstWidth <= 0 || dstHeight <= 0) + { + throw new System.ArgumentException("Source and destination sizes must be positive."); + } + + var srcNeeded = srcWidth * srcHeight; + var dstNeeded = dstWidth * dstHeight * 4; + if (source.Length < srcNeeded) + { + throw new System.ArgumentException("Source is smaller than width*height.", nameof(source)); + } + + if (dest.Length < dstNeeded) + { + throw new System.ArgumentException("Destination is smaller than width*height*4.", nameof(dest)); + } + + for (var y = 0; y < dstHeight; y++) + { + var sy = y * srcHeight / dstHeight; + var srcRow = sy * srcWidth; + var dstRow = y * dstWidth * 4; + for (var x = 0; x < dstWidth; x++) + { + var sx = x * srcWidth / dstWidth; + var pixel = source[srcRow + sx]; + var i = dstRow + (x * 4); + dest[i] = pixel.r; + dest[i + 1] = pixel.g; + dest[i + 2] = pixel.b; + dest[i + 3] = pixel.a; + } + } + } + } +} diff --git a/Packages/StreamVideo/Runtime/Core/BackgroundFilters/MaskFrameScale.cs.meta b/Packages/StreamVideo/Runtime/Core/BackgroundFilters/MaskFrameScale.cs.meta new file mode 100644 index 00000000..55c284fb --- /dev/null +++ b/Packages/StreamVideo/Runtime/Core/BackgroundFilters/MaskFrameScale.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 7e4c1a9b2d6f48e1a0c3b5d7e9f10234 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Packages/StreamVideo/Runtime/Libs/BackgroundFilters/Plugins/Android/StreamBackgroundFilters.androidlib/src/main/java/io/getstream/unitybackgroundfilters/UnityMlKitPersonSegmenter.java b/Packages/StreamVideo/Runtime/Libs/BackgroundFilters/Plugins/Android/StreamBackgroundFilters.androidlib/src/main/java/io/getstream/unitybackgroundfilters/UnityMlKitPersonSegmenter.java index f4ba4d55..8a9b28c1 100644 --- a/Packages/StreamVideo/Runtime/Libs/BackgroundFilters/Plugins/Android/StreamBackgroundFilters.androidlib/src/main/java/io/getstream/unitybackgroundfilters/UnityMlKitPersonSegmenter.java +++ b/Packages/StreamVideo/Runtime/Libs/BackgroundFilters/Plugins/Android/StreamBackgroundFilters.androidlib/src/main/java/io/getstream/unitybackgroundfilters/UnityMlKitPersonSegmenter.java @@ -16,8 +16,11 @@ /** * Async ML Kit selfie segmenter for Unity. Reuses the last mask and never blocks the caller. - * {@link #destroy()} is non-blocking: in-flight {@code process} releases native resources from - * its listener so the bitmap is not recycled while ML Kit still holds it. + * Each frame gets a new {@link Bitmap}, matching the Android video filter. Reusing one bitmap + * left ML Kit on the first mask while the camera kept moving. + * {@link #destroy()} is non-blocking: an in-flight {@code process} releases its bitmap when + * it finishes. A completed bitmap is kept until the next frame finishes so STREAM_MODE can + * still read it. */ public class UnityMlKitPersonSegmenter { private static final String TAG = "StreamBgFilter"; @@ -29,7 +32,10 @@ public class UnityMlKitPersonSegmenter { private boolean debugLogs; private final Map lastDebugByKey = new HashMap(); private Segmenter segmenter; - private Bitmap reusableBitmap; + private Bitmap inFlightBitmap; + // Bitmap whose process() already completed. Recycled on the next completion. + // Recycling the bitmap inside its own success listener froze STREAM_MODE on the first person. + private Bitmap completedBitmap; private int[] argbScratch; private byte[] latestMask; @@ -106,13 +112,15 @@ public void processAsync(byte[] rgba, int width, int height, int rotationDegrees } try { - Bitmap bitmap = getBitmapLocked(width, height); + Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); + inFlightBitmap = bitmap; copyRgbaToBitmap(rgba, width, height, bitmap); inFlightRotation = rotationDegrees; // Pixels are already upright; passing webcam rotation here would swap mask size. image = InputImage.fromBitmap(bitmap, 0); active = segmenter; } catch (Throwable t) { + recycleInFlightBitmapLocked(); inFlight.set(false); Log.w(TAG, "Failed to copy frame for ML Kit.", t); return; @@ -215,6 +223,17 @@ private void onMaskFailure(Exception e) { private void onProcessFinished(byte[] packed, int width, int height) { synchronized (lock) { + // Keep the bitmap that just finished. STREAM_MODE still reads it while the next + // frame is processed. Recycle only the one from the frame before that. + try { + recycleBitmap(completedBitmap); + completedBitmap = inFlightBitmap; + inFlightBitmap = null; + } catch (Throwable t) { + Log.w(TAG, "Failed to recycle ML Kit bitmap.", t); + completedBitmap = inFlightBitmap; + inFlightBitmap = null; + } inFlight.set(false); if (destroyed) { @@ -244,10 +263,9 @@ private void releaseLocked() { segmenter = null; } - if (reusableBitmap != null && !reusableBitmap.isRecycled()) { - reusableBitmap.recycle(); - } - reusableBitmap = null; + recycleInFlightBitmapLocked(); + recycleBitmap(completedBitmap); + completedBitmap = null; argbScratch = null; synchronized (lastDebugByKey) { @@ -263,18 +281,15 @@ private void clearMaskLocked() { maskDirty = false; } - private Bitmap getBitmapLocked(int width, int height) { - if (reusableBitmap == null - || reusableBitmap.isRecycled() - || reusableBitmap.getWidth() != width - || reusableBitmap.getHeight() != height) { - if (reusableBitmap != null && !reusableBitmap.isRecycled()) { - reusableBitmap.recycle(); - } - reusableBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); - } + private void recycleInFlightBitmapLocked() { + recycleBitmap(inFlightBitmap); + inFlightBitmap = null; + } - return reusableBitmap; + private static void recycleBitmap(Bitmap bitmap) { + if (bitmap != null && !bitmap.isRecycled()) { + bitmap.recycle(); + } } private void copyRgbaToBitmap(byte[] rgba, int width, int height, Bitmap bitmap) { @@ -300,7 +315,7 @@ private void copyRgbaToBitmap(byte[] rgba, int width, int height, Bitmap bitmap) } private String describeBitmap() { - Bitmap bitmap = reusableBitmap; + Bitmap bitmap = inFlightBitmap; if (bitmap == null || bitmap.isRecycled()) { return "null"; } @@ -309,7 +324,7 @@ private String describeBitmap() { } private boolean bitmapAspectMatches(int width, int height) { - Bitmap bitmap = reusableBitmap; + Bitmap bitmap = inFlightBitmap; return bitmap != null && !bitmap.isRecycled() && width * bitmap.getHeight() == height * bitmap.getWidth(); } diff --git a/Packages/StreamVideo/Tests/Editor/BackgroundCompositorTests.cs b/Packages/StreamVideo/Tests/Editor/BackgroundCompositorTests.cs index 1947059a..8c6e9380 100644 --- a/Packages/StreamVideo/Tests/Editor/BackgroundCompositorTests.cs +++ b/Packages/StreamVideo/Tests/Editor/BackgroundCompositorTests.cs @@ -2,6 +2,7 @@ using NUnit.Framework; using StreamVideo.Core.BackgroundFilters; using UnityEngine; +using UnityEngine.Rendering; namespace StreamVideo.Tests.Editor { @@ -121,6 +122,85 @@ public void When_apply_expect_destination_size_is_unchanged() "Size-preserving apply must still composite."); } + [Test] + public void When_mask_moves_expect_sharp_pixel_follows_it() + { + IgnoreIfBackgroundFilterShadersUnsupported(); + if (SystemInfo.graphicsDeviceType == GraphicsDeviceType.Null) + { + Assert.Ignore("Compositing needs a GPU; the Editor is running without graphics."); + } + + const int width = 64; + const int height = 32; + _compositor = new BackgroundCompositor(); + _compositor.SetIntensity(StreamVideo.Core.BlurIntensity.Light); + _destination = new RenderTexture(width, height, 0, RenderTextureFormat.ARGB32); + _destination.Create(); + + var source = new Texture2D(width, height, TextureFormat.RGBA32, false) + { + filterMode = FilterMode.Point, + wrapMode = TextureWrapMode.Clamp, + }; + var mask = new Texture2D(width, height, TextureFormat.R8, false) + { + filterMode = FilterMode.Point, + wrapMode = TextureWrapMode.Clamp, + }; + try + { + var sourcePixels = new Color[width * height]; + for (var y = 0; y < height; y++) + { + for (var x = 0; x < width; x++) + { + sourcePixels[(y * width) + x] = Color.green; + } + } + + for (var y = 0; y < height; y++) + { + sourcePixels[(y * width) + 10] = Color.red; + sourcePixels[(y * width) + 52] = Color.blue; + } + + source.SetPixels(sourcePixels); + source.Apply(false, false); + + UploadColumnMask(mask, width, height, 10); + _compositor.SetMask(mask); + _compositor.Apply(source, _destination); + + var left = ReadDestinationPixel(10, height / 2); + var right = ReadDestinationPixel(52, height / 2); + Assert.That(left.r, Is.GreaterThan(0.7f), + "The sharp cutout must keep the source color where the mask is."); + Assert.That(left.g, Is.LessThan(0.3f), + "A masked source pixel must not be replaced by the blurred neighbors."); + Assert.That(right.b, Is.LessThan(0.7f), + "A pixel outside the mask must be blurred rather than left sharp."); + + UploadColumnMask(mask, width, height, 52); + _compositor.SetMask(mask); + _compositor.Apply(source, _destination); + + left = ReadDestinationPixel(10, height / 2); + right = ReadDestinationPixel(52, height / 2); + Assert.That(right.b, Is.GreaterThan(0.7f), + "The sharp cutout must move when the mask moves."); + Assert.That(right.g, Is.LessThan(0.3f), + "The new mask position must show the original pixel, not the blur."); + Assert.That(left.r, Is.LessThan(0.7f), + "The previous mask position must not stay sharp."); + } + finally + { + UnityEngine.Object.DestroyImmediate(source); + UnityEngine.Object.DestroyImmediate(mask); + } + } + [Test] public void When_copy_args_missing_expect_can_copy_texture_is_false() { @@ -149,6 +229,44 @@ public void When_copy_args_not_created_expect_can_copy_texture_is_false() UnityEngine.Object.DestroyImmediate(released); } + private static void UploadColumnMask(Texture2D mask, int width, int height, int column) + { + var pixels = new byte[width * height]; + for (var y = 0; y < height; y++) + { + for (var x = column - 2; x <= column + 2; x++) + { + if (x < 0 || x >= width) + { + continue; + } + + pixels[(y * width) + x] = 255; + } + } + + mask.SetPixelData(pixels, 0); + mask.Apply(false, false); + } + + private Color ReadDestinationPixel(int x, int y) + { + var previous = RenderTexture.active; + var readback = new Texture2D(_destination.width, _destination.height, TextureFormat.RGBA32, false); + try + { + RenderTexture.active = _destination; + readback.ReadPixels(new Rect(0, 0, _destination.width, _destination.height), 0, 0); + readback.Apply(false, false); + return readback.GetPixel(x, y); + } + finally + { + RenderTexture.active = previous; + UnityEngine.Object.DestroyImmediate(readback); + } + } + private static void IgnoreIfBackgroundFilterShadersUnsupported() { var shader = Shader.Find("Hidden/StreamVideo/BackgroundMaskBlend") diff --git a/Packages/StreamVideo/Tests/Editor/MaskFrameScaleTests.cs b/Packages/StreamVideo/Tests/Editor/MaskFrameScaleTests.cs new file mode 100644 index 00000000..6e8d6c56 --- /dev/null +++ b/Packages/StreamVideo/Tests/Editor/MaskFrameScaleTests.cs @@ -0,0 +1,31 @@ +#if STREAM_TESTS_ENABLED +using NUnit.Framework; +using StreamVideo.Core.BackgroundFilters; +using UnityEngine; + +namespace StreamVideo.Tests.Editor +{ + /// + /// Tests for . + /// + internal sealed class MaskFrameScaleTests + { + [Test] + public void When_downscale_nearest_expect_bottom_row_and_column_centers_are_kept() + { + // 4x2, row 0 is the bottom row. Destination 2x1 must sample that bottom row, not the top. + var source = new[] + { + new Color32(1, 0, 0, 255), new Color32(2, 0, 0, 255), new Color32(3, 0, 0, 255), new Color32(4, 0, 0, 255), + new Color32(9, 0, 0, 255), new Color32(8, 0, 0, 255), new Color32(7, 0, 0, 255), new Color32(6, 0, 0, 255), + }; + var dest = new byte[2 * 1 * 4]; + + MaskFrameScale.DownscaleNearest(source, 4, 2, dest, 2, 1); + + Assert.That(dest, Is.EqualTo(new byte[] { 1, 0, 0, 255, 3, 0, 0, 255 }), + "A 2x1 downscale of a bottom-up buffer must keep the bottom row and the left of each half."); + } + } +} +#endif diff --git a/Packages/StreamVideo/Tests/Editor/MaskFrameScaleTests.cs.meta b/Packages/StreamVideo/Tests/Editor/MaskFrameScaleTests.cs.meta new file mode 100644 index 00000000..39462e4b --- /dev/null +++ b/Packages/StreamVideo/Tests/Editor/MaskFrameScaleTests.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 6b8d2e4f1a904c7e9d5b3a8c0f172635 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Packages/StreamVideo/Tests/Editor/PersonMaskOrientationTests.cs b/Packages/StreamVideo/Tests/Editor/PersonMaskOrientationTests.cs index 6a0a9417..05c52128 100644 --- a/Packages/StreamVideo/Tests/Editor/PersonMaskOrientationTests.cs +++ b/Packages/StreamVideo/Tests/Editor/PersonMaskOrientationTests.cs @@ -38,6 +38,93 @@ public void When_mask_rotated_90_then_unrotated_expect_original_bytes() "Rotate 90 then unrotate must yield the original webcam-space mask bytes."); } + [Test] + public void When_mask_rotated_270_then_unrotated_expect_original_bytes() + { + var original = new byte[] { 10, 20, 30, 40, 50, 60 }; + const int width = 2; + const int height = 3; + + var rotated = PersonMaskOrientation.RotateClockwise(original, width, height, 1, 270, + out var rotatedWidth, out var rotatedHeight); + + Assert.That(rotatedWidth, Is.EqualTo(3), + "Clockwise 270 must swap width and height."); + Assert.That(rotatedHeight, Is.EqualTo(2), + "Clockwise 270 must swap width and height."); + Assert.That(rotated, Is.EqualTo(new byte[] { 20, 40, 60, 10, 30, 50 }), + "Clockwise 270 of a 2x3 R8 buffer must match row-major y-down mapping."); + + var restored = PersonMaskOrientation.UnrotateClockwise(rotated, rotatedWidth, rotatedHeight, 1, 270, + out var restoredWidth, out var restoredHeight); + + Assert.That(restoredWidth, Is.EqualTo(width), + "Unrotate 270 must restore the original mask width for compositor UVs."); + Assert.That(restoredHeight, Is.EqualTo(height), + "Unrotate 270 must restore the original mask height for compositor UVs."); + Assert.That(restored, Is.EqualTo(original), + "Rotate 270 then unrotate must yield the original webcam-space mask bytes."); + } + + [Test] + public void When_bottom_up_readback_is_flipped_then_rotated_90_expect_upright_image() + { + // Visual image, top row first: 1 2 / 3 4. ReadPixels stores the bottom row first. + var readback = new byte[] { 3, 4, 1, 2 }; + const int width = 2; + const int height = 2; + var yDown = (byte[])readback.Clone(); + PersonMaskOrientation.FlipVertical(yDown, width, height, 1); + + var upright = PersonMaskOrientation.RotateClockwise(yDown, width, height, 1, 90, + out var uprightWidth, out var uprightHeight); + + Assert.That(uprightWidth, Is.EqualTo(height), + "Clockwise 90 of the flipped readback must swap width and height."); + Assert.That(uprightHeight, Is.EqualTo(width), + "Clockwise 90 of the flipped readback must swap width and height."); + Assert.That(upright, Is.EqualTo(new byte[] { 3, 1, 4, 2 }), + "Flipping a bottom-up readback then rotating 90 must present the upright image."); + + var unrotated = PersonMaskOrientation.UnrotateClockwise(upright, uprightWidth, uprightHeight, 1, 90, + out var cameraWidth, out var cameraHeight); + PersonMaskOrientation.FlipVertical(unrotated, cameraWidth, cameraHeight, 1); + + Assert.That(cameraWidth, Is.EqualTo(width), + "The mask must return to the readback width."); + Assert.That(cameraHeight, Is.EqualTo(height), + "The mask must return to the readback height."); + Assert.That(unrotated, Is.EqualTo(readback), + "Unrotate and the upload flip must put the mask back on the readback pixels."); + } + + [Test] + public void When_bottom_up_readback_is_flipped_then_rotated_270_expect_upright_image() + { + var readback = new byte[] { 3, 4, 1, 2 }; + const int width = 2; + const int height = 2; + var yDown = (byte[])readback.Clone(); + PersonMaskOrientation.FlipVertical(yDown, width, height, 1); + + var upright = PersonMaskOrientation.RotateClockwise(yDown, width, height, 1, 270, + out var uprightWidth, out var uprightHeight); + + Assert.That(uprightWidth, Is.EqualTo(height), + "Clockwise 270 of the flipped readback must swap width and height."); + Assert.That(uprightHeight, Is.EqualTo(width), + "Clockwise 270 of the flipped readback must swap width and height."); + Assert.That(upright, Is.EqualTo(new byte[] { 2, 4, 1, 3 }), + "Flipping a bottom-up readback then rotating 270 must present the upright image."); + + var unrotated = PersonMaskOrientation.UnrotateClockwise(upright, uprightWidth, uprightHeight, 1, 270, + out var cameraWidth, out var cameraHeight); + PersonMaskOrientation.FlipVertical(unrotated, cameraWidth, cameraHeight, 1); + + Assert.That(unrotated, Is.EqualTo(readback), + "Unrotate 270 and the upload flip must put the mask back on the readback pixels."); + } + [Test] public void When_mask_rotated_180_then_unrotated_expect_original_bytes() { From 0703e45d39b3aef2582c7df2a1d4f9862bf2ed26 Mon Sep 17 00:00:00 2001 From: Daniel Sierpinski Date: Fri, 4 Dec 2026 12:05:25 +0100 Subject: [PATCH 2/2] Clean up the Android blur cutout fix and match the publisher's upright orientation. Remove the CPU GetPixels32 fallback, MaskFrameScale, input hashing, and the debug heartbeat. Flip the ReadPixels bytes only when the camera is not vertically mirrored, matching PublisherVideoRotator, and return the flip with the mask through Java. takeMaskIfNew now snapshots the mask size, rotation, and flip so they always describe the returned bytes. Copy the readback into a reused buffer instead of allocating per submission. Widen the compositor mask-move test bands so half-texel resampling cannot fail it. Co-authored-by: Cursor --- .../AndroidMlKitPersonSegmenter.cs | 438 ++---------------- .../Core/BackgroundFilters/MaskFrameScale.cs | 59 --- .../BackgroundFilters/MaskFrameScale.cs.meta | 11 - .../PersonMaskOrientation.cs | 72 ++- .../UnityMlKitPersonSegmenter.java | 62 ++- .../Tests/Editor/BackgroundCompositorTests.cs | 15 +- .../Tests/Editor/MaskFrameScaleTests.cs | 31 -- .../Tests/Editor/MaskFrameScaleTests.cs.meta | 11 - .../Editor/PersonMaskOrientationTests.cs | 80 ++++ 9 files changed, 242 insertions(+), 537 deletions(-) delete mode 100644 Packages/StreamVideo/Runtime/Core/BackgroundFilters/MaskFrameScale.cs delete mode 100644 Packages/StreamVideo/Runtime/Core/BackgroundFilters/MaskFrameScale.cs.meta delete mode 100644 Packages/StreamVideo/Tests/Editor/MaskFrameScaleTests.cs delete mode 100644 Packages/StreamVideo/Tests/Editor/MaskFrameScaleTests.cs.meta diff --git a/Packages/StreamVideo/Runtime/Core/BackgroundFilters/AndroidMlKitPersonSegmenter.cs b/Packages/StreamVideo/Runtime/Core/BackgroundFilters/AndroidMlKitPersonSegmenter.cs index 75e25f0b..63cbcfd0 100644 --- a/Packages/StreamVideo/Runtime/Core/BackgroundFilters/AndroidMlKitPersonSegmenter.cs +++ b/Packages/StreamVideo/Runtime/Core/BackgroundFilters/AndroidMlKitPersonSegmenter.cs @@ -2,6 +2,7 @@ using StreamVideo.Libs.Logs; using UnityEngine; #if UNITY_ANDROID && !UNITY_EDITOR +using StreamVideo.Core.LowLevelClient; using UnityEngine.Experimental.Rendering; #endif using Object = UnityEngine.Object; @@ -10,19 +11,14 @@ namespace StreamVideo.Core.BackgroundFilters { /// /// Android ML Kit selfie segmenter. Async process, last-mask reuse. - /// The camera copy is a ReadPixels of a linear downscale, taken only when ML Kit is free. - /// AsyncGPUReadback of that target kept completing while the cutout stayed on the first person. - /// If that GPU copy is bit-identical for a while and WebCamTexture.GetPixels32 is not, - /// later frames come from the CPU buffer instead. Each submitted frame is a new Android bitmap. - /// The mask texture is reused. With STREAM_DEBUG_ENABLED and STREAM_LOG_BG_FILTER, - /// a log every two seconds reports whether the camera bytes and the mask bytes are changing. - /// Does not ReadPixels the publish texture. + /// The camera is blitted into a small target that is copied with ReadPixels only when ML Kit + /// can accept a frame. Does not ReadPixels the publish texture. /// 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. - /// ReadPixels and GetPixels32 are bottom-up. Rotation treats row 0 as the top, matching - /// an Android bitmap, so those bytes are flipped before they are rotated upright. The mask is - /// flipped back before Texture2D.SetPixelData, where row 0 is the bottom. + /// keeping the camera aspect. The bottom-up ReadPixels bytes are turned into the upright image + /// the publisher sends (), and the mask is mapped + /// back before Texture2D.SetPixelData so compositor UVs match WebCamTexture space. + /// The rotation and flip travel with the frame through Java, so a mask is always mapped back with the + /// values it was submitted with, even if the camera switches in between. /// only checks the ML Kit classpath. Segmentation.getClient /// runs on the first / . /// is non-blocking: an in-flight Java process releases its own resources @@ -74,11 +70,6 @@ public void RequestSegmentation(Texture source) #if STREAM_DEBUG_ENABLED && STREAM_LOG_BG_FILTER _lastSource = source; #endif - if (_useCpuCamera && TrySubmitWebCamCpu(source as WebCamTexture)) - { - return; - } - // ML Kit is the slow part. Copy the camera only when it can accept a frame, // so ReadPixels does not flush the GPU on frames that would be dropped. if (_native.Call("isBusy")) @@ -93,12 +84,12 @@ public void RequestSegmentation(Texture source) } Graphics.Blit(source, _downscaleRt); - _lastSourceRotation = GetSourceRotationDegrees(source); + PublisherVideoRotator.TryGetUprightOrientation(source as WebCamTexture, out _lastSourceRotation, + out var verticallyMirrored); #if STREAM_DEBUG_ENABLED && STREAM_LOG_BG_FILTER LogSubmitOrientation(source); #endif - ReadbackSynchronouslyAndProcess(); - TryPromoteCpuCamera(source); + ReadbackSynchronouslyAndProcess(PersonMaskOrientation.NeedsFlipBeforeRotation(verticallyMirrored)); #endif } @@ -115,9 +106,6 @@ public void Resume() } _paused = false; -#if UNITY_ANDROID && !UNITY_EDITOR && STREAM_DEBUG_ENABLED && STREAM_LOG_BG_FILTER - _nextPipelineLogAt = 0f; -#endif } public void Dispose() @@ -145,14 +133,9 @@ public void Dispose() public void ReleaseResources() { #if UNITY_ANDROID && !UNITY_EDITOR + _readbackRgba = null; _uprightRgba = null; - _yDownRgba = null; _rgbaSbytes = null; - _cpuRgba = null; - _cpuPixels = null; - _useCpuCamera = false; - _hasInputHash = false; - _identicalInputStreak = 0; DestroyTexture(ref _syncReadbackTexture); #endif _hasMask = false; @@ -168,23 +151,25 @@ public void PumpPendingMask() return; } + // The getters describe the mask returned by the last takeMaskIfNew. + var maskBytes = _native.Call("takeMaskIfNew"); + if (maskBytes == null) + { + return; + } + var width = _native.Call("getMaskWidth"); var height = _native.Call("getMaskHeight"); var rotation = _native.Call("getMaskRotation"); - var maskBytes = _native.Call("takeMaskIfNew"); - if (maskBytes != null && width > 0 && height > 0) + var flipped = _native.Call("getMaskFlipped"); + if (width <= 0 || height <= 0) { - var packed = ToByteArray(maskBytes); - var webcamMask = PersonMaskOrientation.UnrotateClockwise(packed, width, height, 1, rotation, - out var webcamWidth, out var webcamHeight); - // ML Kit's bitmap is y-down. SetPixelData is bottom-up, matching the camera texture. - PersonMaskOrientation.FlipVertical(webcamMask, webcamWidth, webcamHeight, 1); - UploadMask(webcamMask, webcamWidth, webcamHeight); + return; } -#if STREAM_DEBUG_ENABLED && STREAM_LOG_BG_FILTER - LogPipelineHeartbeat(); -#endif + var cameraMask = PersonMaskOrientation.UprightToCamera(ToByteArray(maskBytes), width, height, 1, + rotation, flipped, out var cameraWidth, out var cameraHeight); + UploadMask(cameraMask, cameraWidth, cameraHeight); #endif } @@ -199,44 +184,17 @@ public void PumpPendingMask() private RenderTexture _downscaleRt; private int _lastSourceRotation; #if UNITY_ANDROID && !UNITY_EDITOR - private const int IdenticalFramePromoteInterval = 12; private static readonly GraphicsFormat MaskInputFormat = GraphicsFormat.R8G8B8A8_UNorm; - private int _lastInputHash; - private bool _hasInputHash; - private int _identicalInputStreak; - private bool _useCpuCamera; #if STREAM_DEBUG_ENABLED && STREAM_LOG_BG_FILTER - private const float PipelineLogIntervalSeconds = 2f; - - private float _nextPipelineLogAt; - private int _readbacksCompleted; - private int _masksUploaded; - private int _readbacksLogged; - private int _masksLogged; - private int _inputChanges; - private int _inputChangesLogged; - private int _maskChanges; - private int _maskChangesLogged; - private int _lastMaskHash; - private bool _hasMaskHash; - private int _lastCentroidX = -1; - private int _lastCentroidY = -1; - private int _centroidMinX; - private int _centroidMaxX; - private int _centroidMinY; - private int _centroidMaxY; - private bool _hasCentroidSpan; private Texture _lastSource; #endif private bool _createAttempted; private AndroidJavaObject _native; private Texture2D _syncReadbackTexture; private sbyte[] _rgbaSbytes; + private byte[] _readbackRgba; private byte[] _uprightRgba; - private byte[] _yDownRgba; - private byte[] _cpuRgba; - private Color32[] _cpuPixels; #endif private AndroidMlKitPersonSegmenter(ILogs logs) @@ -336,97 +294,7 @@ private static AndroidJavaObject CreateNative() return new AndroidJavaObject(JavaClass); } - private bool TrySubmitWebCamCpu(WebCamTexture webcam) - { - if (webcam == null) - { - return false; - } - - if (_native.Call("isBusy")) - { - return true; - } - - if (!TryCopyWebCam(webcam, out var rgba, out var width, out var height)) - { - return false; - } - - _lastSourceRotation = GetSourceRotationDegrees(webcam); -#if STREAM_DEBUG_ENABLED && STREAM_LOG_BG_FILTER - _readbacksCompleted++; -#endif - NoteInput(rgba, width * height * 4); - SubmitRgba(CopyAsYDown(rgba, width, height), width, height, _lastSourceRotation); - return true; - } - - private void TryPromoteCpuCamera(Texture source) - { - if (_useCpuCamera || _identicalInputStreak < IdenticalFramePromoteInterval - || _identicalInputStreak % IdenticalFramePromoteInterval != 0) - { - return; - } - - var webcam = source as WebCamTexture; - if (!TryCopyWebCam(webcam, out var rgba, out var width, out var height)) - { - return; - } - - var cpuHash = HashSample(rgba, width * height * 4); - if (cpuHash == _lastInputHash) - { - return; - } - - _useCpuCamera = true; - _logs?.Warning( - "Background filter: GPU camera copy is stuck; reading WebCamTexture pixels on the CPU. gfx=" - + SystemInfo.graphicsDeviceType); - } - - private bool TryCopyWebCam(WebCamTexture webcam, out byte[] rgba, out int width, out int height) - { - rgba = null; - width = 0; - height = 0; - if (webcam == null || !webcam.isReadable || webcam.width < 2 || webcam.height < 2) - { - return false; - } - - var count = webcam.width * webcam.height; - if (_cpuPixels == null || _cpuPixels.Length != count) - { - _cpuPixels = new Color32[count]; - } - - try - { - _cpuPixels = webcam.GetPixels32(_cpuPixels); - } - catch (Exception e) - { - _logs?.Warning("Background filter: failed to read WebCamTexture pixels: " + e.Message); - return false; - } - - GetMaskInputSize(webcam.width, webcam.height, out width, out height); - var needed = width * height * 4; - if (_cpuRgba == null || _cpuRgba.Length < needed) - { - _cpuRgba = new byte[needed]; - } - - MaskFrameScale.DownscaleNearest(_cpuPixels, webcam.width, webcam.height, _cpuRgba, width, height); - rgba = _cpuRgba; - return true; - } - - private void ReadbackSynchronouslyAndProcess() + private void ReadbackSynchronouslyAndProcess(bool flip) { var width = _downscaleRt.width; var height = _downscaleRt.height; @@ -444,19 +312,20 @@ private void ReadbackSynchronouslyAndProcess() var prev = RenderTexture.active; RenderTexture.active = _downscaleRt; _syncReadbackTexture.ReadPixels(new Rect(0, 0, width, height), 0, 0, false); - _syncReadbackTexture.Apply(false, false); RenderTexture.active = prev; - // ReadPixels is bottom-up. Rotation and the Android bitmap treat row 0 as the top. - var rgba = _syncReadbackTexture.GetRawTextureData(); -#if STREAM_DEBUG_ENABLED && STREAM_LOG_BG_FILTER - _readbacksCompleted++; -#endif - NoteInput(rgba, width * height * 4); - SubmitRgba(CopyAsYDown(rgba, width, height), width, height, _lastSourceRotation); + // ReadPixels stores Texture2D bottom-up on every API. + var raw = _syncReadbackTexture.GetRawTextureData(); + if (_readbackRgba == null || _readbackRgba.Length != raw.Length) + { + _readbackRgba = new byte[raw.Length]; + } + + raw.CopyTo(_readbackRgba); + SubmitRgba(_readbackRgba, width, height, _lastSourceRotation, flip); } - private void SubmitRgba(byte[] rgba, int width, int height, int rotationDegrees) + private void SubmitRgba(byte[] rgba, int width, int height, int rotationDegrees, bool flip) { if (_disposed || rgba == null || _native == null) { @@ -464,22 +333,16 @@ private void SubmitRgba(byte[] rgba, int width, int height, int rotationDegrees) } var rotation = PersonMaskOrientation.NormalizeClockwiseDegrees(rotationDegrees); - var submitRgba = rgba; - var submitWidth = width; - var submitHeight = height; - if (rotation != 0) - { - PersonMaskOrientation.GetRotatedSize(width, height, rotation, out submitWidth, out submitHeight); - var needed = submitWidth * submitHeight * 4; - if (_uprightRgba == null || _uprightRgba.Length < needed) - { - _uprightRgba = new byte[needed]; - } - - PersonMaskOrientation.RotateClockwise(rgba, width, height, 4, rotation, _uprightRgba); - submitRgba = _uprightRgba; + PersonMaskOrientation.GetRotatedSize(width, height, rotation, out var submitWidth, out var submitHeight); + var needed = submitWidth * submitHeight * 4; + if (rotation != 0 && (_uprightRgba == null || _uprightRgba.Length < needed)) + { + _uprightRgba = new byte[needed]; } + var submitRgba = PersonMaskOrientation.CameraToUpright(rgba, width, height, 4, rotation, flip, + _uprightRgba); + #if STREAM_DEBUG_ENABLED && STREAM_LOG_BG_FILTER var webcam = _lastSource as WebCamTexture; var canRead = CameraOrientationDebug.CanReadWebCamOrientation(webcam); @@ -488,40 +351,13 @@ private void SubmitRgba(byte[] rgba, int width, int height, int rotationDegrees) "rgba=" + width + "x" + height + " bytes=" + rgba.Length + " upright=" + submitWidth + "x" + submitHeight + " mlkitRotationDegrees=0 (pixels rotated CW " + rotation + ")" + + " flipped=" + flip + " webcamRot=" + webcamRot + " mirrored=" + (canRead && webcam.videoVerticallyMirrored) + " gfx=" + SystemInfo.graphicsDeviceType + " asyncReadback=" + SystemInfo.supportsAsyncGPUReadback); #endif - _native.Call("processAsync", ToSByteArray(submitRgba), submitWidth, submitHeight, rotation); - } - - private static int GetSourceRotationDegrees(Texture source) - { - var webcam = source as WebCamTexture; - if (webcam == null) - { - return 0; - } - - return PersonMaskOrientation.NormalizeClockwiseDegrees(webcam.videoRotationAngle); - } - - /// - /// has row 0 at the bottom, like ReadPixels and - /// GetPixels32. The copy has row 0 at the top so clockwise rotation matches the bitmap. - /// - private byte[] CopyAsYDown(byte[] bottomUp, int width, int height) - { - var needed = width * height * 4; - if (_yDownRgba == null || _yDownRgba.Length < needed) - { - _yDownRgba = new byte[needed]; - } - - Buffer.BlockCopy(bottomUp, 0, _yDownRgba, 0, needed); - PersonMaskOrientation.FlipVertical(_yDownRgba, width, height, 4); - return _yDownRgba; + _native.Call("processAsync", ToSByteArray(submitRgba), submitWidth, submitHeight, rotation, flip); } private void UploadMask(byte[] mask, int width, int height) @@ -546,13 +382,11 @@ private void UploadMask(byte[] mask, int width, int height) }; } - // Caller flipped the y-down mask so row 0 is the bottom of the camera texture. _maskTexture.SetPixelData(mask, 0); _maskTexture.Apply(false, false); _hasMask = true; + #if STREAM_DEBUG_ENABLED && STREAM_LOG_BG_FILTER - _masksUploaded++; - NoteMask(mask, width, height); var hits = 0; var needed = width * height; for (var i = 0; i < needed; i++) @@ -574,178 +408,6 @@ private void UploadMask(byte[] mask, int width, int height) #endif } -#if STREAM_DEBUG_ENABLED && STREAM_LOG_BG_FILTER - private void LogPipelineHeartbeat() - { - var now = Time.realtimeSinceStartup; - if (_nextPipelineLogAt <= 0f) - { - _nextPipelineLogAt = now + PipelineLogIntervalSeconds; - return; - } - - if (now < _nextPipelineLogAt) - { - return; - } - - _nextPipelineLogAt = now + PipelineLogIntervalSeconds; - var readbacks = _readbacksCompleted - _readbacksLogged; - var masks = _masksUploaded - _masksLogged; - var inputChanged = _inputChanges - _inputChangesLogged; - var maskChanged = _maskChanges - _maskChangesLogged; - var spanX = _hasCentroidSpan ? _centroidMaxX - _centroidMinX : 0; - var spanY = _hasCentroidSpan ? _centroidMaxY - _centroidMinY : 0; - var status = string.Empty; - if (readbacks == 0) - { - status = " readback stopped"; - } - else if (inputChanged == 0) - { - status = " camera frame unchanged"; - } - else if (masks == 0) - { - status = " ML Kit stopped"; - } - else if (maskChanged == 0) - { - status = " mask unchanged"; - } - - _logs?.Info("Background filter: gfx=" + SystemInfo.graphicsDeviceType - + " cpuCamera=" + _useCpuCamera - + " readbacks completed=" + readbacks - + " masks uploaded=" + masks - + " inputChanged=" + inputChanged - + " maskChanged=" + maskChanged - + " rot=" + _lastSourceRotation - + " centroid=" + _lastCentroidX + "," + _lastCentroidY - + " centroidSpan=" + spanX + "," + spanY - + " (total " + _readbacksCompleted + "/" + _masksUploaded + ")" - + status); - _readbacksLogged = _readbacksCompleted; - _masksLogged = _masksUploaded; - _inputChangesLogged = _inputChanges; - _maskChangesLogged = _maskChanges; - _hasCentroidSpan = false; - } -#endif - - private void NoteInput(byte[] rgba, int length) - { - var hash = HashSample(rgba, length); - if (_hasInputHash) - { - if (hash == _lastInputHash) - { - _identicalInputStreak++; - } - else - { - _identicalInputStreak = 0; -#if STREAM_DEBUG_ENABLED && STREAM_LOG_BG_FILTER - _inputChanges++; -#endif - } - } - - _lastInputHash = hash; - _hasInputHash = true; - } - -#if STREAM_DEBUG_ENABLED && STREAM_LOG_BG_FILTER - private void NoteMask(byte[] mask, int width, int height) - { - var hash = HashSample(mask, width * height); - if (_hasMaskHash && hash != _lastMaskHash) - { - _maskChanges++; - } - - _lastMaskHash = hash; - _hasMaskHash = true; - - long sumX = 0; - long sumY = 0; - var hits = 0; - var count = width * height; - for (var i = 0; i < count; i++) - { - if (mask[i] <= 128) - { - continue; - } - - sumX += i % width; - sumY += i / width; - hits++; - } - - if (hits == 0) - { - _lastCentroidX = -1; - _lastCentroidY = -1; - return; - } - - _lastCentroidX = (int)(sumX / hits); - _lastCentroidY = (int)(sumY / hits); - if (!_hasCentroidSpan) - { - _centroidMinX = _centroidMaxX = _lastCentroidX; - _centroidMinY = _centroidMaxY = _lastCentroidY; - _hasCentroidSpan = true; - return; - } - - if (_lastCentroidX < _centroidMinX) - { - _centroidMinX = _lastCentroidX; - } - - if (_lastCentroidX > _centroidMaxX) - { - _centroidMaxX = _lastCentroidX; - } - - if (_lastCentroidY < _centroidMinY) - { - _centroidMinY = _lastCentroidY; - } - - if (_lastCentroidY > _centroidMaxY) - { - _centroidMaxY = _lastCentroidY; - } - } -#endif - - private static int HashSample(byte[] data, int length) - { - if (data == null || length <= 0) - { - return 0; - } - - if (length > data.Length) - { - length = data.Length; - } - - unchecked - { - var hash = 2166136261; - for (var i = 0; i < length; i++) - { - hash = (hash ^ data[i]) * 16777619; - } - - return (int)hash; - } - } - private static byte[] ToByteArray(sbyte[] source) { if (source == null) @@ -795,8 +457,7 @@ private void EnsureDownscaleRt(Texture source) ReleaseDownscaleRt(); - // Linear UNorm on both Vulkan and GLES. A default ARGB32 target is sRGB in a - // linear project, and the two APIs do not hand those bytes back the same way. + // Explicit linear UNorm. A default ARGB32 target is sRGB in a Linear project. var descriptor = new RenderTextureDescriptor(width, height, MaskInputFormat, 0) { msaaSamples = 1, @@ -876,7 +537,6 @@ private static void GetMaskInputSize(int sourceWidth, int sourceHeight, out int width = Mathf.Max(2, Mathf.RoundToInt(sourceWidth * scale)); height = Mathf.Max(2, Mathf.RoundToInt(sourceHeight * scale)); } - #endif private void ReleaseDownscaleRt() diff --git a/Packages/StreamVideo/Runtime/Core/BackgroundFilters/MaskFrameScale.cs b/Packages/StreamVideo/Runtime/Core/BackgroundFilters/MaskFrameScale.cs deleted file mode 100644 index f8fd156f..00000000 --- a/Packages/StreamVideo/Runtime/Core/BackgroundFilters/MaskFrameScale.cs +++ /dev/null @@ -1,59 +0,0 @@ -using UnityEngine; - -namespace StreamVideo.Core.BackgroundFilters -{ - /// - /// Nearest-neighbor downscale of a bottom-up camera buffer into tightly packed RGBA. - /// Row 0 stays the bottom row, matching WebCamTexture.GetPixels32 and Texture2D.ReadPixels. - /// - internal static class MaskFrameScale - { - public static void DownscaleNearest(Color32[] source, int srcWidth, int srcHeight, byte[] dest, int dstWidth, - int dstHeight) - { - if (source == null) - { - throw new System.ArgumentNullException(nameof(source)); - } - - if (dest == null) - { - throw new System.ArgumentNullException(nameof(dest)); - } - - if (srcWidth <= 0 || srcHeight <= 0 || dstWidth <= 0 || dstHeight <= 0) - { - throw new System.ArgumentException("Source and destination sizes must be positive."); - } - - var srcNeeded = srcWidth * srcHeight; - var dstNeeded = dstWidth * dstHeight * 4; - if (source.Length < srcNeeded) - { - throw new System.ArgumentException("Source is smaller than width*height.", nameof(source)); - } - - if (dest.Length < dstNeeded) - { - throw new System.ArgumentException("Destination is smaller than width*height*4.", nameof(dest)); - } - - for (var y = 0; y < dstHeight; y++) - { - var sy = y * srcHeight / dstHeight; - var srcRow = sy * srcWidth; - var dstRow = y * dstWidth * 4; - for (var x = 0; x < dstWidth; x++) - { - var sx = x * srcWidth / dstWidth; - var pixel = source[srcRow + sx]; - var i = dstRow + (x * 4); - dest[i] = pixel.r; - dest[i + 1] = pixel.g; - dest[i + 2] = pixel.b; - dest[i + 3] = pixel.a; - } - } - } - } -} diff --git a/Packages/StreamVideo/Runtime/Core/BackgroundFilters/MaskFrameScale.cs.meta b/Packages/StreamVideo/Runtime/Core/BackgroundFilters/MaskFrameScale.cs.meta deleted file mode 100644 index 55c284fb..00000000 --- a/Packages/StreamVideo/Runtime/Core/BackgroundFilters/MaskFrameScale.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 7e4c1a9b2d6f48e1a0c3b5d7e9f10234 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Packages/StreamVideo/Runtime/Core/BackgroundFilters/PersonMaskOrientation.cs b/Packages/StreamVideo/Runtime/Core/BackgroundFilters/PersonMaskOrientation.cs index e0ee510f..472dfe18 100644 --- a/Packages/StreamVideo/Runtime/Core/BackgroundFilters/PersonMaskOrientation.cs +++ b/Packages/StreamVideo/Runtime/Core/BackgroundFilters/PersonMaskOrientation.cs @@ -4,13 +4,63 @@ 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. + /// mask back to WebCamTexture UV space. Rotation uses row-major layout with row 0 at + /// the top, like an Android Bitmap. + /// Android uses / on bottom-up + /// ReadPixels bytes. iOS uses and + /// on AsyncGPUReadback bytes. /// internal static class PersonMaskOrientation { + /// + /// Same notion of upright as PublisherVideoRotator: bottom-up bytes read top-down are + /// already vertically flipped, so they are flipped back unless the camera reports + /// videoVerticallyMirrored. + /// + public static bool NeedsFlipBeforeRotation(bool verticallyMirrored) => !verticallyMirrored; + + /// + /// Turns bottom-up camera bytes (ReadPixels / SetPixelData row order) into the + /// upright top-down image PublisherVideoRotator publishes. Flips + /// in place when is set. Returns + /// when no rotation is needed, otherwise , + /// which must hold the rotated size. + /// + public static byte[] CameraToUpright(byte[] bottomUp, int width, int height, int bytesPerPixel, + int degreesClockwise, bool flip, byte[] dest) + { + if (flip) + { + FlipVertical(bottomUp, width, height, bytesPerPixel); + } + + if (NormalizeClockwiseDegrees(degreesClockwise) == 0) + { + return bottomUp; + } + + RotateClockwise(bottomUp, width, height, bytesPerPixel, degreesClockwise, dest); + return dest; + } + + /// + /// Inverse of for a mask of the upright size. Pass the rotation and + /// flip the frame was submitted with. The result is bottom-up and aligned with the camera texture. + /// May return flipped in place. + /// + public static byte[] UprightToCamera(byte[] upright, int width, int height, int bytesPerPixel, + int degreesClockwise, bool flipped, out int cameraWidth, out int cameraHeight) + { + var camera = UnrotateClockwise(upright, width, height, bytesPerPixel, degreesClockwise, + out cameraWidth, out cameraHeight); + if (flipped && camera != null) + { + FlipVertical(camera, cameraWidth, cameraHeight, bytesPerPixel); + } + + return camera; + } + public static int NormalizeClockwiseDegrees(int degrees) { var n = degrees % 360; @@ -118,8 +168,8 @@ public static void RotateClockwise(byte[] source, int width, int height, int byt } /// - /// GLES AsyncGPUReadback matches this y-down layout with no CPU flip. Vulkan and - /// Metal (graphicsUVStartsAtTop) are the opposite; flip once after readback. + /// iOS AsyncGPUReadback path. GLES AsyncGPUReadback matches this y-down layout with no CPU + /// flip. Vulkan and Metal (graphicsUVStartsAtTop) are the opposite; flip once after readback. /// ReadPixels is already Unity Texture2D bottom-up and must not use this path. /// iOS Metal still needs on /// mask upload: a regular 2D WebCamTexture has UV y=0 at the bottom, unlike GLES OES. @@ -135,11 +185,11 @@ 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 - /// 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 + /// iOS AsyncGPUReadback path. 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 GLES does not flip on upload. 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. /// public static bool NeedsYFlipFromBitmapLayoutToTexture2D(bool isOpenGles) => !isOpenGles; diff --git a/Packages/StreamVideo/Runtime/Libs/BackgroundFilters/Plugins/Android/StreamBackgroundFilters.androidlib/src/main/java/io/getstream/unitybackgroundfilters/UnityMlKitPersonSegmenter.java b/Packages/StreamVideo/Runtime/Libs/BackgroundFilters/Plugins/Android/StreamBackgroundFilters.androidlib/src/main/java/io/getstream/unitybackgroundfilters/UnityMlKitPersonSegmenter.java index 8a9b28c1..3234a4df 100644 --- a/Packages/StreamVideo/Runtime/Libs/BackgroundFilters/Plugins/Android/StreamBackgroundFilters.androidlib/src/main/java/io/getstream/unitybackgroundfilters/UnityMlKitPersonSegmenter.java +++ b/Packages/StreamVideo/Runtime/Libs/BackgroundFilters/Plugins/Android/StreamBackgroundFilters.androidlib/src/main/java/io/getstream/unitybackgroundfilters/UnityMlKitPersonSegmenter.java @@ -16,11 +16,10 @@ /** * Async ML Kit selfie segmenter for Unity. Reuses the last mask and never blocks the caller. - * Each frame gets a new {@link Bitmap}, matching the Android video filter. Reusing one bitmap - * left ML Kit on the first mask while the camera kept moving. - * {@link #destroy()} is non-blocking: an in-flight {@code process} releases its bitmap when - * it finishes. A completed bitmap is kept until the next frame finishes so STREAM_MODE can - * still read it. + * One frame is in flight at a time. Each frame is copied into a new {@link Bitmap}; the bitmap + * of the last completed frame is recycled when the next frame finishes, not from its own listener. + * {@link #destroy()} is non-blocking: an in-flight {@code process} releases its resources when + * it finishes. */ public class UnityMlKitPersonSegmenter { private static final String TAG = "StreamBgFilter"; @@ -33,17 +32,23 @@ public class UnityMlKitPersonSegmenter { private final Map lastDebugByKey = new HashMap(); private Segmenter segmenter; private Bitmap inFlightBitmap; - // Bitmap whose process() already completed. Recycled on the next completion. - // Recycling the bitmap inside its own success listener froze STREAM_MODE on the first person. private Bitmap completedBitmap; private int[] argbScratch; + private int inFlightRotation; + private boolean inFlightFlipped; private byte[] latestMask; + private int latestWidth; + private int latestHeight; + private int latestRotation; + private boolean latestFlipped; + private boolean maskDirty; + // Describe the mask returned by the last takeMaskIfNew, so a frame finishing in between + // cannot pair those bytes with another frame's size, rotation, or flip. private int maskWidth; private int maskHeight; - private boolean maskDirty; - private int inFlightRotation; private int maskRotation; + private boolean maskFlipped; /** * Classpath check only. Does not call {@link Segmentation#getClient}. @@ -96,10 +101,10 @@ public boolean isBusy() { /** * {@code rgba} must already be upright (Unity rotates webcam pixels clockwise by * {@code rotationDegrees} before calling). {@code fromBitmap} stays at 0 so ML Kit - * does not swap mask dimensions. {@code rotationDegrees} is stored and returned with - * the mask so Unity can inverse-rotate back to webcam UVs. + * does not swap mask dimensions. {@code rotationDegrees} and {@code flipped} are stored and + * returned with the mask so Unity can map it back to webcam UVs. */ - public void processAsync(byte[] rgba, int width, int height, int rotationDegrees) { + public void processAsync(byte[] rgba, int width, int height, int rotationDegrees, boolean flipped) { if (rgba == null || width <= 0 || height <= 0) { return; } @@ -116,6 +121,7 @@ public void processAsync(byte[] rgba, int width, int height, int rotationDegrees inFlightBitmap = bitmap; copyRgbaToBitmap(rgba, width, height, bitmap); inFlightRotation = rotationDegrees; + inFlightFlipped = flipped; // Pixels are already upright; passing webcam rotation here would swap mask size. image = InputImage.fromBitmap(bitmap, 0); active = segmenter; @@ -130,6 +136,7 @@ public void processAsync(byte[] rgba, int width, int height, int rotationDegrees try { debug("submit", "processAsync bitmap=" + width + "x" + height + " mlkitRotationDegrees=0 pixelsRotatedCW=" + rotationDegrees + + " flipped=" + flipped + " rgbaBytes=" + rgba.length); active.process(image) .addOnSuccessListener(this::onMaskSuccess) @@ -147,6 +154,10 @@ public byte[] takeMaskIfNew() { } maskDirty = false; + maskWidth = latestWidth; + maskHeight = latestHeight; + maskRotation = latestRotation; + maskFlipped = latestFlipped; return latestMask; } } @@ -169,6 +180,12 @@ public int getMaskRotation() { } } + public boolean getMaskFlipped() { + synchronized (lock) { + return maskFlipped; + } + } + public void destroy() { synchronized (lock) { destroyed = true; @@ -223,17 +240,14 @@ private void onMaskFailure(Exception e) { private void onProcessFinished(byte[] packed, int width, int height) { synchronized (lock) { - // Keep the bitmap that just finished. STREAM_MODE still reads it while the next - // frame is processed. Recycle only the one from the frame before that. + Bitmap finished = inFlightBitmap; + inFlightBitmap = null; try { recycleBitmap(completedBitmap); - completedBitmap = inFlightBitmap; - inFlightBitmap = null; } catch (Throwable t) { Log.w(TAG, "Failed to recycle ML Kit bitmap.", t); - completedBitmap = inFlightBitmap; - inFlightBitmap = null; } + completedBitmap = finished; inFlight.set(false); if (destroyed) { @@ -246,9 +260,10 @@ private void onProcessFinished(byte[] packed, int width, int height) { } latestMask = packed; - maskWidth = width; - maskHeight = height; - maskRotation = inFlightRotation; + latestWidth = width; + latestHeight = height; + latestRotation = inFlightRotation; + latestFlipped = inFlightFlipped; maskDirty = true; } } @@ -275,9 +290,14 @@ private void releaseLocked() { private void clearMaskLocked() { latestMask = null; + latestWidth = 0; + latestHeight = 0; + latestRotation = 0; + latestFlipped = false; maskWidth = 0; maskHeight = 0; maskRotation = 0; + maskFlipped = false; maskDirty = false; } diff --git a/Packages/StreamVideo/Tests/Editor/BackgroundCompositorTests.cs b/Packages/StreamVideo/Tests/Editor/BackgroundCompositorTests.cs index 8c6e9380..e535a9d5 100644 --- a/Packages/StreamVideo/Tests/Editor/BackgroundCompositorTests.cs +++ b/Packages/StreamVideo/Tests/Editor/BackgroundCompositorTests.cs @@ -131,10 +131,12 @@ public void When_mask_moves_expect_sharp_pixel_follows_it() Assert.Ignore("Compositing needs a GPU; the Editor is running without graphics."); } + // Color bands as wide as the mask band, read at their centers, so a half-texel offset in + // any blit cannot mix in the background color. const int width = 64; const int height = 32; _compositor = new BackgroundCompositor(); - _compositor.SetIntensity(StreamVideo.Core.BlurIntensity.Light); + _compositor.SetIntensity(StreamVideo.Core.BlurIntensity.Heavy); _destination = new RenderTexture(width, height, 0, RenderTextureFormat.ARGB32); _destination.Create(); @@ -161,8 +163,11 @@ public void When_mask_moves_expect_sharp_pixel_follows_it() for (var y = 0; y < height; y++) { - sourcePixels[(y * width) + 10] = Color.red; - sourcePixels[(y * width) + 52] = Color.blue; + for (var offset = -ColumnBandHalfWidth; offset <= ColumnBandHalfWidth; offset++) + { + sourcePixels[(y * width) + 10 + offset] = Color.red; + sourcePixels[(y * width) + 52 + offset] = Color.blue; + } } source.SetPixels(sourcePixels); @@ -234,7 +239,7 @@ private static void UploadColumnMask(Texture2D mask, int width, int height, int var pixels = new byte[width * height]; for (var y = 0; y < height; y++) { - for (var x = column - 2; x <= column + 2; x++) + for (var x = column - ColumnBandHalfWidth; x <= column + ColumnBandHalfWidth; x++) { if (x < 0 || x >= width) { @@ -284,6 +289,8 @@ private static RenderTexture CreateDestination() return destination; } + private const int ColumnBandHalfWidth = 2; + private BackgroundCompositor _compositor; private RenderTexture _destination; } diff --git a/Packages/StreamVideo/Tests/Editor/MaskFrameScaleTests.cs b/Packages/StreamVideo/Tests/Editor/MaskFrameScaleTests.cs deleted file mode 100644 index 6e8d6c56..00000000 --- a/Packages/StreamVideo/Tests/Editor/MaskFrameScaleTests.cs +++ /dev/null @@ -1,31 +0,0 @@ -#if STREAM_TESTS_ENABLED -using NUnit.Framework; -using StreamVideo.Core.BackgroundFilters; -using UnityEngine; - -namespace StreamVideo.Tests.Editor -{ - /// - /// Tests for . - /// - internal sealed class MaskFrameScaleTests - { - [Test] - public void When_downscale_nearest_expect_bottom_row_and_column_centers_are_kept() - { - // 4x2, row 0 is the bottom row. Destination 2x1 must sample that bottom row, not the top. - var source = new[] - { - new Color32(1, 0, 0, 255), new Color32(2, 0, 0, 255), new Color32(3, 0, 0, 255), new Color32(4, 0, 0, 255), - new Color32(9, 0, 0, 255), new Color32(8, 0, 0, 255), new Color32(7, 0, 0, 255), new Color32(6, 0, 0, 255), - }; - var dest = new byte[2 * 1 * 4]; - - MaskFrameScale.DownscaleNearest(source, 4, 2, dest, 2, 1); - - Assert.That(dest, Is.EqualTo(new byte[] { 1, 0, 0, 255, 3, 0, 0, 255 }), - "A 2x1 downscale of a bottom-up buffer must keep the bottom row and the left of each half."); - } - } -} -#endif diff --git a/Packages/StreamVideo/Tests/Editor/MaskFrameScaleTests.cs.meta b/Packages/StreamVideo/Tests/Editor/MaskFrameScaleTests.cs.meta deleted file mode 100644 index 39462e4b..00000000 --- a/Packages/StreamVideo/Tests/Editor/MaskFrameScaleTests.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 6b8d2e4f1a904c7e9d5b3a8c0f172635 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Packages/StreamVideo/Tests/Editor/PersonMaskOrientationTests.cs b/Packages/StreamVideo/Tests/Editor/PersonMaskOrientationTests.cs index 05c52128..836a562c 100644 --- a/Packages/StreamVideo/Tests/Editor/PersonMaskOrientationTests.cs +++ b/Packages/StreamVideo/Tests/Editor/PersonMaskOrientationTests.cs @@ -1,6 +1,8 @@ #if STREAM_TESTS_ENABLED using NUnit.Framework; using StreamVideo.Core.BackgroundFilters; +using StreamVideo.Core.LowLevelClient; +using UnityEngine; namespace StreamVideo.Tests.Editor { @@ -125,6 +127,60 @@ public void When_bottom_up_readback_is_flipped_then_rotated_270_expect_upright_i "Unrotate 270 and the upload flip must put the mask back on the readback pixels."); } + [TestCase(0, false)] + [TestCase(0, true)] + [TestCase(90, false)] + [TestCase(90, true)] + [TestCase(180, false)] + [TestCase(180, true)] + [TestCase(270, false)] + [TestCase(270, true)] + public void When_camera_bytes_made_upright_expect_same_image_as_publisher(int rotation, + bool verticallyMirrored) + { + const int width = 3; + const int height = 2; + var bottomUp = new byte[] { 1, 2, 3, 4, 5, 6 }; + var flip = PersonMaskOrientation.NeedsFlipBeforeRotation(verticallyMirrored); + + var upright = PersonMaskOrientation.CameraToUpright((byte[])bottomUp.Clone(), width, height, 1, + rotation, flip, new byte[width * height]); + + Assert.That(upright, Is.EqualTo(GetPublisherUprightTopDown(bottomUp, width, height, rotation, + verticallyMirrored)), + $"Segmenter input at {rotation} degrees, mirrored={verticallyMirrored} must match the upright image the publisher sends."); + } + + [TestCase(0, false)] + [TestCase(0, true)] + [TestCase(90, false)] + [TestCase(90, true)] + [TestCase(180, false)] + [TestCase(180, true)] + [TestCase(270, false)] + [TestCase(270, true)] + public void When_upright_mask_mapped_back_expect_original_camera_bytes(int rotation, bool verticallyMirrored) + { + const int width = 3; + const int height = 2; + var bottomUp = new byte[] { 1, 2, 3, 4, 5, 6 }; + var flip = PersonMaskOrientation.NeedsFlipBeforeRotation(verticallyMirrored); + PersonMaskOrientation.GetRotatedSize(width, height, rotation, out var uprightWidth, + out var uprightHeight); + var upright = PersonMaskOrientation.CameraToUpright((byte[])bottomUp.Clone(), width, height, 1, + rotation, flip, new byte[width * height]); + + var camera = PersonMaskOrientation.UprightToCamera((byte[])upright.Clone(), uprightWidth, + uprightHeight, 1, rotation, flip, out var cameraWidth, out var cameraHeight); + + Assert.That(cameraWidth, Is.EqualTo(width), + "The mask must return to the camera texture width."); + Assert.That(cameraHeight, Is.EqualTo(height), + "The mask must return to the camera texture height."); + Assert.That(camera, Is.EqualTo(bottomUp), + $"At {rotation} degrees, mirrored={verticallyMirrored} the mask must line up with the camera pixels it was made from."); + } + [Test] public void When_mask_rotated_180_then_unrotated_expect_original_bytes() { @@ -188,6 +244,30 @@ public void When_uploading_bitmap_layout_mask_expect_texture2d_flip_on_metal_onl Assert.That(PersonMaskOrientation.NeedsYFlipFromBitmapLayoutToTexture2D(false), Is.True, "iOS Metal WebCamTexture is a regular 2D texture; flip Bitmap-layout mask bytes on upload."); } + + /// + /// CPU version of the publisher rotation shader, sampled at texel centers. Returns the result top-down. + /// + private static byte[] GetPublisherUprightTopDown(byte[] bottomUp, int width, int height, int rotation, + bool verticallyMirrored) + { + var transform = PublisherVideoRotator.GetUvTransform(rotation, verticallyMirrored); + PersonMaskOrientation.GetRotatedSize(width, height, rotation, out var destWidth, out var destHeight); + var topDown = new byte[destWidth * destHeight]; + for (var y = 0; y < destHeight; y++) + { + for (var x = 0; x < destWidth; x++) + { + var u = (x + 0.5f) / destWidth - 0.5f; + var v = (y + 0.5f) / destHeight - 0.5f; + var sourceX = Mathf.FloorToInt((transform.x * u + transform.y * v + 0.5f) * width); + var sourceY = Mathf.FloorToInt((transform.z * u + transform.w * v + 0.5f) * height); + topDown[(destHeight - 1 - y) * destWidth + x] = bottomUp[sourceY * width + sourceX]; + } + } + + return topDown; + } } } #endif