public async Task SctpError()
        {
            // Setup
            var config = new PeerConnectionConfiguration();
            var pc1    = new PeerConnection();
            var pc2    = new PeerConnection();
            await pc1.InitializeAsync(config);

            await pc2.InitializeAsync(config);

            pc1.LocalSdpReadytoSend += async(string type, string sdp) =>
            {
                await pc2.SetRemoteDescriptionAsync(type, sdp);

                if (type == "offer")
                {
                    pc2.CreateAnswer();
                }
            };
            pc2.LocalSdpReadytoSend += async(string type, string sdp) =>
            {
                await pc1.SetRemoteDescriptionAsync(type, sdp);

                if (type == "offer")
                {
                    pc1.CreateAnswer();
                }
            };
            pc1.IceCandidateReadytoSend += (string candidate, int sdpMlineindex, string sdpMid)
                                           => pc2.AddIceCandidate(sdpMid, sdpMlineindex, candidate);
            pc2.IceCandidateReadytoSend += (string candidate, int sdpMlineindex, string sdpMid)
                                           => pc1.AddIceCandidate(sdpMid, sdpMlineindex, candidate);

            // Connect
            {
                var c1 = new ManualResetEventSlim(false);
                var c2 = new ManualResetEventSlim(false);
                pc1.Connected += () => c1.Set();
                pc2.Connected += () => c2.Set();
                Assert.True(pc1.CreateOffer());
                Assert.True(c1.Wait(TimeSpan.FromSeconds(60.0)));
                Assert.True(c2.Wait(TimeSpan.FromSeconds(60.0)));
                Assert.True(pc1.IsConnected);
                Assert.True(pc1.IsConnected);
            }

            // Try to add a data channel. This should fail because SCTP was not negotiated.
            Assert.ThrowsAsync <SctpNotNegotiatedException>(async() => await pc1.AddDataChannelAsync("dummy", false, false));
            Assert.ThrowsAsync <SctpNotNegotiatedException>(async() => await pc1.AddDataChannelAsync(42, "dummy", false, false));

            // Clean-up
            pc1.Close();
            pc1.Dispose();
            pc2.Close();
            pc2.Dispose();
        }
Exemplo n.º 2
0
        public async void PeerConnectionLocalConnect()
        {
            using (var pc1 = new PeerConnection())
            {
                await pc1.InitializeAsync();

                using (var pc2 = new PeerConnection())
                {
                    await pc2.InitializeAsync();

                    // Prepare SDP event handlers
                    pc1.LocalSdpReadytoSend += async(SdpMessage message) =>
                    {
                        await pc2.SetRemoteDescriptionAsync(message);

                        if (message.Type == SdpMessageType.Offer)
                        {
                            pc2.CreateAnswer();
                        }
                    };
                    pc2.LocalSdpReadytoSend += async(SdpMessage message) =>
                    {
                        await pc1.SetRemoteDescriptionAsync(message);

                        if (message.Type == SdpMessageType.Offer)
                        {
                            pc1.CreateAnswer();
                        }
                    };
                    pc1.IceCandidateReadytoSend += (IceCandidate candidate) => pc2.AddIceCandidate(candidate);
                    pc2.IceCandidateReadytoSend += (IceCandidate candidate) => pc1.AddIceCandidate(candidate);

                    // Connect
                    var conn1 = new ManualResetEventSlim(initialState: false);
                    var conn2 = new ManualResetEventSlim(initialState: false);
                    pc1.Connected += () => conn1.Set();
                    pc2.Connected += () => conn2.Set();
                    pc1.CreateOffer();
                    WaitForSdpExchangeCompleted(conn1, conn2);

                    pc1.Close();
                    pc2.Close();
                }
            }
        }
        protected async Task MakeICECall(PeerConnection pc1, PeerConnection pc2)
        {
            pc1.LocalSdpReadytoSend += (string type, string sdp) =>
            {
                pc2.SetRemoteDescription(type, sdp);
                if (type == "offer")
                {
                    pc2.CreateAnswer();
                }
            };
            pc2.LocalSdpReadytoSend += (string type, string sdp) =>
            {
                pc1.SetRemoteDescription(type, sdp);
                if (type == "offer")
                {
                    pc1.CreateAnswer();
                }
            };
            pc1.IceCandidateReadytoSend += (string candidate, int sdpMlineindex, string sdpMid) =>
            {
                pc2.AddIceCandidate(sdpMid, sdpMlineindex, candidate);
            };
            pc2.IceCandidateReadytoSend += (string candidate, int sdpMlineindex, string sdpMid) =>
            {
                pc1.AddIceCandidate(sdpMid, sdpMlineindex, candidate);
            };

            var pcConfig = new PeerConnectionConfiguration();
            await pc1.InitializeAsync(pcConfig);

            await pc2.InitializeAsync(pcConfig);

            var ev1 = new ManualResetEventSlim(initialState: false);
            var ev2 = new ManualResetEventSlim(initialState: false);

            pc1.Connected += () => ev1.Set();
            pc2.Connected += () => ev2.Set();
            pc1.CreateOffer();
            ev1.Wait(millisecondsTimeout: 5000);
            ev2.Wait(millisecondsTimeout: 5000);
        }
Exemplo n.º 4
0
 public void CreateAnswer(Callback <RTCSessionDescription> callback)
 {
     MustNotDisposed();
     _peerConnectionImpl.CreateAnswer(callback);
 }
Exemplo n.º 5
0
        private async void Window_Initialized(object sender, EventArgs e)
        {
            _peerConnection = new PeerConnection();
            var config = new PeerConnectionConfiguration
            {
                IceServers = new List <IceServer> {
                    new IceServer {
                        Urls = { "turn:35.193.0.31:3478" }, TurnPassword = "******", TurnUserName = "******"
                    }
                }
            };

            _peerConnection.Connected += () =>
            {
                Debugger.Log(0, "", "Peerconnection: DONE");
            };
            _peerConnection.IceStateChanged += (IceConnectionState newState) =>
            {
                Debugger.Log(0, "", $"ICE state: {newState}\n");
            };

            await _peerConnection.InitializeAsync(config);

            _dc = await _peerConnection.AddDataChannelAsync(14, "vzgo", true, true);

            Debugger.Log(0, "", "Peer connection initialized successfully.\n");

            _peerConnection.LocalSdpReadytoSend     += Peer_LocalSdpReadytoSendAsync;
            _peerConnection.IceCandidateReadytoSend += Peer_IceCandidateReadytoSend;
            _hubConnection = new HubConnectionBuilder()
                             .WithUrl(new Uri(SignallerConstants.SignallerUrl))
                             .AddJsonProtocol()
                             .WithAutomaticReconnect(new[] { TimeSpan.Zero, TimeSpan.Zero, TimeSpan.FromSeconds(10) })
                             .Build();


            _hubConnection.On <string>("Message", (message) =>
            {
                var msg = JsonConvert.DeserializeObject <SignallingMessage>(message);
                switch (msg.MessageType)
                {
                case SignallingMessage.WireMessageType.Offer:
                    _peerConnection.SetRemoteDescription("offer", msg.Data);
                    _peerConnection.CreateAnswer();
                    break;

                case SignallingMessage.WireMessageType.Answer:
                    _peerConnection.SetRemoteDescription("answer", msg.Data);
                    break;

                case SignallingMessage.WireMessageType.Ice:
                    var parts = msg.Data.Split(new string[] { msg.IceDataSeparator },
                                               StringSplitOptions.RemoveEmptyEntries);
                    // Note the inverted arguments for historical reasons.
                    // 'candidate' is last in AddIceCandidate(), but first in the message.
                    string sdpMid     = parts[2];
                    int sdpMlineindex = int.Parse(parts[1]);
                    string candidate  = parts[0];
                    _peerConnection.AddIceCandidate(sdpMid, sdpMlineindex, candidate);
                    break;
                }
            });

            await _hubConnection.StartAsync();

            await _hubConnection.InvokeAsync("JoinRoom", SignallerConstants.RoomName);
        }
Exemplo n.º 6
0
        static async Task Main(string[] args)
        {
            DataChannel dataChannel = null;

            try
            {
                // Create a new peer connection automatically disposed at the end of the program
                using var pc = new PeerConnection();

                // Initialize the connection with a STUN server to allow remote access
                var config = new PeerConnectionConfiguration
                {
                    IceServers = new List <IceServer> {
                        new IceServer {
                            Urls = { "stun:stun.l.google.com:19302" }
                        }
                    }
                };
                await pc.InitializeAsync(config);

                Console.WriteLine("Peer connection initialized.");

                Console.WriteLine("Opening data channel");
                dataChannel = await pc.AddDataChannelAsync("data", true, true);

                // Setup signaling
                Console.WriteLine("Starting signaling...");
                var signaler = new NamedPipeSignaler.NamedPipeSignaler(pc, "testpipe");
                signaler.SdpMessageReceived += (string type, string sdp) => {
                    pc.SetRemoteDescription(type, sdp);
                    if (type == "offer")
                    {
                        pc.CreateAnswer();
                    }
                };
                signaler.IceCandidateReceived += (string sdpMid, int sdpMlineindex, string candidate) => {
                    pc.AddIceCandidate(sdpMid, sdpMlineindex, candidate);
                };
                await signaler.StartAsync();

                // Start peer connection
                pc.Connected       += () => { Console.WriteLine("PeerConnection: connected."); };
                pc.IceStateChanged += (IceConnectionState newState) => { Console.WriteLine($"ICE state: {newState}"); };

                pc.DataChannelAdded += (DataChannel c) =>
                {
                    Console.WriteLine("DataChannel added");

                    c.MessageReceived += (byte[] _msg) =>
                    {
                        Console.WriteLine("received {0} bytes", _msg.Length);
                    };
                };

                if (signaler.IsClient)
                {
                    Console.WriteLine("Connecting to remote peer...");
                    pc.CreateOffer();
                }
                else
                {
                    Console.WriteLine("Waiting for offer from remote peer...");
                }

                Console.WriteLine("Press a 'S' to send data. 'Esc' to exit ...");

                ConsoleKeyInfo key;

                while ((key = Console.ReadKey(true)).Key != ConsoleKey.Escape)
                {
                    if (key.Key == ConsoleKey.S)
                    {
                        Console.WriteLine("Sending data");
                        dataChannel.SendMessage(new byte[3000]);
                    }
                }
                signaler.Stop();
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }

            Console.WriteLine("Program termined.");
        }
Exemplo n.º 7
0
        static async Task Main()
        {
            try
            {
                Console.WriteLine("Starting...");
                //create and Initialize capture object to record audio
                var           waveFormat = new WaveFormat(44100, 32, 2, AudioEncoding.MpegLayer3);
                WasapiCapture capture    = new WasapiCapture(true, AudioClientShareMode.Shared, 100, waveFormat);

                //initialize the selected device for recording
                capture.Initialize();
                //fill ice servers here
                List <string> urls = new List <string>();


                using var pc = new PeerConnection();

                var config = new PeerConnectionConfiguration
                {
                    IceServers = new List <IceServer> {
                        new IceServer {
                            Urls = urls,
                        }
                    }
                    ,
                    BundlePolicy = BundlePolicy.MaxBundle
                };

                await pc.InitializeAsync(config);

                Console.WriteLine("Peer connection initialized.");


                //create audio transceiver
                Transceiver transceiver = pc.AddTransceiver(MediaKind.Audio);
                transceiver.DesiredDirection = Transceiver.Direction.ReceiveOnly;
                Console.WriteLine("Create audio transceiver ...");

                DataChannel chanel = await pc.AddDataChannelAsync("Data", true, true, cancellationToken : default);

                string url = "";
                WebSocketSharp.WebSocket signaling = new WebSocket(url);
                signaling.SslConfiguration.EnabledSslProtocols = System.Security.Authentication.SslProtocols.Tls12;

                signaling.OnMessage += async(sender, message) =>
                {
                    try
                    {
                        //response messages may differ from service provider to another, adjust WebsocketResponse object accordingly
                        var messageObject = JsonConvert.DeserializeObject <WebsocketResponse>(message.Data);
                        var mess          = new SdpMessage {
                            Content = messageObject.Data.Sdp, Type = SdpMessage.StringToType("answer")
                        };

                        if (!string.IsNullOrEmpty(mess.Content))
                        {
                            Console.WriteLine("Sdpmessage: {0}, Type: {1}", mess.Content, mess.Type);
                            await pc.SetRemoteDescriptionAsync(mess);

                            if (mess.Type == SdpMessageType.Answer)
                            {
                                bool res = pc.CreateAnswer();
                                Console.WriteLine("Answer created? {0}", res);
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e.Message);
                    }
                };


                signaling.OnError += (sender, e) =>
                {
                    Console.WriteLine(e.Message, e.Exception);
                };
                signaling.OnOpen += (sender, e) =>
                {
                    pc.CreateOffer();
                    Console.WriteLine("open");
                };
                signaling.Connect();

                transceiver.Associated += (tranciever) =>
                {
                    Console.WriteLine("Transivier: {0}, {1}", tranciever.Name, tranciever.StreamIDs);
                };



                pc.LocalSdpReadytoSend += (SdpMessage message) =>
                {
                    Console.WriteLine(message.Content);

                    //modify the offer message according to your need

                    var data = new
                    {
                        streamId = "",
                        sdp      = message.Content
                    };
                    var payload = JsonConvert.SerializeObject(new
                    {
                        type    = "cmd",
                        transId = 0,
                        name    = "view",
                        data    = data
                    });
                    Console.WriteLine("Sdp offer to send: " + payload);

                    signaling.Send(payload);
                };


                pc.RenegotiationNeeded += () =>
                {
                    Console.WriteLine("Regotiation needed");
                };

                //when a remote audio track is added, start recording
                pc.AudioTrackAdded += (RemoteAudioTrack track) =>
                {
                    //create a wavewriter to write the data to
                    WaveWriter w = new WaveWriter("audio.mp3", capture.WaveFormat);

                    //setup an eventhandler to receive the recorded data
                    capture.DataAvailable += (s, e) =>
                    {
                        //save the recorded audio
                        w.Write(e.Data, e.Offset, e.ByteCount);
                    };

                    //start recording
                    capture.Start();
                    //this should output the sound
                    track.OutputToDevice(true);

                    //track.AudioFrameReady += (AudioFrame frame) =>
                    //{
                    //you can print anything here if you want to make sure that's you're recieving audio

                    //};
                };


                pc.Connected += () =>
                {
                    Console.WriteLine("Connected");
                    Console.WriteLine(pc.DataChannels.Count);
                };
                pc.IceStateChanged += (IceConnectionState newState) =>
                {
                    Console.WriteLine($"ICE state: {newState}");
                };

                Console.WriteLine("Press enter to stop");
                Console.ReadLine();

                //stop recording
                capture.Stop();
                pc.Close();
                signaling.Close();
                Console.WriteLine("Program termined.");
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }
Exemplo n.º 8
0
        public async Task <string> InitiateCallRTC()
        {
            var list = new List <string>();

            list.Add(this.Configuration.GetSection("Key")["iceServer"]);
            AudioTrackSource microphoneSource = null;
            LocalAudioTrack  localAudioTrack  = null;
            Transceiver      audioTransceiver = null;

            var iceServer = new IceServer
            {
                Urls         = list,
                TurnPassword = this.Configuration.GetSection("Key")["turnPwd"],
                TurnUserName = this.Configuration.GetSection("Key")["turnUser"]
            };

            var serverList = new List <IceServer>();

            serverList.Add(iceServer);
            var connectionConfig = new PeerConnectionConfiguration {
                IceServers       = serverList,
                IceTransportType = IceTransportType.All,
                BundlePolicy     = BundlePolicy.Balanced,
                SdpSemantic      = SdpSemantic.UnifiedPlan
            };
            var connection = new PeerConnection();
            await connection.InitializeAsync(connectionConfig);

            microphoneSource = await DeviceAudioTrackSource.CreateAsync();

            var audioTrackConfig = new LocalAudioTrackInitConfig
            {
                trackName = "microphone_track"
            };

            localAudioTrack = LocalAudioTrack.CreateFromSource(microphoneSource, audioTrackConfig);

            audioTransceiver = connection.AddTransceiver(MediaKind.Audio);
            audioTransceiver.LocalAudioTrack  = localAudioTrack;
            audioTransceiver.DesiredDirection = Transceiver.Direction.SendReceive;

            var signaler = new NamedPipeSignaler.NamedPipeSignaler(connection, "testpipe");

            connection.Connected += () => {
                Console.WriteLine("PeerConnection: connected.");
            };

            signaler.SdpMessageReceived += async(SdpMessage message) =>
            {
                // Note: we use 'await' to ensure the remote description is applied
                // before calling CreateAnswer(). Failing to do so will prevent the
                // answer from being generated, and the connection from establishing.
                await connection.SetRemoteDescriptionAsync(message);

                if (message.Type == SdpMessageType.Offer)
                {
                    connection.CreateAnswer();
                }
            };

            await signaler.StartAsync();

            signaler.IceCandidateReceived += (IceCandidate candidate) => {
                connection.AddIceCandidate(candidate);
            };

            connection.IceStateChanged += (IceConnectionState newState) => {
                Console.WriteLine($"ICE state: {newState}");
            };

            if (signaler.IsClient)
            {
                Console.WriteLine("Connecting to remote peer...");
                connection.CreateOffer();
            }
            else
            {
                Console.WriteLine("Waiting for offer from remote peer...");
            }

            return(connection.IsConnected + "-" + connection.Name + "-");
        }