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
@@ -0,0 +1,47 @@
using StreamVideo.Core.StatefulModels;
using StreamVideo.Core.StatefulModels.Tracks;
using UnityEngine;
using UnityEngine.UIElements;

namespace StreamVideoDocsCodeSamples._01_basics
{
/// <summary>
/// Binds a participant video track to a UI Toolkit Image.
/// Size the element with USS (absolute fill or flex-grow). Otherwise it sizes itself to the texture
/// and the layout jumps when the incoming resolution changes.
/// </summary>
internal class UiToolkitVideoCodeSamples : MonoBehaviour
{
public void BindParticipant(IStreamVideoCallParticipant participant)
{
foreach (var track in participant.GetTracks())
{
OnParticipantTrackAdded(participant, track);
}

// A reconnect creates a new track. Bind again from TrackAdded.
participant.TrackAdded += OnParticipantTrackAdded;
}

private void OnEnable()
{
_video = _document.rootVisualElement.Q<Image>("video");
_video.scaleMode = ScaleMode.ScaleAndCrop;
}

private void OnParticipantTrackAdded(IStreamVideoCallParticipant participant, IStreamTrack track)
{
if (!(track is StreamVideoTrack videoTrack))
{
return;
}

videoTrack.SetRenderTarget(_video);
}

[SerializeField]
private UIDocument _document;

private Image _video;
}
}

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,9 @@ public interface IStreamVideoDeviceManager : IDeviceManager<CameraDeviceInfo>, I
/// Assign it once (e.g. to a RawImage); the same instance is returned for the lifetime of the client, so no
/// rebinding is needed for camera switches, filter changes, joining, or leaving calls.
/// It is black until the camera delivers frames and is resized in place when the video size or orientation
/// changes. Do not apply the camera's videoRotationAngle. Call from the main thread.
/// changes. A UI Toolkit <see cref="UnityEngine.UIElements.Image"/> does not regenerate its crop when that
/// same texture instance changes size; call <see cref="UnityEngine.UIElements.VisualElement.MarkDirtyRepaint"/>
/// when the width or height changes. Do not apply the camera's videoRotationAngle. Call from the main thread.
/// </summary>
Texture GetLocalPreviewTexture();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,18 @@ private void OnVideoReceived(Texture renderer)
_targetImage.texture = renderer;
}

//StreamTodo: can we remove Unity dependency?
//StreamTodo: can we remove Unity dependency?
/// <summary>
/// Renders this track into a uGUI <see cref="RawImage"/>.
/// </summary>
/// <remarks>
/// Only one render target is active. The last <c>SetRenderTarget</c> call wins and clears the other target.
/// Call from the main thread. The target is updated when the incoming resolution changes and the texture
/// instance is replaced. After a reconnect the participant receives a new track
/// (<see cref="StreamVideo.Core.StatefulModels.IStreamVideoCallParticipant.TrackAdded"/>), so call <c>SetRenderTarget</c> again.
/// </remarks>
/// <param name="targetImage">Image that receives the video. Must not be null.</param>
/// <exception cref="ArgumentNullException"><paramref name="targetImage"/> is null.</exception>
public void SetRenderTarget(RawImage targetImage)
{
if (targetImage == null)
Expand All @@ -32,18 +43,53 @@ public void SetRenderTarget(RawImage targetImage)
}

_targetImage = targetImage;
_targetUIToolkitImage = null;
}

/// <summary>
/// Renders this track into a UI Toolkit <see cref="UnityEngine.UIElements.Image"/>.
/// </summary>
/// <remarks>
/// Only one render target is active. The last <c>SetRenderTarget</c> call wins and clears the other target.
/// Call from the main thread. <see cref="UnityEngine.UIElements.Image.image"/> stays null until the first
/// frame. The SDK assigns the new texture instance when the incoming resolution changes.
/// After a reconnect the participant receives a new track
/// (<see cref="StreamVideo.Core.StatefulModels.IStreamVideoCallParticipant.TrackAdded"/>), so call <c>SetRenderTarget</c> again.
/// Set <see cref="UnityEngine.UIElements.Image.scaleMode"/> to <see cref="ScaleMode.ScaleAndCrop"/> and size
/// the element with USS (absolute fill or flex-grow). Without that, the element sizes itself to the texture
/// and the layout jumps when the resolution changes.
/// </remarks>
/// <param name="targetImage">Element that receives the video. Must not be null.</param>
/// <exception cref="ArgumentNullException"><paramref name="targetImage"/> is null.</exception>
public void SetRenderTarget(UnityEngine.UIElements.Image targetImage)
{
if (targetImage == null)
{
throw new ArgumentNullException(nameof(targetImage));
}

_targetUIToolkitImage = targetImage;
_targetImage = null;
}

internal override void Update()
{
base.Update();
if (_targetImage == null)

if (_targetImage != null)
{
_targetImage.texture = Track.Texture;
return;
}

_targetImage.texture = Track.Texture;

if (_targetUIToolkitImage != null)
{
var texture = Track.Texture;
if (!ReferenceEquals(_targetUIToolkitImage.image, texture))
{
_targetUIToolkitImage.image = texture;
}
}
}

protected override void OnDisposing()
Expand All @@ -55,13 +101,21 @@ protected override void OnDisposing()
// {
// Track.OnVideoReceived -= OnVideoReceived;
// }


if (_targetUIToolkitImage != null && ReferenceEquals(_targetUIToolkitImage.image, Track.Texture))
{
_targetUIToolkitImage.image = null;
}

_targetUIToolkitImage = null;

base.OnDisposing();
}

//StreamTodo: remove
internal RenderTexture TargetTexture => throw new NotSupportedException("This property is deprecated");

private RawImage _targetImage;
private UnityEngine.UIElements.Image _targetUIToolkitImage;
}
}
209 changes: 209 additions & 0 deletions Packages/StreamVideo/Tests/Editor/StreamVideoTrackTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,209 @@
#if STREAM_TESTS_ENABLED
using System;
using System.Reflection;
using System.Threading;
using NUnit.Framework;
using StreamVideo.Core.StatefulModels.Tracks;
using Unity.WebRTC;
using UnityEngine;
using UnityEngine.UI;
using Object = UnityEngine.Object;
using UiImage = UnityEngine.UIElements.Image;

namespace StreamVideo.Tests.Editor
{
/// <summary>
/// Tests for <see cref="StreamVideoTrack"/> render targets.
/// A sending <see cref="VideoStreamTrack"/> has a stable destination texture until its source size changes.
/// </summary>
internal sealed class StreamVideoTrackTests
{
[SetUp]
public void SetUp()
{
_uiImage = new UiImage();
_rawHost = new GameObject("StreamVideoTrackTests");
_rawImage = _rawHost.AddComponent<RawImage>();
EnsureWebRtcSyncContext();

try
{
_source = CreateTexture(160, 90);
_mediaTrack = new VideoStreamTrack(_source);
_track = new StreamVideoTrack(_mediaTrack);
}
catch (Exception exception)
{
Assert.Ignore(
"A sending VideoStreamTrack cannot be constructed in this Editor session (" +
exception.GetType().Name + ": " + exception.Message +
"). WebRTC.Context is created on assembly reload and is not publicly initializable.");
}
}

[TearDown]
public void TearDown()
{
_track?.Dispose();
_mediaTrack?.Dispose();
DestroyTexture(_source);
DestroyTexture(_replacement);
if (_rawHost != null)
{
Object.DestroyImmediate(_rawHost);
}
}

[Test]
public void When_ui_toolkit_render_target_set_expect_image_receives_texture()
{
_track.SetRenderTarget(_uiImage);

_track.Update();

Assert.That(_uiImage.image, Is.SameAs(_mediaTrack.Texture),
"The UI Toolkit image should show the track texture after Update.");
Assert.That(_uiImage.image.width, Is.GreaterThan(0),
"The received texture should have a non-zero width.");
}

[Test]
public void When_retarget_to_raw_image_expect_ui_toolkit_updates_stop()
{
_track.SetRenderTarget(_uiImage);
_track.Update();
var firstTexture = _mediaTrack.Texture;

_track.SetRenderTarget(_rawImage);
_replacement = CreateTexture(320, 180);
_mediaTrack.ReplaceSourceTexture(_replacement);
_track.Update();

Assert.That(_mediaTrack.Texture, Is.Not.SameAs(firstTexture),
"A source size change should replace the sending texture instance.");
Assert.That(_rawImage.texture, Is.SameAs(_mediaTrack.Texture),
"The RawImage should receive the new texture after retargeting.");
Assert.That(_uiImage.image, Is.SameAs(firstTexture),
"The UI Toolkit image should stop updating after a RawImage target is set.");
}

[Test]
public void When_retarget_to_ui_toolkit_expect_raw_image_updates_stop()
{
_track.SetRenderTarget(_rawImage);
_track.Update();
var firstTexture = _mediaTrack.Texture;

_track.SetRenderTarget(_uiImage);
_replacement = CreateTexture(320, 180);
_mediaTrack.ReplaceSourceTexture(_replacement);
_track.Update();

Assert.That(_uiImage.image, Is.SameAs(_mediaTrack.Texture),
"The UI Toolkit image should receive the new texture after retargeting.");
Assert.That(_rawImage.texture, Is.SameAs(firstTexture),
"The RawImage should stop updating after a UI Toolkit target is set.");
}

[Test]
public void When_set_render_target_null_expect_argument_null_exception()
{
Assert.Throws<ArgumentNullException>(() => _track.SetRenderTarget((RawImage)null),
"A null RawImage should be rejected.");
Assert.Throws<ArgumentNullException>(() => _track.SetRenderTarget((UiImage)null),
"A null UI Toolkit image should be rejected.");
}

[Test]
public void When_track_disposed_expect_ui_toolkit_image_cleared()
{
_track.SetRenderTarget(_uiImage);
_track.Update();
Assert.That(_uiImage.image, Is.SameAs(_mediaTrack.Texture),
"Precondition: the image shows this track before dispose.");

_track.Dispose();
_track = null;

Assert.That(_uiImage.image, Is.Null,
"Dispose should clear the UI Toolkit image when it still shows this track's texture.");
}

[Test]
public void When_disposed_track_image_shows_another_track_expect_texture_kept()
{
var otherSource = CreateTexture(192, 108);
VideoStreamTrack otherMedia = null;
StreamVideoTrack otherTrack = null;
try
{
otherMedia = new VideoStreamTrack(otherSource);
otherTrack = new StreamVideoTrack(otherMedia);
_track.SetRenderTarget(_uiImage);
_track.Update();
otherTrack.SetRenderTarget(_uiImage);
otherTrack.Update();

_track.Dispose();
_track = null;

Assert.That(_uiImage.image, Is.SameAs(otherMedia.Texture),
"Dispose should not clear an image that another track has since taken over.");
}
finally
{
otherTrack?.Dispose();
otherMedia?.Dispose();
DestroyTexture(otherSource);
}
}

// Edit Mode does not run RuntimeInitializeOnLoadMethod, so WebRTC's sync context stays null
// and disposing a track throws. Play Mode installs the real context. This only fills the gap.
private static void EnsureWebRtcSyncContext()
{
var field = typeof(WebRTC).GetField("s_syncContext", BindingFlags.NonPublic | BindingFlags.Static);
if (field == null || field.GetValue(null) != null)
{
return;
}

field.SetValue(null, new InlineSynchronizationContext());
}

private sealed class InlineSynchronizationContext : SynchronizationContext
{
public override void Post(SendOrPostCallback callback, object state) => callback(state);

public override void Send(SendOrPostCallback callback, object state) => callback(state);
}

private static RenderTexture CreateTexture(int width, int height)
{
var format = WebRTC.GetSupportedGraphicsFormat(SystemInfo.graphicsDeviceType);
var texture = new RenderTexture(width, height, 0, format);
texture.Create();
return texture;
}

private static void DestroyTexture(RenderTexture texture)
{
if (texture == null)
{
return;
}

texture.Release();
Object.DestroyImmediate(texture);
}

private StreamVideoTrack _track;
private VideoStreamTrack _mediaTrack;
private RenderTexture _source;
private RenderTexture _replacement;
private GameObject _rawHost;
private RawImage _rawImage;
private UiImage _uiImage;
}
}
#endif
11 changes: 11 additions & 0 deletions Packages/StreamVideo/Tests/Editor/StreamVideoTrackTests.cs.meta

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading
Loading