// %BANNER_BEGIN%
// ---------------------------------------------------------------------
// %COPYRIGHT_BEGIN%
// Copyright (c) (2018-2022) Magic Leap, Inc. All Rights Reserved.
// Use of this file is governed by the Software License Agreement, located here: https://www.magicleap.com/software-license-agreement-ml2
// Terms and conditions applicable to third-party materials accompanying this distribution may also be found in the top-level NOTICE file appearing herein.
// %COPYRIGHT_END%
// ---------------------------------------------------------------------
// %BANNER_END%
namespace UnityEngine.XR.MagicLeap
{
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Text;
using UnityEngine.XR.MagicLeap.Native;
///
/// MLWebRTC class contains the API to interface with the
/// WebRTC C API.
///
public partial class MLWebRTC
{
///
/// Class that represents a connection used by the MLWebRTC API.
///
public partial class PeerConnection
{
///
/// A map of the remote media streams for the connection, keys media stream ids.
///
private Dictionary remoteMediaStreams = new Dictionary();
///
/// A list of the local media stream tracks for the connection.
///
private List localMediaStreamTracks = new List();
///
/// A list of the remote data channels for the connection.
///
private List remoteDataChannels = new List();
///
/// A list of the local data channels for the connection.
///
private List localDataChannels = new List();
///
/// The handle for this managed object.
///
private GCHandle gcHandle;
///
/// Initializes a new instance of the class.
///
internal PeerConnection()
{
}
///
/// Delegate describing the callback necessary to monitor errors.
///
/// The connection the event was invoked on.
/// The error message.
public delegate void OnErrorDelegate(MLWebRTC.PeerConnection connection, string message);
///
/// Delegate describing the callback necessary to monitor if a connection has been made.
///
/// The connection the event was invoked on.
public delegate void OnConnectedDelegate(MLWebRTC.PeerConnection connection);
///
/// Delegate describing the callback necessary to monitor if a disconnection has been made.
///
/// The connection the event was invoked on.
public delegate void OnDisconnectedDelegate(MLWebRTC.PeerConnection connection);
///
/// A delegate that describes the requirements of the OnTrackAddedDelegate callback.
///
/// The media stream associated with the added track.
/// The track that was added to the connection.
public delegate void OnTrackAddedMultipleStreamsDelegate(List mediaStreams, MLWebRTC.MediaStream.Track addedTrack);
///
/// A delegate that describes the requirements of the OnTrackRemovedDelegate callback.
///
/// The media stream associated with the removed track.
/// The track that was removed from the connection.
public delegate void OnTrackRemovedMultipleStreamsDelegate(List mediaStreams, MLWebRTC.MediaStream.Track removedTrack);
///
/// A delegate that describes the requirements of the OnDataChannelReceivedDelegate callback.
///
/// The connection the event was invoked on.
/// The data channel that was added to the connection.
public delegate void OnDataChannelReceivedDelegate(MLWebRTC.PeerConnection connection, MLWebRTC.DataChannel dataChannel);
///
/// Delegate describing the callback necessary to monitor when an offer is sent.
///
/// The connection the event was invoked on.
/// The json of the offer sent.
public delegate void OnLocalOfferCreatedDelegate(MLWebRTC.PeerConnection connection, string sdpSend);
///
/// Delegate describing the callback necessary to monitor when an answer to an offer is sent.
///
/// The connection the event was invoked on.
/// The json of the answer sent.
public delegate void OnLocalAnswerCreatedDelegate(MLWebRTC.PeerConnection connection, string sendAnswer);
///
/// Delegate describing the callback necessary to monitor when an ice candidate is sent.
///
/// The connection the event was invoked on.
/// The ice candidate that was sent.
public delegate void OnLocalIceCandidateFoundDelegate(MLWebRTC.PeerConnection connection, MLWebRTC.IceCandidate iceCandidate);
///
/// Delegate describing the callback necessary to notify that all ICEs have been gathered.
///
/// The connection the event was invoked on.
public delegate void OnIceGatheringCompletedDelegate(MLWebRTC.PeerConnection connection);
///
/// Event invoked for when an error occurs.
///
public event OnErrorDelegate OnError = delegate { };
///
/// Event invoked for when a connection between a local and remote peer is established.
///
public event OnConnectedDelegate OnConnected = delegate { };
///
/// Event invoked for when a connection between a local and remote peer is destroyed.
///
public event OnDisconnectedDelegate OnDisconnected = delegate { };
///
/// Event invoked for when a track is added to a connection.
///
public event OnTrackAddedMultipleStreamsDelegate OnTrackAddedMultipleStreams = delegate { };
///
/// Event invoked for when a track is removed from a connection.
///
public event OnTrackRemovedMultipleStreamsDelegate OnTrackRemovedMultipleStreams = delegate { };
///
/// Event invoked for when a data channel is received by a connection.
///
public event OnDataChannelReceivedDelegate OnDataChannelReceived = delegate { };
///
/// Event invoked for when an offer is sent.
///
public event OnLocalOfferCreatedDelegate OnLocalOfferCreated = delegate { };
///
/// Event invoked for when an answer is sent.
///
public event OnLocalAnswerCreatedDelegate OnLocalAnswerCreated = delegate { };
///
/// Event invoked for when an ice candidate is sent.
///
public event OnLocalIceCandidateFoundDelegate OnLocalIceCandidateFound = delegate { };
///
/// Event invoked for when ice gathering completed.
///
public event OnIceGatheringCompletedDelegate OnIceGatheringCompleted = delegate { };
///
/// Gets the ice servers used for the connection.
///
public MLWebRTC.IceServer[] IceServers { get; private set; }
///
/// Gets the ice candidate chosen by the connection.
///
public MLWebRTC.IceCandidate IceCandidate { get; private set; }
///
/// Gets the handle of the connection.
///
internal ulong Handle { get; private set; }
///
/// Gets the remote streams map of the connection.
///
internal Dictionary RemoteMediaStreams { get => this.remoteMediaStreams; }
///
/// Gets the local tracks map of the connection.
///
internal List LocalMediaStreamTracks { get => this.localMediaStreamTracks; }
///
/// Gets the remote data channels map of the connection.
///
internal List RemoteDataChannels { get => this.remoteDataChannels; }
///
/// Gets the local data channels map of the connection.
///
internal List LocalDataChannels { get => this.localDataChannels; }
///
/// Creates an initialized PeerConnection object.
///
/// The ice servers to create the connection with.
/// The MLResult object of the inner platform call(s).
/// An initialized PeerConnection object.
public static PeerConnection CreateRemote(MLWebRTC.IceServer[] iceServers, out MLResult result)
{
var permResult = MLPermissions.CheckPermission(MLPermission.Internet);
if (!MLResult.DidNativeCallSucceed(permResult.Result, nameof(CreateRemote)))
{
MLPluginLog.Error($"{nameof(CreateRemote)} requires missing permission {MLPermission.Internet}");
result = MLResult.Create(MLResult.Code.PermissionDenied);
return null;
}
List connections = MLWebRTC.Instance.connections;
MLResult.Code resultCode = NativeBindings.CreateRemoteConnection(iceServers, out PeerConnection connection);
MLResult.DidNativeCallSucceed(resultCode, nameof(NativeBindings.CreateRemoteConnection));
result = MLResult.Create(resultCode);
if (result.IsOk)
{
connections.Add(connection);
}
return connection;
}
///
/// Creates an initialized PeerConnection object with a forward proxy configuration.
///
/// The ice servers to create the connection with.
/// Configuration for the forward proxy.
/// The MLResult object of the inner platform call(s).
/// An initialized PeerConnection object.
public static PeerConnection CreateRemote(MLWebRTC.IceServer[] iceServers, MLWebRTC.ProxyConfig proxyConfig, out MLResult result)
{
var permResult = MLPermissions.CheckPermission(MLPermission.Internet);
if (!MLResult.DidNativeCallSucceed(permResult.Result, nameof(CreateRemote)))
{
MLPluginLog.Error($"{nameof(CreateRemote)} requires missing permission {MLPermission.Internet}");
result = MLResult.Create(MLResult.Code.PermissionDenied);
return null;
}
List connections = MLWebRTC.Instance.connections;
MLResult.Code resultCode = NativeBindings.CreateRemoteConnection(iceServers, proxyConfig, out PeerConnection connection);
MLResult.DidNativeCallSucceed(resultCode, nameof(NativeBindings.CreateRemoteConnection));
result = MLResult.Create(resultCode);
if (result.IsOk)
{
connections.Add(connection);
}
return connection;
}
///
/// Gets if the connection is currently connected or not.
///
/// True if connected.
///
/// MLResult.Result will be MLResult.Code.Ok if destroying all handles was successful.
/// MLResult.Result will be MLResult.Code.WebRTCResultInstanceNotCreated if MLWebRTC instance was not created.
/// MLResult.Result will be MLResult.Code.WebRTCResultMismatchingHandle if an incorrect handle was sent.
/// MLResult.Result will be MLResult.Code.InvalidParam if an invalid parameter was passed.
///
public MLResult IsConnected(out bool connected)
{
if (!MagicLeapNativeBindings.MLHandleIsValid(this.Handle))
{
connected = false;
return MLResult.Create(MLResult.Code.InvalidParam, "Handle is invalid.");
}
bool isConnected = false;
MLResult.Code resultCode = NativeBindings.MLWebRTCConnectionIsConnected(this.Handle, out isConnected);
MLResult.DidNativeCallSucceed(resultCode, nameof(NativeBindings.MLWebRTCConnectionIsConnected));
connected = isConnected;
return MLResult.Create(resultCode);
}
///
/// Gets if the connection has failed or not.
///
/// True if connection has failed.
///
/// MLResult.Result will be MLResult.Code.Ok if destroying all handles was successful.
/// MLResult.Result will be MLResult.Code.WebRTCResultInstanceNotCreated if MLWebRTC instance was not created.
/// MLResult.Result will be MLResult.Code.WebRTCResultMismatchingHandle if an incorrect handle was sent.
/// MLResult.Result will be MLResult.Code.InvalidParam if an invalid parameter was passed.
///
public MLResult HasFailed(out bool failed)
{
if (!MagicLeapNativeBindings.MLHandleIsValid(this.Handle))
{
failed = false;
return MLResult.Create(MLResult.Code.InvalidParam, "Handle is invalid.");
}
bool isFailed = false;
MLResult.Code resultCode = NativeBindings.MLWebRTCConnectionHasFailed(this.Handle, out isFailed);
MLResult.DidNativeCallSucceed(resultCode, nameof(NativeBindings.MLWebRTCConnectionHasFailed));
failed = isFailed;
return MLResult.Create(resultCode);
}
///
/// Creates the offer for the connection.
///
///
/// MLResult.Result will be MLResult.Code.Ok if destroying all handles was successful.
/// MLResult.Result will be MLResult.Code.WebRTCResultInstanceNotCreated if MLWebRTC instance was not created.
/// MLResult.Result will be MLResult.Code.WebRTCResultMismatchingHandle if an incorrect handle was sent.
///
public MLResult CreateOffer()
{
if (!MagicLeapNativeBindings.MLHandleIsValid(this.Handle))
{
return MLResult.Create(MLResult.Code.InvalidParam, "Handle is invalid.");
}
MLResult.Code resultCode = NativeBindings.MLWebRTCConnectionCreateOffer(this.Handle);
MLResult.DidNativeCallSucceed(resultCode, nameof(NativeBindings.MLWebRTCConnectionCreateOffer));
return MLResult.Create(resultCode);
}
///
/// Sets the remote offer for the connection.
///
/// The offer to set.
///
/// MLResult.Result will be MLResult.Code.Ok if destroying all handles was successful.
/// MLResult.Result will be MLResult.Code.WebRTCResultInstanceNotCreated if MLWebRTC instance was not created.
/// MLResult.Result will be MLResult.Code.WebRTCResultMismatchingHandle if an incorrect handle was sent.
/// MLResult.Result will be MLResult.Code.InvalidParam if an invalid parameter was passed.
///
public MLResult SetRemoteOffer(string remoteOffer)
{
if (!MagicLeapNativeBindings.MLHandleIsValid(this.Handle))
{
return MLResult.Create(MLResult.Code.InvalidParam, "Handle is invalid.");
}
MLResult.Code resultCode = NativeBindings.MLWebRTCConnectionSetRemoteOffer(this.Handle, remoteOffer);
MLResult.DidNativeCallSucceed(resultCode, nameof(NativeBindings.MLWebRTCConnectionSetRemoteOffer));
return MLResult.Create(resultCode);
}
///
/// Sets the remote answer for the connection.
///
/// The answer to set.
///
/// MLResult.Result will be MLResult.Code.Ok if destroying all handles was successful.
/// MLResult.Result will be MLResult.Code.WebRTCResultInstanceNotCreated if MLWebRTC instance was not created.
/// MLResult.Result will be MLResult.Code.WebRTCResultMismatchingHandle if an incorrect handle was sent.
/// MLResult.Result will be MLResult.Code.InvalidParam if an invalid parameter was passed.
///
public MLResult SetRemoteAnswer(string remoteAnswer)
{
if (!MagicLeapNativeBindings.MLHandleIsValid(this.Handle))
{
return MLResult.Create(MLResult.Code.InvalidParam, "Handle is invalid.");
}
MLResult.Code resultCode = NativeBindings.MLWebRTCConnectionSetRemoteAnswer(this.Handle, remoteAnswer);
MLResult.DidNativeCallSucceed(resultCode, nameof(NativeBindings.MLWebRTCConnectionSetRemoteAnswer));
return MLResult.Create(resultCode);
}
///
/// Adds an ice candidate to the connection.
///
/// The ice candidate to add.
///
/// MLResult.Result will be MLResult.Code.Ok if destroying all handles was successful.
/// MLResult.Result will be MLResult.Code.WebRTCResultInstanceNotCreated if MLWebRTC instance was not created.
/// MLResult.Result will be MLResult.Code.WebRTCResultMismatchingHandle if an incorrect handle was sent.
/// MLResult.Result will be MLResult.Code.InvalidParam if an invalid parameter was passed.
///
public MLResult AddRemoteIceCandidate(MLWebRTC.IceCandidate iceCandidate)
{
if (!MagicLeapNativeBindings.MLHandleIsValid(this.Handle))
{
return MLResult.Create(MLResult.Code.InvalidParam, "Handle is invalid.");
}
NativeBindings.MLWebRTCConnectionIceCandidate nativeIceCandidate = new NativeBindings.MLWebRTCConnectionIceCandidate();
nativeIceCandidate.Data = iceCandidate;
MLResult.Code resultCode = NativeBindings.MLWebRTCConnectionAddRemoteIceCandidate(this.Handle, in nativeIceCandidate);
if (MLResult.DidNativeCallSucceed(resultCode, nameof(NativeBindings.MLWebRTCConnectionAddRemoteIceCandidate)))
{
this.IceCandidate = iceCandidate;
}
return MLResult.Create(resultCode);
}
///
/// Destroys the connection.
///
///
/// MLResult.Result will be MLResult.Code.Ok if destroying all handles was successful.
/// MLResult.Result will be MLResult.Code.WebRTCResultInstanceNotCreated if MLWebRTC instance was not created.
/// MLResult.Result will be MLResult.Code.WebRTCResultMismatchingHandle if an incorrect handle was sent.
///
public MLResult Destroy()
{
if (!MagicLeapNativeBindings.MLHandleIsValid(this.Handle))
{
return MLResult.Create(MLResult.Code.InvalidParam, "Handle is invalid.");
}
MLResult.Code resultCode = MLResult.Code.Ok;
// Remove local tracks from this connection.
foreach (MLWebRTC.MediaStream.Track mediaStreamTrack in this.localMediaStreamTracks)
{
// Don't call this.RemoveLocalTrack() because that modifies the list we're iterating on.
var result = NativeBindings.MLWebRTCConnectionRemoveLocalSourceTrack(this.Handle, mediaStreamTrack.Handle);
MLResult.DidNativeCallSucceed(result, nameof(NativeBindings.MLWebRTCConnectionRemoveLocalSourceTrack));
}
// Invalidate the handles of any remote sources and remove the media stream id from the set of unique ids.
foreach (MLWebRTC.MediaStream mediaStream in this.remoteMediaStreams.Values)
{
foreach (MediaStream.Track remoteTrack in mediaStream.Tracks)
{
remoteTrack.Cleanup();
}
mediaStream.Tracks.Clear();
mediaStream.ParentConnections.Remove(this);
foreach (MLWebRTC.MediaStream.Track track in mediaStream.Tracks)
{
track.Handle = MagicLeapNativeBindings.InvalidHandle;
}
}
// Destroy local data channels.
foreach (MLWebRTC.DataChannel dataChannel in this.localDataChannels)
{
dataChannel.Destroy();
}
// Destroy this connection.
resultCode = NativeBindings.MLWebRTCConnectionDestroy(this.Handle);
this.Handle = MagicLeapNativeBindings.InvalidHandle;
this.localMediaStreamTracks.Clear();
this.remoteMediaStreams.Clear();
this.remoteDataChannels.Clear();
this.localDataChannels.Clear();
this.IceServers = null;
this.gcHandle.Free();
MLWebRTC.Instance.connections.Remove(this);
return MLResult.Create(resultCode);
}
///
/// Adds a local track to the connection.
///
/// Track to add to the connection.
///
/// MLResult.Result will be MLResult.Code.Ok if destroying all handles was successful.
/// MLResult.Result will be MLResult.Code.WebRTCResultInstanceNotCreated if MLWebRTC instance was not created.
/// MLResult.Result will be MLResult.Code.WebRTCResultMismatchingHandle if an incorrect handle was sent.
///
public MLResult AddLocalTrack(MLWebRTC.MediaStream.Track trackToAdd)
{
if (!MagicLeapNativeBindings.MLHandleIsValid(this.Handle))
{
return MLResult.Create(MLResult.Code.InvalidParam, "Handle is invalid.");
}
if (trackToAdd == null)
{
return MLResult.Create(MLResult.Code.InvalidParam, "Track is null.");
}
if (this.localMediaStreamTracks.Contains(trackToAdd))
{
return MLResult.Create(MLResult.Code.InvalidParam, "Connection already has this track.");
}
string[] streamIds = new string[trackToAdd.Streams.Count];
for (int i = 0; i < streamIds.Length; ++i)
{
streamIds[i] = trackToAdd.Streams[i].Id;
trackToAdd.Streams[i].ParentConnections.Add(this);
}
NativeBindings.MLWebRTCTrackInfo trackInfo = new NativeBindings.MLWebRTCTrackInfo(streamIds, trackToAdd.Id);
MLResult.Code resultCode = NativeBindings.MLWebRTCConnectionAddLocalSourceTrackEx(Handle, trackToAdd.Handle, ref trackInfo);
trackInfo.FreeUnmanagedMemory();
if (MLResult.DidNativeCallSucceed(resultCode, nameof(NativeBindings.MLWebRTCConnectionAddLocalSourceTrackEx)))
{
localMediaStreamTracks.Add(trackToAdd);
}
return MLResult.Create(resultCode);
}
///
/// Removes a local track to the connection.
///
/// Track to remove to the connection.
///
/// MLResult.Result will be MLResult.Code.Ok if destroying all handles was successful.
/// MLResult.Result will be MLResult.Code.WebRTCResultInstanceNotCreated if MLWebRTC instance was not created.
/// MLResult.Result will be MLResult.Code.WebRTCResultMismatchingHandle if an incorrect handle was sent.
///
public MLResult RemoveLocalTrack(MLWebRTC.MediaStream.Track trackToRemove)
{
if (!MagicLeapNativeBindings.MLHandleIsValid(this.Handle))
{
return MLResult.Create(MLResult.Code.InvalidParam, "Handle is invalid.");
}
if (trackToRemove == null)
{
return MLResult.Create(MLResult.Code.InvalidParam, "Track is null.");
}
if (!this.localMediaStreamTracks.Contains(trackToRemove))
{
return MLResult.Create(MLResult.Code.InvalidParam, "Connection does not have this track.");
}
MLResult.Code resultCode = MLWebRTC.PeerConnection.NativeBindings.MLWebRTCConnectionRemoveLocalSourceTrack(this.Handle, trackToRemove.Handle);
MLResult.DidNativeCallSucceed(resultCode, nameof(MLWebRTC.PeerConnection.NativeBindings.MLWebRTCConnectionRemoveLocalSourceTrack));
this.localMediaStreamTracks.Remove(trackToRemove);
foreach (MLWebRTC.MediaStream stream in trackToRemove.Streams)
{
stream.ParentConnections.Remove(this);
}
return MLResult.Create(resultCode);
}
public bool ContainsTrack(MediaStream.Track track)
{
return localMediaStreamTracks != null && localMediaStreamTracks.Contains(track);
}
}
}
}