diff --git a/Packages/StreamVideo/Runtime/Core/BackgroundFilters/AndroidMlKitPersonSegmenter.cs b/Packages/StreamVideo/Runtime/Core/BackgroundFilters/AndroidMlKitPersonSegmenter.cs index d5c60ec8..63cbcfd0 100644 --- a/Packages/StreamVideo/Runtime/Core/BackgroundFilters/AndroidMlKitPersonSegmenter.cs +++ b/Packages/StreamVideo/Runtime/Core/BackgroundFilters/AndroidMlKitPersonSegmenter.cs @@ -2,22 +2,23 @@ using StreamVideo.Libs.Logs; using UnityEngine; #if UNITY_ANDROID && !UNITY_EDITOR -using UnityEngine.Rendering; +using StreamVideo.Core.LowLevelClient; +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 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. - /// Vulkan AsyncGPUReadback is Y-flipped once into the GLES/Bitmap y-down layout; GLES is not - /// flipped. Mask upload does not flip again. + /// 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 @@ -55,7 +56,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 +67,16 @@ 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 + // 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 +84,18 @@ public void RequestSegmentation(Texture source) } Graphics.Blit(source, _downscaleRt); -#if STREAM_DEBUG_ENABLED && STREAM_LOG_BG_FILTER - _lastSource = source; -#endif - _lastSourceRotation = GetSourceRotationDegrees(source); + PublisherVideoRotator.TryGetUprightOrientation(source as WebCamTexture, out _lastSourceRotation, + out var verticallyMirrored); #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(); + ReadbackSynchronouslyAndProcess(PersonMaskOrientation.NeedsFlipBeforeRotation(verticallyMirrored)); #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() @@ -155,8 +133,7 @@ public void Dispose() public void ReleaseResources() { #if UNITY_ANDROID && !UNITY_EDITOR - _hasPendingRgba = false; - _pendingRgba = null; + _readbackRgba = null; _uprightRgba = null; _rgbaSbytes = null; DestroyTexture(ref _syncReadbackTexture); @@ -174,19 +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); - UploadMask(webcamMask, webcamWidth, webcamHeight); + return; } - TrySubmitPending(); + var cameraMask = PersonMaskOrientation.UprightToCamera(ToByteArray(maskBytes), width, height, 1, + rotation, flipped, out var cameraWidth, out var cameraHeight); + UploadMask(cameraMask, cameraWidth, cameraHeight); #endif } @@ -197,25 +180,21 @@ 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 static readonly GraphicsFormat MaskInputFormat = GraphicsFormat.R8G8B8A8_UNorm; + #if STREAM_DEBUG_ENABLED && STREAM_LOG_BG_FILTER private Texture _lastSource; #endif private bool _createAttempted; private AndroidJavaObject _native; - private Action _readbackCallback; private Texture2D _syncReadbackTexture; private sbyte[] _rgbaSbytes; - private byte[] _pendingRgba; + private byte[] _readbackRgba; private byte[] _uprightRgba; - private int _pendingWidth; - private int _pendingHeight; - private int _pendingRotation; - private bool _hasPendingRgba; #endif private AndroidMlKitPersonSegmenter(ILogs logs) @@ -315,78 +294,7 @@ 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() - { - Action callback = null; - callback = request => OnReadback(request, callback); - return callback; - } - - private void OnReadback(AsyncGPUReadbackRequest request, Action callback) - { - if (callback != _readbackCallback) - { - return; - } - - _readbackInFlight = false; - - if (_disposed || _paused || _native == null) - { - return; - } - - if (request.hasError) - { - _logs?.Warning("Background filter: mask input readback failed."); - return; - } - - var data = request.GetData(); - var length = data.Length; - if (_pendingRgba == null || _pendingRgba.Length != length) - { - _pendingRgba = new byte[length]; - } - - 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)) - { - PersonMaskOrientation.FlipVertical(_pendingRgba, _pendingWidth, _pendingHeight, 4); - } - - _pendingRotation = _lastSourceRotation; - _hasPendingRgba = true; - TrySubmitPending(); - } - - private void TrySubmitPending() - { - if (_disposed || !_hasPendingRgba || _paused || _native == null) - { - return; - } - - if (_native.Call("isBusy")) - { - return; - } - - SubmitRgba(_pendingRgba, _pendingWidth, _pendingHeight, _pendingRotation); - _hasPendingRgba = false; - } - - private void ReadbackSynchronouslyAndProcess() + private void ReadbackSynchronouslyAndProcess(bool flip) { var width = _downscaleRt.width; var height = _downscaleRt.height; @@ -404,14 +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 stores Texture2D bottom-up on every API; do not Y-flip this path. - SubmitRgba(_syncReadbackTexture.GetRawTextureData(), 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) { @@ -419,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); @@ -443,23 +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); + _native.Call("processAsync", ToSByteArray(submitRgba), submitWidth, submitHeight, rotation, flip); } private void UploadMask(byte[] mask, int width, int height) @@ -487,7 +385,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; @@ -547,7 +444,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 +457,25 @@ private void EnsureDownscaleRt(Texture source) ReleaseDownscaleRt(); - _downscaleRt = new RenderTexture(width, height, 0, RenderTextureFormat.ARGB32) + // Explicit linear UNorm. A default ARGB32 target is sRGB in a Linear project. + 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() 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 f4ba4d55..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,8 +16,10 @@ /** * 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. + * 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"; @@ -29,15 +31,24 @@ public class UnityMlKitPersonSegmenter { private boolean debugLogs; private final Map lastDebugByKey = new HashMap(); private Segmenter segmenter; - private Bitmap reusableBitmap; + private Bitmap inFlightBitmap; + 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}. @@ -90,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; } @@ -106,13 +117,16 @@ 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; + inFlightFlipped = flipped; // 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; @@ -122,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) @@ -139,6 +154,10 @@ public byte[] takeMaskIfNew() { } maskDirty = false; + maskWidth = latestWidth; + maskHeight = latestHeight; + maskRotation = latestRotation; + maskFlipped = latestFlipped; return latestMask; } } @@ -161,6 +180,12 @@ public int getMaskRotation() { } } + public boolean getMaskFlipped() { + synchronized (lock) { + return maskFlipped; + } + } + public void destroy() { synchronized (lock) { destroyed = true; @@ -215,6 +240,14 @@ private void onMaskFailure(Exception e) { private void onProcessFinished(byte[] packed, int width, int height) { synchronized (lock) { + Bitmap finished = inFlightBitmap; + inFlightBitmap = null; + try { + recycleBitmap(completedBitmap); + } catch (Throwable t) { + Log.w(TAG, "Failed to recycle ML Kit bitmap.", t); + } + completedBitmap = finished; inFlight.set(false); if (destroyed) { @@ -227,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; } } @@ -244,10 +278,9 @@ private void releaseLocked() { segmenter = null; } - if (reusableBitmap != null && !reusableBitmap.isRecycled()) { - reusableBitmap.recycle(); - } - reusableBitmap = null; + recycleInFlightBitmapLocked(); + recycleBitmap(completedBitmap); + completedBitmap = null; argbScratch = null; synchronized (lastDebugByKey) { @@ -257,24 +290,26 @@ 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; } - 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 +335,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 +344,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..e535a9d5 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,90 @@ 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."); + } + + // 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.Heavy); + _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++) + { + for (var offset = -ColumnBandHalfWidth; offset <= ColumnBandHalfWidth; offset++) + { + sourcePixels[(y * width) + 10 + offset] = Color.red; + sourcePixels[(y * width) + 52 + offset] = 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 +234,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 - ColumnBandHalfWidth; x <= column + ColumnBandHalfWidth; 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") @@ -166,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/PersonMaskOrientationTests.cs b/Packages/StreamVideo/Tests/Editor/PersonMaskOrientationTests.cs index 6a0a9417..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 { @@ -38,6 +40,147 @@ 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."); + } + + [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() { @@ -101,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