Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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
{
/// <summary>
/// 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
/// <c>processAsync</c> is in flight, then submitted as soon as the segmenter is free.
/// Does not block <c>OnUpdate</c> 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 <c>ReadPixels</c> only when ML Kit
/// can accept a frame. Does not ReadPixels the publish texture.
/// Input is scaled so the short side is <see cref="MinMaskInputSize"/> (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 <c>WebCamTexture</c> 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 <c>ReadPixels</c> bytes are turned into the upright image
/// the publisher sends (<see cref="PersonMaskOrientation.CameraToUpright"/>), and the mask is mapped
/// back before <c>Texture2D.SetPixelData</c> so compositor UVs match <c>WebCamTexture</c> 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.
/// <see cref="TryCreate"/> only checks the ML Kit classpath. <c>Segmentation.getClient</c>
/// runs on the first <see cref="Resume"/> / <see cref="RequestSegmentation"/>.
/// <see cref="Dispose"/> is non-blocking: an in-flight Java <c>process</c> releases its own resources
Expand Down Expand Up @@ -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;
}
Expand All @@ -66,58 +67,35 @@ 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<bool>("isBusy"))
{
return;
}

EnsureDownscaleRt(source);
if (_downscaleRt == null)
{
return;
}

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()
Expand Down Expand Up @@ -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);
Expand All @@ -174,19 +151,25 @@ public void PumpPendingMask()
return;
}

// The getters describe the mask returned by the last takeMaskIfNew.
var maskBytes = _native.Call<sbyte[]>("takeMaskIfNew");
if (maskBytes == null)
{
return;
}

var width = _native.Call<int>("getMaskWidth");
var height = _native.Call<int>("getMaskHeight");
var rotation = _native.Call<int>("getMaskRotation");
var maskBytes = _native.Call<sbyte[]>("takeMaskIfNew");
if (maskBytes != null && width > 0 && height > 0)
var flipped = _native.Call<bool>("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
}

Expand All @@ -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<AsyncGPUReadbackRequest> _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)
Expand Down Expand Up @@ -315,78 +294,7 @@ private static AndroidJavaObject CreateNative()
return new AndroidJavaObject(JavaClass);
}

/// <summary>
/// Reused for every request until <see cref="Pause"/> drops it, so a stale callback is detected by identity
/// without allocating per readback.
/// </summary>
private Action<AsyncGPUReadbackRequest> CreateReadbackCallback()
{
Action<AsyncGPUReadbackRequest> callback = null;
callback = request => OnReadback(request, callback);
return callback;
}

private void OnReadback(AsyncGPUReadbackRequest request, Action<AsyncGPUReadbackRequest> 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<byte>();
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<bool>("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;
Expand All @@ -404,37 +312,37 @@ 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<byte>();
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)
{
return;
}

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);
Expand All @@ -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)
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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())
{
Expand All @@ -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()
Expand Down
Loading
Loading