Esempio n. 1
0
        /// <summary>
        /// Uninitialize the underlying WebRTC library, effectively cleaning up the allocated peer connection.
        /// </summary>
        /// <remarks>
        /// <see cref="Peer"/> will be <c>null</c> afterward.
        /// </remarks>
        public void Uninitialize()
        {
            if ((_nativePeer != null) && _nativePeer.Initialized)
            {
                // Fire signals before doing anything else to allow listeners to clean-up,
                // including un-registering any callback and remove any track from the connection.
                OnShutdown.Invoke();

                // Prevent publicly accessing the native peer after it has been deinitialized.
                // This does not prevent systems caching a reference from accessing it, but it
                // is their responsibility to check that the peer is initialized.
                Peer = null;

                // Detach all transceivers. This prevents senders/receivers from trying to access
                // them during their clean-up sequence, as transceivers are about to be destroyed
                // by the native implementation.
                foreach (var mediaLine in _mediaLines)
                {
                    mediaLine.UnpairTransceiver();
                }

                // Close the connection and release native resources.
                _nativePeer.Dispose();
                _nativePeer = null;
            }
        }
        /// <summary>
        /// Initialize the underlying WebRTC peer connection.
        /// </summary>
        /// <remarks>
        /// This method is asynchronous and completes its task when the initializing completed.
        /// On successful completion, it also trigger the <see cref="OnInitialized"/> event.
        /// Note however that this completion is free-threaded and complete immediately when the
        /// underlying peer connection is initialized, whereas any <see cref="OnInitialized"/>
        /// event handler is invoked when control returns to the main Unity app thread. The former
        /// is faster, but does not allow accessing the underlying peer connection because it
        /// returns before <see cref="OnPostInitialize"/> executed. Therefore it is generally
        /// recommended to listen to the <see cref="OnInitialized"/> event, and ignore the returned
        /// <see xref="System.Threading.Tasks.Task"/> object.
        /// </remarks>
        private async Task <WebRTC.PeerConnection> InitializePluginAsync(CancellationToken token)
        {
            // Ensure Android binding is initialized before accessing the native implementation
            Android.Initialize();

#if UNITY_WSA && !UNITY_EDITOR
            if (Library.UsedAudioDeviceModule == AudioDeviceModule.LegacyModule)
            {
                // Preventing access to audio crashes the ADM1 at startup and the entire application.
                bool permissionGranted = await UwpUtils.RequestAccessAsync(StreamingCaptureMode.Audio);

                if (!permissionGranted)
                {
                    return(null);
                }
            }
#endif
            // Create the peer connection managed wrapper and its native implementation
            var nativePeer = new WebRTC.PeerConnection();

            nativePeer.AudioTrackAdded +=
                (RemoteAudioTrack track) =>
            {
                // Tracks will be output by AudioReceivers, so avoid outputting them twice.
                track.OutputToDevice(false);
            };

            Debug.Log("Initializing WebRTC Peer Connection...");
            var config = new PeerConnectionConfiguration();
            foreach (var server in IceServers)
            {
                config.IceServers.Add(new IceServer
                {
                    Urls         = { server.ToString() },
                    TurnUserName = IceUsername,
                    TurnPassword = IceCredential
                });
            }

            try
            {
                await nativePeer.InitializeAsync(config, token);

                return(nativePeer);
            }
            catch (OperationCanceledException canceled) { throw canceled; }
            catch (Exception ex)
            {
                nativePeer.Dispose();
                token.ThrowIfCancellationRequested();

                EnsureIsMainAppThread();
                var errorMessage = new StringBuilder();
                errorMessage.Append("WebRTC plugin initializing failed. See full log for exception details.\n");
                errorMessage.Append($"Exception: {ex.Message}");
                OnError.Invoke(errorMessage.ToString());
                throw ex;
            }
        }
Esempio n. 3
0
        /// <summary>
        /// Uninitialize the underlying WebRTC library, effectively cleaning up the allocated peer connection.
        /// </summary>
        /// <remarks>
        /// <see cref="Peer"/> will be <c>null</c> afterward.
        /// </remarks>
        public void Uninitialize()
        {
            if ((_nativePeer != null) && _nativePeer.Initialized)
            {
                // Fire signals before doing anything else to allow listeners to clean-up,
                // including un-registering any callback and remove any track from the connection.
                OnShutdown.Invoke();
                Signaler.OnPeerUninitializing(this);

                // Prevent publicly accessing the native peer after it has been deinitialized.
                // This does not prevent systems caching a reference from accessing it, but it
                // is their responsibility to check that the peer is initialized.
                Peer = null;

                // Close the connection and release native resources.
                _nativePeer.Dispose();
            }
        }