Skip to content
Open
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 @@ -16,8 +16,8 @@ namespace StreamVideo.Core.BackgroundFilters
/// 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.
/// Vulkan AsyncGPUReadback is Y-flipped once into the GLES/Bitmap y-down layout and the mask is
/// flipped back before upload; GLES is not flipped.
/// <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 @@ -90,6 +90,9 @@ public void RequestSegmentation(Texture source)
_readbackCallback = CreateReadbackCallback();
}

#if STREAM_DEBUG_ENABLED && STREAM_LOG_BG_FILTER
_latency.OnReadbackRequested();
#endif
try
{
AsyncGPUReadback.Request(_downscaleRt, 0, TextureFormat.RGBA32, _readbackCallback);
Expand Down Expand Up @@ -117,6 +120,9 @@ public void Pause()
// A late callback from before the pause must not upload or clear a newer request's flag.
_readbackCallback = null;
_hasPendingRgba = false;
#if STREAM_DEBUG_ENABLED && STREAM_LOG_BG_FILTER
_latency.Reset();
#endif
#endif
}

Expand Down Expand Up @@ -181,9 +187,12 @@ public void PumpPendingMask()
if (maskBytes != null && width > 0 && height > 0)
{
var packed = ToByteArray(maskBytes);
var webcamMask = PersonMaskOrientation.UnrotateClockwise(packed, width, height, 1, rotation,
out var webcamWidth, out var webcamHeight);
var webcamMask = PersonMaskOrientation.ToReadbackLayout(packed, width, height, rotation,
_submittedYFlipped, out var webcamWidth, out var webcamHeight);
UploadMask(webcamMask, webcamWidth, webcamHeight);
#if STREAM_DEBUG_ENABLED && STREAM_LOG_BG_FILTER
_latency.OnMaskUploaded(_native.Call<bool>("isBusy"));
#endif
}

TrySubmitPending();
Expand Down Expand Up @@ -215,7 +224,12 @@ public void PumpPendingMask()
private int _pendingWidth;
private int _pendingHeight;
private int _pendingRotation;
private bool _pendingYFlipped;
private bool _hasPendingRgba;
private bool _submittedYFlipped;
#if STREAM_DEBUG_ENABLED && STREAM_LOG_BG_FILTER
private readonly MaskLatencyStats _latency = new MaskLatencyStats();
#endif
#endif

private AndroidMlKitPersonSegmenter(ILogs logs)
Expand Down Expand Up @@ -359,14 +373,18 @@ private void OnReadback(AsyncGPUReadbackRequest request, Action<AsyncGPUReadback
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))
_pendingYFlipped = packedBytes > 0 && _pendingRgba.Length >= packedBytes
&& PersonMaskOrientation.NeedsAsyncGpuReadbackYFlip(SystemInfo.graphicsUVStartsAtTop, isOpenGles);
if (_pendingYFlipped)
{
PersonMaskOrientation.FlipVertical(_pendingRgba, _pendingWidth, _pendingHeight, 4);
}

_pendingRotation = _lastSourceRotation;
_hasPendingRgba = true;
#if STREAM_DEBUG_ENABLED && STREAM_LOG_BG_FILTER
_latency.OnReadbackCompleted();
#endif
TrySubmitPending();
}

Expand All @@ -382,8 +400,11 @@ private void TrySubmitPending()
return;
}

SubmitRgba(_pendingRgba, _pendingWidth, _pendingHeight, _pendingRotation);
SubmitRgba(_pendingRgba, _pendingWidth, _pendingHeight, _pendingRotation, _pendingYFlipped);
_hasPendingRgba = false;
#if STREAM_DEBUG_ENABLED && STREAM_LOG_BG_FILTER
_latency.OnSubmitted();
#endif
}

private void ReadbackSynchronouslyAndProcess()
Expand All @@ -408,16 +429,18 @@ private void ReadbackSynchronouslyAndProcess()
RenderTexture.active = prev;

// ReadPixels stores Texture2D bottom-up on every API; do not Y-flip this path.
SubmitRgba(_syncReadbackTexture.GetRawTextureData(), width, height, _lastSourceRotation);
SubmitRgba(_syncReadbackTexture.GetRawTextureData(), width, height, _lastSourceRotation, false);
}

private void SubmitRgba(byte[] rgba, int width, int height, int rotationDegrees)
private void SubmitRgba(byte[] rgba, int width, int height, int rotationDegrees, bool yFlipped)
{
if (_disposed || rgba == null || _native == null)
{
return;
}

_submittedYFlipped = yFlipped;

var rotation = PersonMaskOrientation.NormalizeClockwiseDegrees(rotationDegrees);
var submitRgba = rgba;
var submitWidth = width;
Expand Down Expand Up @@ -487,7 +510,6 @@ private void UploadMask(byte[] mask, int width, int height)
_maskTexture.SetPixelData(mask, 0);
_maskTexture.Apply(false, false);
_hasMask = true;
// Mask bytes stay in the GLES y-down layout (Vulkan readback was already flipped).

#if STREAM_DEBUG_ENABLED && STREAM_LOG_BG_FILTER
var hits = 0;
Expand Down Expand Up @@ -672,5 +694,145 @@ private void DestroyTexture(ref Texture2D texture)

texture = null;
}

#if UNITY_ANDROID && !UNITY_EDITOR && STREAM_DEBUG_ENABLED && STREAM_LOG_BG_FILTER
/// <summary>
/// Mask age = camera frame read for segmentation until its mask is uploaded. Split into readback,
/// waiting for ML Kit to be free, and ML Kit processing (includes up to one Unity frame of pickup).
/// Logs averages and maxima every <see cref="WindowSeconds"/>. Grep logcat for <c>BgFilterLatency</c>.
/// </summary>
private sealed class MaskLatencyStats
{
public void OnReadbackRequested() => _requestTime = Now;

public void OnReadbackCompleted()
{
var now = Now;
_pendingCaptureTime = _requestTime;
_pendingReadyTime = now;
_readback.Add(now - _requestTime);
}

public void OnSubmitted()
{
_previous = _last;
_last = new Submission(_pendingCaptureTime, _pendingReadyTime, Now);
}

/// <param name="nativeBusy">A newer frame was submitted before this mask was picked up,
/// so the mask belongs to the previous submission.</param>
public void OnMaskUploaded(bool nativeBusy)
{
var submission = nativeBusy ? _previous : _last;
if (!submission.IsValid)
{
return;
}

var now = Now;
_age.Add(now - submission.CaptureTime);
_queued.Add(submission.SubmitTime - submission.ReadyTime);
_mlKit.Add(now - submission.SubmitTime);

if (_windowStart <= 0)
{
_windowStart = now;
_windowStartFrame = Time.frameCount;
return;
}

var window = now - _windowStart;
if (window < WindowSeconds)
{
return;
}

var line = "[BgFilterLatency] masksPerSec=" + (_age.Count / window).ToString("0.0")
+ " unityFps=" + ((Time.frameCount - _windowStartFrame) / window).ToString("0.0")
+ " | ms avg/max: age=" + _age + " readback=" + _readback + " waitForMlKit=" + _queued
+ " mlKit=" + _mlKit
+ " | " + SystemInfo.graphicsDeviceType;
Debug.LogFormat(LogType.Warning, LogOption.NoStacktrace, null, "{0}", line);

_age.Clear();
_readback.Clear();
_queued.Clear();
_mlKit.Clear();
_windowStart = now;
_windowStartFrame = Time.frameCount;
}

public void Reset()
{
_last = default;
_previous = default;
_windowStart = 0;
_age.Clear();
_readback.Clear();
_queued.Clear();
_mlKit.Clear();
}

private const double WindowSeconds = 2.0;

private readonly Metric _age = new Metric();
private readonly Metric _readback = new Metric();
private readonly Metric _queued = new Metric();
private readonly Metric _mlKit = new Metric();

private double _requestTime;
private double _pendingCaptureTime;
private double _pendingReadyTime;
private Submission _last;
private Submission _previous;
private double _windowStart;
private int _windowStartFrame;

private static double Now => Time.realtimeSinceStartupAsDouble;

private readonly struct Submission
{
public readonly double CaptureTime;
public readonly double ReadyTime;
public readonly double SubmitTime;

public bool IsValid => SubmitTime > 0;

public Submission(double captureTime, double readyTime, double submitTime)
{
CaptureTime = captureTime;
ReadyTime = readyTime;
SubmitTime = submitTime;
}
}

private sealed class Metric
{
public int Count { get; private set; }

public void Add(double seconds)
{
Count++;
_sum += seconds;
_max = Math.Max(_max, seconds);
}

public void Clear()
{
Count = 0;
_sum = 0;
_max = 0;
}

public override string ToString()
=> Count == 0
? "n/a"
: (_sum / Count * 1000).ToString("0") + "/" + (_max * 1000).ToString("0");

private double _sum;
private double _max;
}
}
#endif
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@ namespace StreamVideo.Core.BackgroundFilters
/// Clockwise pixel-buffer rotation for native segmenter input and inverse mapping of the
/// mask back to <c>WebCamTexture</c> 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 <c>WebCamTexture</c>; Android GLES does not.
/// flipped into this layout once and flipped back before the mask is uploaded
/// (<see cref="ToReadbackLayout"/> on Android, <see cref="NeedsYFlipFromBitmapLayoutToTexture2D"/> on iOS).
/// </summary>
internal static class PersonMaskOrientation
{
Expand Down Expand Up @@ -66,6 +66,26 @@ public static byte[] UnrotateClockwise(byte[] source, int width, int height, int
return RotateClockwise(source, width, height, bytesPerPixel, inverse, out destWidth, out destHeight);
}

/// <summary>
/// Maps an R8 mask computed from a rotated (and optionally Y-flipped) readback buffer back into
/// the readback layout, which matches <c>Texture2D.SetPixelData</c> on the same graphics API.
/// Every flip applied after readback must be undone here, otherwise the mask is mirrored against
/// the camera image (left/right after a 90° portrait rotation). May modify and return
/// <paramref name="mask"/>.
/// </summary>
public static byte[] ToReadbackLayout(byte[] mask, int width, int height, int degreesClockwise,
bool readbackWasYFlipped, out int destWidth, out int destHeight)
{
var unrotated = UnrotateClockwise(mask, width, height, 1, degreesClockwise, out destWidth,
out destHeight);
if (unrotated != null && readbackWasYFlipped)
{
FlipVertical(unrotated, destWidth, destHeight, 1);
}

return unrotated;
}

public static void RotateClockwise(byte[] source, int width, int height, int bytesPerPixel,
int degreesClockwise, byte[] dest)
{
Expand Down Expand Up @@ -137,7 +157,7 @@ public static bool NeedsAsyncGpuReadbackYFlip(bool graphicsUvStartsAtTop, bool i
/// <summary>
/// Bitmap y-down row 0 is the top of the image. <c>Texture2D.SetPixelData</c> row 0
/// is the bottom. GLES OES <c>WebCamTexture</c> sampling matches y-down bytes in a
/// Texture2D, so Android does not flip on upload. iOS Metal <c>WebCamTexture</c> is a
/// Texture2D. Android uses <see cref="ToReadbackLayout"/> instead. iOS Metal <c>WebCamTexture</c> 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.
Expand Down
38 changes: 38 additions & 0 deletions Packages/StreamVideo/Tests/Editor/PersonMaskOrientationTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,44 @@ public void When_mask_flipped_vertically_expect_rows_reversed()
"Flipping twice must restore the original bytes.");
}

[TestCase(0, false)]
[TestCase(90, false)]
[TestCase(180, false)]
[TestCase(270, false)]
[TestCase(0, true)]
[TestCase(90, true)]
[TestCase(180, true)]
[TestCase(270, true)]
public void When_mask_mapped_back_to_readback_layout_expect_it_lines_up_with_readback(int rotation,
bool readbackWasYFlipped)
{
// 3x2 readback, unique values. The fake segmenter returns its input, so the mapped mask must
// equal the readback byte for byte.
var readback = new byte[] { 10, 20, 30, 40, 50, 60 };
const int width = 3;
const int height = 2;

var input = (byte[])readback.Clone();
if (readbackWasYFlipped)
{
PersonMaskOrientation.FlipVertical(input, width, height, 1);
}

var segmenterInput = PersonMaskOrientation.RotateClockwise(input, width, height, 1, rotation,
out var inputWidth, out var inputHeight);
var mask = (byte[])segmenterInput.Clone();

var mapped = PersonMaskOrientation.ToReadbackLayout(mask, inputWidth, inputHeight, rotation,
readbackWasYFlipped, out var mappedWidth, out var mappedHeight);

Assert.That(mappedWidth, Is.EqualTo(width),
"Mapped mask width must match the readback so compositor UVs line up.");
Assert.That(mappedHeight, Is.EqualTo(height),
"Mapped mask height must match the readback so compositor UVs line up.");
Assert.That(mapped, Is.EqualTo(readback),
"Mask must undo both the rotation and the readback Y-flip, otherwise it is mirrored against the camera.");
}

[Test]
public void When_async_readback_on_gles_expect_no_y_flip()
{
Expand Down
Loading