33 | */
34 | #endregion
35 |
36 | using System;
37 |
38 | namespace WebSocketSharp
39 | {
40 | ///
41 | /// Represents the event data for the event.
42 | ///
43 | ///
44 | ///
45 | /// That event occurs when the gets an error.
46 | ///
47 | ///
48 | /// If you would like to get the error message, you should access
49 | /// the property.
50 | ///
51 | ///
52 | /// And if the error is due to an exception, you can get it by accessing
53 | /// the property.
54 | ///
55 | ///
56 | public class ErrorEventArgs : EventArgs
57 | {
58 | #region Private Fields
59 |
60 | private Exception _exception;
61 | private string _message;
62 |
63 | #endregion
64 |
65 | #region Internal Constructors
66 |
67 | internal ErrorEventArgs (string message)
68 | : this (message, null)
69 | {
70 | }
71 |
72 | internal ErrorEventArgs (string message, Exception exception)
73 | {
74 | _message = message;
75 | _exception = exception;
76 | }
77 |
78 | #endregion
79 |
80 | #region Public Properties
81 |
82 | ///
83 | /// Gets the exception that caused the error.
84 | ///
85 | ///
86 | /// An instance that represents the cause of
87 | /// the error if it is due to an exception; otherwise, .
88 | ///
89 | public Exception Exception {
90 | get {
91 | return _exception;
92 | }
93 | }
94 |
95 | ///
96 | /// Gets the error message.
97 | ///
98 | ///
99 | /// A that represents the error message.
100 | ///
101 | public string Message {
102 | get {
103 | return _message;
104 | }
105 | }
106 |
107 | #endregion
108 | }
109 | }
110 |
--------------------------------------------------------------------------------
/UnityWebRTC/Assets/WebSocketSharp/WebSocketException.cs:
--------------------------------------------------------------------------------
1 | #region License
2 | /*
3 | * WebSocketException.cs
4 | *
5 | * The MIT License
6 | *
7 | * Copyright (c) 2012-2016 sta.blockhead
8 | *
9 | * Permission is hereby granted, free of charge, to any person obtaining a copy
10 | * of this software and associated documentation files (the "Software"), to deal
11 | * in the Software without restriction, including without limitation the rights
12 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
13 | * copies of the Software, and to permit persons to whom the Software is
14 | * furnished to do so, subject to the following conditions:
15 | *
16 | * The above copyright notice and this permission notice shall be included in
17 | * all copies or substantial portions of the Software.
18 | *
19 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
22 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
24 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
25 | * THE SOFTWARE.
26 | */
27 | #endregion
28 |
29 | using System;
30 |
31 | namespace WebSocketSharp
32 | {
33 | ///
34 | /// The exception that is thrown when a fatal error occurs in
35 | /// the WebSocket communication.
36 | ///
37 | public class WebSocketException : Exception
38 | {
39 | #region Private Fields
40 |
41 | private CloseStatusCode _code;
42 |
43 | #endregion
44 |
45 | #region Internal Constructors
46 |
47 | internal WebSocketException ()
48 | : this (CloseStatusCode.Abnormal, null, null)
49 | {
50 | }
51 |
52 | internal WebSocketException (Exception innerException)
53 | : this (CloseStatusCode.Abnormal, null, innerException)
54 | {
55 | }
56 |
57 | internal WebSocketException (string message)
58 | : this (CloseStatusCode.Abnormal, message, null)
59 | {
60 | }
61 |
62 | internal WebSocketException (CloseStatusCode code)
63 | : this (code, null, null)
64 | {
65 | }
66 |
67 | internal WebSocketException (string message, Exception innerException)
68 | : this (CloseStatusCode.Abnormal, message, innerException)
69 | {
70 | }
71 |
72 | internal WebSocketException (CloseStatusCode code, Exception innerException)
73 | : this (code, null, innerException)
74 | {
75 | }
76 |
77 | internal WebSocketException (CloseStatusCode code, string message)
78 | : this (code, message, null)
79 | {
80 | }
81 |
82 | internal WebSocketException (
83 | CloseStatusCode code, string message, Exception innerException
84 | )
85 | : base (message ?? code.GetMessage (), innerException)
86 | {
87 | _code = code;
88 | }
89 |
90 | #endregion
91 |
92 | #region Public Properties
93 |
94 | ///
95 | /// Gets the status code indicating the cause of the exception.
96 | ///
97 | ///
98 | /// One of the enum values that represents
99 | /// the status code indicating the cause of the exception.
100 | ///
101 | public CloseStatusCode Code {
102 | get {
103 | return _code;
104 | }
105 | }
106 |
107 | #endregion
108 | }
109 | }
110 |
--------------------------------------------------------------------------------
/UnityWebRTC/Assets/WebSocketSharp/CloseEventArgs.cs:
--------------------------------------------------------------------------------
1 | #region License
2 | /*
3 | * CloseEventArgs.cs
4 | *
5 | * The MIT License
6 | *
7 | * Copyright (c) 2012-2019 sta.blockhead
8 | *
9 | * Permission is hereby granted, free of charge, to any person obtaining a copy
10 | * of this software and associated documentation files (the "Software"), to deal
11 | * in the Software without restriction, including without limitation the rights
12 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
13 | * copies of the Software, and to permit persons to whom the Software is
14 | * furnished to do so, subject to the following conditions:
15 | *
16 | * The above copyright notice and this permission notice shall be included in
17 | * all copies or substantial portions of the Software.
18 | *
19 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
22 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
24 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
25 | * THE SOFTWARE.
26 | */
27 | #endregion
28 |
29 | using System;
30 |
31 | namespace WebSocketSharp
32 | {
33 | ///
34 | /// Represents the event data for the event.
35 | ///
36 | ///
37 | ///
38 | /// That event occurs when the WebSocket connection has been closed.
39 | ///
40 | ///
41 | /// If you would like to get the reason for the connection close, you should
42 | /// access the or property.
43 | ///
44 | ///
45 | public class CloseEventArgs : EventArgs
46 | {
47 | #region Private Fields
48 |
49 | private bool _clean;
50 | private PayloadData _payloadData;
51 |
52 | #endregion
53 |
54 | #region Internal Constructors
55 |
56 | internal CloseEventArgs (PayloadData payloadData, bool clean)
57 | {
58 | _payloadData = payloadData;
59 | _clean = clean;
60 | }
61 |
62 | internal CloseEventArgs (ushort code, string reason, bool clean)
63 | {
64 | _payloadData = new PayloadData (code, reason);
65 | _clean = clean;
66 | }
67 |
68 | #endregion
69 |
70 | #region Public Properties
71 |
72 | ///
73 | /// Gets the status code for the connection close.
74 | ///
75 | ///
76 | /// A that represents the status code for
77 | /// the connection close if present.
78 | ///
79 | public ushort Code {
80 | get {
81 | return _payloadData.Code;
82 | }
83 | }
84 |
85 | ///
86 | /// Gets the reason for the connection close.
87 | ///
88 | ///
89 | /// A that represents the reason for
90 | /// the connection close if present.
91 | ///
92 | public string Reason {
93 | get {
94 | return _payloadData.Reason;
95 | }
96 | }
97 |
98 | ///
99 | /// Gets a value indicating whether the connection has been closed cleanly.
100 | ///
101 | ///
102 | /// true if the connection has been closed cleanly; otherwise,
103 | /// false.
104 | ///
105 | public bool WasClean {
106 | get {
107 | return _clean;
108 | }
109 | }
110 |
111 | #endregion
112 | }
113 | }
114 |
--------------------------------------------------------------------------------
/UnityWebRTC/Assets/WebSocketSharp/Net/HttpHeaderInfo.cs:
--------------------------------------------------------------------------------
1 | #region License
2 | /*
3 | * HttpHeaderInfo.cs
4 | *
5 | * The MIT License
6 | *
7 | * Copyright (c) 2013-2020 sta.blockhead
8 | *
9 | * Permission is hereby granted, free of charge, to any person obtaining a copy
10 | * of this software and associated documentation files (the "Software"), to deal
11 | * in the Software without restriction, including without limitation the rights
12 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
13 | * copies of the Software, and to permit persons to whom the Software is
14 | * furnished to do so, subject to the following conditions:
15 | *
16 | * The above copyright notice and this permission notice shall be included in
17 | * all copies or substantial portions of the Software.
18 | *
19 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
22 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
24 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
25 | * THE SOFTWARE.
26 | */
27 | #endregion
28 |
29 | using System;
30 |
31 | namespace WebSocketSharp.Net
32 | {
33 | internal class HttpHeaderInfo
34 | {
35 | #region Private Fields
36 |
37 | private string _headerName;
38 | private HttpHeaderType _headerType;
39 |
40 | #endregion
41 |
42 | #region Internal Constructors
43 |
44 | internal HttpHeaderInfo (string headerName, HttpHeaderType headerType)
45 | {
46 | _headerName = headerName;
47 | _headerType = headerType;
48 | }
49 |
50 | #endregion
51 |
52 | #region Internal Properties
53 |
54 | internal bool IsMultiValueInRequest {
55 | get {
56 | var headerType = _headerType & HttpHeaderType.MultiValueInRequest;
57 |
58 | return headerType == HttpHeaderType.MultiValueInRequest;
59 | }
60 | }
61 |
62 | internal bool IsMultiValueInResponse {
63 | get {
64 | var headerType = _headerType & HttpHeaderType.MultiValueInResponse;
65 |
66 | return headerType == HttpHeaderType.MultiValueInResponse;
67 | }
68 | }
69 |
70 | #endregion
71 |
72 | #region Public Properties
73 |
74 | public string HeaderName {
75 | get {
76 | return _headerName;
77 | }
78 | }
79 |
80 | public HttpHeaderType HeaderType {
81 | get {
82 | return _headerType;
83 | }
84 | }
85 |
86 | public bool IsRequest {
87 | get {
88 | var headerType = _headerType & HttpHeaderType.Request;
89 |
90 | return headerType == HttpHeaderType.Request;
91 | }
92 | }
93 |
94 | public bool IsResponse {
95 | get {
96 | var headerType = _headerType & HttpHeaderType.Response;
97 |
98 | return headerType == HttpHeaderType.Response;
99 | }
100 | }
101 |
102 | #endregion
103 |
104 | #region Public Methods
105 |
106 | public bool IsMultiValue (bool response)
107 | {
108 | var headerType = _headerType & HttpHeaderType.MultiValue;
109 |
110 | if (headerType != HttpHeaderType.MultiValue)
111 | return response ? IsMultiValueInResponse : IsMultiValueInRequest;
112 |
113 | return response ? IsResponse : IsRequest;
114 | }
115 |
116 | public bool IsRestricted (bool response)
117 | {
118 | var headerType = _headerType & HttpHeaderType.Restricted;
119 |
120 | if (headerType != HttpHeaderType.Restricted)
121 | return false;
122 |
123 | return response ? IsResponse : IsRequest;
124 | }
125 |
126 | #endregion
127 | }
128 | }
129 |
--------------------------------------------------------------------------------
/python/cli.py:
--------------------------------------------------------------------------------
1 | import argparse
2 | import asyncio
3 | import logging
4 | import math
5 | from collections import deque
6 |
7 | import cv2
8 | import numpy
9 | import logging
10 |
11 | from aiortc import (
12 | RTCIceCandidate,
13 | RTCPeerConnection,
14 | RTCSessionDescription,
15 | VideoStreamTrack,
16 | )
17 | from aiortc.contrib.signaling import BYE, add_signaling_arguments, create_signaling
18 |
19 | from receiver import OpenCVReceiver
20 | from signaler import UnityTcpSignaling
21 |
22 | _LOGGER = logging.getLogger("mr.webrtc.python")
23 | _LOGGER.addHandler(logging.NullHandler())
24 |
25 |
26 | async def run(pc, player, receiver, signaling, role, queue):
27 | def add_tracks():
28 | if player and player.audio:
29 | pc.addTrack(player.audio)
30 |
31 | if player and player.video:
32 | pc.addTrack(player.video)
33 | else:
34 | pc.addTrack(FlagVideoStreamTrack())
35 |
36 | @pc.on("track")
37 | def on_track(track):
38 | _LOGGER.info("Receiving %s" % track.kind)
39 | receiver.addTrack(track)
40 |
41 | # connect signaling
42 | _LOGGER.info("Waiting for signaler connection ...")
43 | await signaling.connect()
44 |
45 | # consume signaling
46 | while True:
47 | obj = await signaling.receive()
48 | # if obj is not None:
49 | # print(obj)
50 |
51 | if isinstance(obj, RTCSessionDescription):
52 | await pc.setRemoteDescription(obj)
53 | await receiver.start()
54 |
55 | async def check_queue():
56 | while True:
57 | if len(queue):
58 | img = queue.pop()
59 | queue.clear()
60 | try:
61 | cv2.imshow("hello", img)
62 | cv2.waitKey(1)
63 | except Exception as e:
64 | print(e)
65 | await asyncio.sleep(0.05)
66 |
67 | asyncio.create_task(check_queue())
68 |
69 | if obj.type == "offer":
70 | # send answer
71 | # add_tracks()
72 | await pc.setLocalDescription(await pc.createAnswer())
73 | await signaling.send(pc.localDescription)
74 | elif isinstance(obj, RTCIceCandidate):
75 | await pc.addIceCandidate(obj)
76 | elif obj is BYE:
77 | print("Exiting")
78 | break
79 |
80 |
81 | if __name__ == "__main__":
82 | import time
83 |
84 | parser = argparse.ArgumentParser(description="Video stream from the command line")
85 | parser.add_argument("--verbose", "-v", action="count")
86 | parser.add_argument("--host", "-ip", help="ip address of signaler/sender instance")
87 | parser.add_argument("--port", "-p", help="port of signaler/sender instance")
88 | add_signaling_arguments(parser)
89 | args = parser.parse_args()
90 |
91 | if args.verbose:
92 | logging.basicConfig(level=logging.DEBUG)
93 | else:
94 | logging.basicConfig(level=logging.WARN)
95 | _LOGGER.setLevel(level=logging.INFO)
96 |
97 | host = args.host or "localhost"
98 | port = args.port or 9095
99 |
100 | # create signaling and peer connection
101 | signaling = UnityTcpSignaling(host=host, port=port)
102 | pc = RTCPeerConnection()
103 |
104 | player = None
105 | frame_queue = deque()
106 | receiver = OpenCVReceiver(queue=frame_queue)
107 | # run event loop
108 | loop = asyncio.get_event_loop()
109 | try:
110 | loop.run_until_complete(
111 | run(
112 | pc=pc,
113 | player=player,
114 | receiver=receiver,
115 | signaling=signaling,
116 | role="answer",
117 | queue=frame_queue,
118 | )
119 | )
120 | except KeyboardInterrupt:
121 | pass
122 | finally:
123 | # cleanup
124 | _LOGGER.info("Shutting down receiver and peer connection.")
125 | loop.run_until_complete(receiver.stop())
126 | loop.run_until_complete(signaling.close())
127 | loop.run_until_complete(pc.close())
128 |
--------------------------------------------------------------------------------
/UnityWebRTC/Assets/WebSocketSharp/Net/AuthenticationBase.cs:
--------------------------------------------------------------------------------
1 | #region License
2 | /*
3 | * AuthenticationBase.cs
4 | *
5 | * The MIT License
6 | *
7 | * Copyright (c) 2014 sta.blockhead
8 | *
9 | * Permission is hereby granted, free of charge, to any person obtaining a copy
10 | * of this software and associated documentation files (the "Software"), to deal
11 | * in the Software without restriction, including without limitation the rights
12 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
13 | * copies of the Software, and to permit persons to whom the Software is
14 | * furnished to do so, subject to the following conditions:
15 | *
16 | * The above copyright notice and this permission notice shall be included in
17 | * all copies or substantial portions of the Software.
18 | *
19 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
22 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
24 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
25 | * THE SOFTWARE.
26 | */
27 | #endregion
28 |
29 | using System;
30 | using System.Collections.Specialized;
31 | using System.Text;
32 |
33 | namespace WebSocketSharp.Net
34 | {
35 | internal abstract class AuthenticationBase
36 | {
37 | #region Private Fields
38 |
39 | private AuthenticationSchemes _scheme;
40 |
41 | #endregion
42 |
43 | #region Internal Fields
44 |
45 | internal NameValueCollection Parameters;
46 |
47 | #endregion
48 |
49 | #region Protected Constructors
50 |
51 | protected AuthenticationBase (AuthenticationSchemes scheme, NameValueCollection parameters)
52 | {
53 | _scheme = scheme;
54 | Parameters = parameters;
55 | }
56 |
57 | #endregion
58 |
59 | #region Public Properties
60 |
61 | public string Algorithm {
62 | get {
63 | return Parameters["algorithm"];
64 | }
65 | }
66 |
67 | public string Nonce {
68 | get {
69 | return Parameters["nonce"];
70 | }
71 | }
72 |
73 | public string Opaque {
74 | get {
75 | return Parameters["opaque"];
76 | }
77 | }
78 |
79 | public string Qop {
80 | get {
81 | return Parameters["qop"];
82 | }
83 | }
84 |
85 | public string Realm {
86 | get {
87 | return Parameters["realm"];
88 | }
89 | }
90 |
91 | public AuthenticationSchemes Scheme {
92 | get {
93 | return _scheme;
94 | }
95 | }
96 |
97 | #endregion
98 |
99 | #region Internal Methods
100 |
101 | internal static string CreateNonceValue ()
102 | {
103 | var src = new byte[16];
104 | var rand = new Random ();
105 | rand.NextBytes (src);
106 |
107 | var res = new StringBuilder (32);
108 | foreach (var b in src)
109 | res.Append (b.ToString ("x2"));
110 |
111 | return res.ToString ();
112 | }
113 |
114 | internal static NameValueCollection ParseParameters (string value)
115 | {
116 | var res = new NameValueCollection ();
117 | foreach (var param in value.SplitHeaderValue (',')) {
118 | var i = param.IndexOf ('=');
119 | var name = i > 0 ? param.Substring (0, i).Trim () : null;
120 | var val = i < 0
121 | ? param.Trim ().Trim ('"')
122 | : i < param.Length - 1
123 | ? param.Substring (i + 1).Trim ().Trim ('"')
124 | : String.Empty;
125 |
126 | res.Add (name, val);
127 | }
128 |
129 | return res;
130 | }
131 |
132 | internal abstract string ToBasicString ();
133 |
134 | internal abstract string ToDigestString ();
135 |
136 | #endregion
137 |
138 | #region Public Methods
139 |
140 | public override string ToString ()
141 | {
142 | return _scheme == AuthenticationSchemes.Basic
143 | ? ToBasicString ()
144 | : _scheme == AuthenticationSchemes.Digest
145 | ? ToDigestString ()
146 | : String.Empty;
147 | }
148 |
149 | #endregion
150 | }
151 | }
152 |
--------------------------------------------------------------------------------
/web/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
97 |
98 |
99 |
100 |
101 |
102 |
103 |
104 |
105 |
106 |
107 | Remote Address:
108 |
109 |
110 |
--------------------------------------------------------------------------------
/UnityWebRTC/Assets/Scripts/TCPSignaler.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft Corporation.
2 | // Licensed under the MIT License.
3 |
4 | using System;
5 | using System.Collections.Concurrent;
6 | using System.IO;
7 | using System.Net;
8 | using System.Net.Sockets;
9 | using System.Threading.Tasks;
10 | using Newtonsoft.Json;
11 | using Newtonsoft.Json.Linq;
12 | using UnityEngine;
13 |
14 | public class TCPSignaler : Signaler
15 | {
16 | ///
17 | /// Client pipe for sending data. This is connected to the remote signaler's server pipe.
18 | ///
19 | private TcpClient _client = null;
20 |
21 | ///
22 | /// Server pipe for receiving data. This is connected to the remote signaler's client pipe.
23 | ///
24 | private TcpListener _server = null;
25 |
26 | private NetworkStream _stream = null;
27 | private StreamReader _streamReader = null;
28 | private StreamWriter _streamWriter = null;
29 | private int _serverPort;
30 |
31 | private readonly BlockingCollection _outgoingMessages = new BlockingCollection(new ConcurrentQueue());
32 |
33 | public TCPSignaler(int port)
34 | {
35 | _serverPort = port;
36 | ClientDisconnected += OnConnectionClosed;
37 | }
38 |
39 | public void WaitForTCPConnection()
40 | {
41 | Debug.Log("Waiting for the remote peer to connect...");
42 | _client = _server.AcceptTcpClient();
43 | _stream = _client.GetStream();
44 | _streamReader = new StreamReader(_stream);
45 | _streamWriter = new StreamWriter(_stream);
46 | _streamWriter.AutoFlush = true;
47 | Debug.Log("Remote peer connected.");
48 | Console.WriteLine("Signaler connection established.");
49 | ClientConnected?.Invoke();
50 | _ = Task.Factory.StartNew(ProcessIncomingMessagesQueue, TaskCreationOptions.LongRunning);
51 | _ = Task.Factory.StartNew(WriteOutgoingMessages, TaskCreationOptions.LongRunning);
52 | }
53 |
54 | public void OnConnectionClosed()
55 | {
56 | _streamReader?.Dispose();
57 | _streamWriter?.Dispose();
58 | _stream?.Dispose();
59 | _client?.Close();
60 | _ = Task.Factory.StartNew(WaitForTCPConnection, TaskCreationOptions.LongRunning);
61 | }
62 |
63 | public override void Start()
64 | {
65 | _server = new TcpListener(IPAddress.Any, _serverPort);
66 | _server.Start();
67 | Debug.Log("Created tcp server;");
68 | _ = Task.Factory.StartNew(WaitForTCPConnection, TaskCreationOptions.LongRunning);
69 | }
70 |
71 | public override void Stop()
72 | {
73 | _outgoingMessages.CompleteAdding();
74 | _outgoingMessages.Dispose();
75 | _server.Stop();
76 | }
77 |
78 | private void ProcessIncomingMessagesQueue()
79 | {
80 | // ReadLine() will block while waiting for a new line
81 | JsonSerializer serializer = new JsonSerializer();
82 | using (StreamReader sr = new StreamReader(_stream))
83 | using (JsonReader reader = new JsonTextReader(sr))
84 | {
85 | reader.SupportMultipleContent = true;
86 | while (reader.Read())
87 | {
88 | var json = serializer.Deserialize(reader);
89 | //Console.WriteLine($"[<-] {json}");
90 | ProcessIncomingMessage(json);
91 | }
92 | }
93 | Console.WriteLine("Finished processing messages");
94 | }
95 |
96 | private void WriteOutgoingMessages()
97 | {
98 | // GetConsumingEnumerable() will block when no message is available,
99 | // until CompleteAdding() is called from Stop().
100 | foreach (var msg in _outgoingMessages.GetConsumingEnumerable())
101 | {
102 | _streamWriter.WriteLine(JsonConvert.SerializeObject(msg, Formatting.None));
103 | }
104 | }
105 |
106 | protected override void SendMessage(JObject json)
107 | {
108 | try
109 | {
110 | // Enqueue the message and immediately return, to avoid blocking the
111 | // WebRTC signaler thread which is typically invoking this method through
112 | // the PeerConnection signaling callbacks.
113 | Console.WriteLine($"[->] {json}");
114 | _outgoingMessages.Add(json);
115 | }
116 | catch (Exception e)
117 | {
118 | Console.WriteLine($"Exception: {e.Message}");
119 | Environment.Exit(-1);
120 | }
121 | }
122 | }
123 |
--------------------------------------------------------------------------------
/UnityWebRTC/Assets/WebSocketSharp/Net/HttpListenerException.cs:
--------------------------------------------------------------------------------
1 | #region License
2 | /*
3 | * HttpListenerException.cs
4 | *
5 | * This code is derived from System.Net.HttpListenerException.cs of Mono
6 | * (http://www.mono-project.com).
7 | *
8 | * The MIT License
9 | *
10 | * Copyright (c) 2005 Novell, Inc. (http://www.novell.com)
11 | * Copyright (c) 2012-2014 sta.blockhead
12 | *
13 | * Permission is hereby granted, free of charge, to any person obtaining a copy
14 | * of this software and associated documentation files (the "Software"), to deal
15 | * in the Software without restriction, including without limitation the rights
16 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
17 | * copies of the Software, and to permit persons to whom the Software is
18 | * furnished to do so, subject to the following conditions:
19 | *
20 | * The above copyright notice and this permission notice shall be included in
21 | * all copies or substantial portions of the Software.
22 | *
23 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
24 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
25 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
26 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
27 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
28 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
29 | * THE SOFTWARE.
30 | */
31 | #endregion
32 |
33 | #region Authors
34 | /*
35 | * Authors:
36 | * - Gonzalo Paniagua Javier
37 | */
38 | #endregion
39 |
40 | using System;
41 | using System.ComponentModel;
42 | using System.Runtime.Serialization;
43 |
44 | namespace WebSocketSharp.Net
45 | {
46 | ///
47 | /// The exception that is thrown when a gets an error
48 | /// processing an HTTP request.
49 | ///
50 | [Serializable]
51 | public class HttpListenerException : Win32Exception
52 | {
53 | #region Protected Constructors
54 |
55 | ///
56 | /// Initializes a new instance of the class from
57 | /// the specified and .
58 | ///
59 | ///
60 | /// A that contains the serialized object data.
61 | ///
62 | ///
63 | /// A that specifies the source for the deserialization.
64 | ///
65 | protected HttpListenerException (
66 | SerializationInfo serializationInfo, StreamingContext streamingContext)
67 | : base (serializationInfo, streamingContext)
68 | {
69 | }
70 |
71 | #endregion
72 |
73 | #region Public Constructors
74 |
75 | ///
76 | /// Initializes a new instance of the class.
77 | ///
78 | public HttpListenerException ()
79 | {
80 | }
81 |
82 | ///
83 | /// Initializes a new instance of the class
84 | /// with the specified .
85 | ///
86 | ///
87 | /// An that identifies the error.
88 | ///
89 | public HttpListenerException (int errorCode)
90 | : base (errorCode)
91 | {
92 | }
93 |
94 | ///
95 | /// Initializes a new instance of the class
96 | /// with the specified and .
97 | ///
98 | ///
99 | /// An that identifies the error.
100 | ///
101 | ///
102 | /// A that describes the error.
103 | ///
104 | public HttpListenerException (int errorCode, string message)
105 | : base (errorCode, message)
106 | {
107 | }
108 |
109 | #endregion
110 |
111 | #region Public Properties
112 |
113 | ///
114 | /// Gets the error code that identifies the error that occurred.
115 | ///
116 | ///
117 | /// An that identifies the error.
118 | ///
119 | public override int ErrorCode {
120 | get {
121 | return NativeErrorCode;
122 | }
123 | }
124 |
125 | #endregion
126 | }
127 | }
128 |
--------------------------------------------------------------------------------
/UnityWebRTC/README.md:
--------------------------------------------------------------------------------
1 | # UnityWebRTC
2 |
3 | This should not be confused with the official [WebRTC for Unity](https://github.com/Unity-Technologies/com.unity.webrtc).
4 |
5 | This folder contains the preconfigured Unity project which can be opened with Unity (or added via UnityHub). Open the scene `Scenes/SignalerExample`, check the `Launcher` GameObject and the attached `RTCServer` component to configure the video stream resolution and signaler. This should be all that is needed to test it in the Unity Editor. Building and export requires you to change the build target in the build settings from Standalone to Universal Windows Platform.
6 |
7 | The project uses [Microsoft Mixed Reality Toolkit (MRTK)](https://github.com/microsoft/MixedRealityToolkit-Unity), [Microsoft Mixed Reality WebRTC](https://github.com/microsoft/MixedReality-WebRTC) and [Newtonsoft.Json for Unity](https://github.com/jilleJr/Newtonsoft.Json-for-Unity) which are configured as UPM packages.
8 | Make sure to copy the scoped registries and dependencies from `Packages/manifest.json` when you use this code in your project. Additionally, the project includes [WebSocketSharp](https://github.com/sta/websocket-sharp) source code in the `Assets/WebSocketSharp` folder.
9 |
10 |
11 | ## Requirements for WebSocketSignaler
12 |
13 | Before you run the Unity project, you need to create an SSL certificate. Modern browsers do not allow video and/or audio streaming over insecure connections. The whole process is described [here](https://github.com/microsoft/MixedReality-WebRTC/tree/master/examples/TestReceiveAV) but for this project can be summarized as:
14 |
15 | * switch into the project folder `/UnityWebRTC/Assets/StreamingAssets/Certs`
16 | * the file `req.conf` is used to configure the certificate. You need to adapt `CN` and `subjectAltName` if you want to access the stream from somewhere else than `localhost`.
17 | * **in this folder** execute
18 | - `openssl req -config req.conf -x509 -newkey rsa:4096 -keyout localhost_key.pem -out localhost.pem -nodes -days 3650`
19 | - `openssl pkcs12 -export -in localhost.pem -inkey localhost_key.pem -out localhost.pfx.bin -nodes`
20 | - if you have paid close attention, you will have realized that the resulting key hasn't been saved as a `*.pfx` key file (as done in the referenced instruction) but `*.pfx.bin`! It seems that `*.pfx` key files in `StreamingAssets` are not exported into UWP packages. By changing the file ending we can workaround that.
21 | - currently, the unity app expects the name to be `localhost.pfx.bin`. Use that name even if the certificate was generated for another domain and/or IP (or change it in `Assets/Scripts/WebSocketSignaler.cs`)
22 | * If you have chosen the default configuration, you can make Chrome/Chromium accept self-signed certificates for localhost by typing `chrome://flags/#allow-insecure-localhost` into the address bar and enabling that option.
23 | * Alternatively, you can access the `WebSocketSignaler` via `https` instead of `wss` (eg. type `https:\\localhost:9999` into your browser while the project is running) and manually accept the certificate.
24 |
25 | ## Limitations HoloLens 2
26 |
27 | As of 2020-10-16, `Mixed Reality WebRTC` does not support HoloLens 2 builds targeting `ARM64` ([ref](https://github.com/microsoft/MixedReality-WebRTC/issues/414)). `ARM` (32-bit) seems to be [supported](https://github.com/microsoft/MixedReality-WebRTC/issues/235) though.
28 |
29 | ## Usage
30 |
31 | Open `Assets/Scenes/SignalerExample` in Unity and check the `Launcher` GameObject. The `RTCServer` features some settings which can be adjusted:
32 |
33 | * `NeedVideo` -- whether the video stream should be sent
34 | * `NeedAudio` -- whether an audio track should be send
35 | * `VideoWidth`, `VideoHeight` and `VideoFps` should be set to values your WebCam/HoloLens camera is actually supporting. Otherwise the stream might not be initialized successfully. `VideoFps` can be set to 0 to ignore that option.
36 | * `VideoProfileId` -- Some HoloLens2 resolutions are only available via a profile. This project will prompt all found profiles and resolutions when initialized. When `VideoProfileId` is empty, it will be ignored.
37 | * `ConnectionType` -- Should be set to `TCP` or `WebSocket`, depending on the client (TCP: Python, WebSocket: browser) you plan to use
38 | * `UseRemoteStun` -- when enabled, the server `stun.l.google.com:19302` will be promoted to the `PeerConnection`. This might help in cases where server and client cannot reach each other directly.
39 |
40 | ### Tested Resolutions
41 |
42 | #### HoloLens 1 (x86)
43 |
44 | * `1280x720@30fps`
45 | * `896x504@24fps`
46 |
47 | #### HoloLens 2 (ARM)
48 |
49 | * `896x504@15fps`
50 | * `Profile '{6B52B017-42C7-4A21-BFE3-23F009149887},120': 640x360@30fps`
51 |
--------------------------------------------------------------------------------
/UnityWebRTC/Assets/WebSocketSharp/Net/QueryStringCollection.cs:
--------------------------------------------------------------------------------
1 | #region License
2 | /*
3 | * QueryStringCollection.cs
4 | *
5 | * This code is derived from HttpUtility.cs (System.Net) of Mono
6 | * (http://www.mono-project.com).
7 | *
8 | * The MIT License
9 | *
10 | * Copyright (c) 2005-2009 Novell, Inc. (http://www.novell.com)
11 | * Copyright (c) 2018 sta.blockhead
12 | *
13 | * Permission is hereby granted, free of charge, to any person obtaining a copy
14 | * of this software and associated documentation files (the "Software"), to deal
15 | * in the Software without restriction, including without limitation the rights
16 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
17 | * copies of the Software, and to permit persons to whom the Software is
18 | * furnished to do so, subject to the following conditions:
19 | *
20 | * The above copyright notice and this permission notice shall be included in
21 | * all copies or substantial portions of the Software.
22 | *
23 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
24 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
25 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
26 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
27 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
28 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
29 | * THE SOFTWARE.
30 | */
31 | #endregion
32 |
33 | #region Authors
34 | /*
35 | * Authors:
36 | * - Patrik Torstensson
37 | * - Wictor Wilén (decode/encode functions)
38 | * - Tim Coleman
39 | * - Gonzalo Paniagua Javier
40 | */
41 | #endregion
42 |
43 | using System;
44 | using System.Collections.Specialized;
45 | using System.Text;
46 |
47 | namespace WebSocketSharp.Net
48 | {
49 | internal sealed class QueryStringCollection : NameValueCollection
50 | {
51 | #region Public Constructors
52 |
53 | public QueryStringCollection ()
54 | {
55 | }
56 |
57 | public QueryStringCollection (int capacity)
58 | : base (capacity)
59 | {
60 | }
61 |
62 | #endregion
63 |
64 | #region Private Methods
65 |
66 | private static string urlDecode (string s, Encoding encoding)
67 | {
68 | return s.IndexOfAny (new[] { '%', '+' }) > -1
69 | ? HttpUtility.UrlDecode (s, encoding)
70 | : s;
71 | }
72 |
73 | #endregion
74 |
75 | #region Public Methods
76 |
77 | public static QueryStringCollection Parse (string query)
78 | {
79 | return Parse (query, Encoding.UTF8);
80 | }
81 |
82 | public static QueryStringCollection Parse (string query, Encoding encoding)
83 | {
84 | if (query == null)
85 | return new QueryStringCollection (1);
86 |
87 | var len = query.Length;
88 | if (len == 0)
89 | return new QueryStringCollection (1);
90 |
91 | if (query == "?")
92 | return new QueryStringCollection (1);
93 |
94 | if (query[0] == '?')
95 | query = query.Substring (1);
96 |
97 | if (encoding == null)
98 | encoding = Encoding.UTF8;
99 |
100 | var ret = new QueryStringCollection ();
101 |
102 | var components = query.Split ('&');
103 | foreach (var component in components) {
104 | len = component.Length;
105 | if (len == 0)
106 | continue;
107 |
108 | if (component == "=")
109 | continue;
110 |
111 | var i = component.IndexOf ('=');
112 | if (i < 0) {
113 | ret.Add (null, urlDecode (component, encoding));
114 | continue;
115 | }
116 |
117 | if (i == 0) {
118 | ret.Add (null, urlDecode (component.Substring (1), encoding));
119 | continue;
120 | }
121 |
122 | var name = urlDecode (component.Substring (0, i), encoding);
123 |
124 | var start = i + 1;
125 | var val = start < len
126 | ? urlDecode (component.Substring (start), encoding)
127 | : String.Empty;
128 |
129 | ret.Add (name, val);
130 | }
131 |
132 | return ret;
133 | }
134 |
135 | public override string ToString ()
136 | {
137 | var buff = new StringBuilder ();
138 |
139 | foreach (var key in AllKeys)
140 | buff.AppendFormat ("{0}={1}&", key, this[key]);
141 |
142 | if (buff.Length > 0)
143 | buff.Length--;
144 |
145 | return buff.ToString ();
146 | }
147 |
148 | #endregion
149 | }
150 | }
151 |
--------------------------------------------------------------------------------
/UnityWebRTC/Assets/WebSocketSharp/Net/HttpStreamAsyncResult.cs:
--------------------------------------------------------------------------------
1 | #region License
2 | /*
3 | * HttpStreamAsyncResult.cs
4 | *
5 | * This code is derived from HttpStreamAsyncResult.cs (System.Net) of Mono
6 | * (http://www.mono-project.com).
7 | *
8 | * The MIT License
9 | *
10 | * Copyright (c) 2005 Novell, Inc. (http://www.novell.com)
11 | * Copyright (c) 2012-2015 sta.blockhead
12 | *
13 | * Permission is hereby granted, free of charge, to any person obtaining a copy
14 | * of this software and associated documentation files (the "Software"), to deal
15 | * in the Software without restriction, including without limitation the rights
16 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
17 | * copies of the Software, and to permit persons to whom the Software is
18 | * furnished to do so, subject to the following conditions:
19 | *
20 | * The above copyright notice and this permission notice shall be included in
21 | * all copies or substantial portions of the Software.
22 | *
23 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
24 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
25 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
26 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
27 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
28 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
29 | * THE SOFTWARE.
30 | */
31 | #endregion
32 |
33 | #region Authors
34 | /*
35 | * Authors:
36 | * - Gonzalo Paniagua Javier
37 | */
38 | #endregion
39 |
40 | using System;
41 | using System.Threading;
42 |
43 | namespace WebSocketSharp.Net
44 | {
45 | internal class HttpStreamAsyncResult : IAsyncResult
46 | {
47 | #region Private Fields
48 |
49 | private byte[] _buffer;
50 | private AsyncCallback _callback;
51 | private bool _completed;
52 | private int _count;
53 | private Exception _exception;
54 | private int _offset;
55 | private object _state;
56 | private object _sync;
57 | private int _syncRead;
58 | private ManualResetEvent _waitHandle;
59 |
60 | #endregion
61 |
62 | #region Internal Constructors
63 |
64 | internal HttpStreamAsyncResult (AsyncCallback callback, object state)
65 | {
66 | _callback = callback;
67 | _state = state;
68 | _sync = new object ();
69 | }
70 |
71 | #endregion
72 |
73 | #region Internal Properties
74 |
75 | internal byte[] Buffer {
76 | get {
77 | return _buffer;
78 | }
79 |
80 | set {
81 | _buffer = value;
82 | }
83 | }
84 |
85 | internal int Count {
86 | get {
87 | return _count;
88 | }
89 |
90 | set {
91 | _count = value;
92 | }
93 | }
94 |
95 | internal Exception Exception {
96 | get {
97 | return _exception;
98 | }
99 | }
100 |
101 | internal bool HasException {
102 | get {
103 | return _exception != null;
104 | }
105 | }
106 |
107 | internal int Offset {
108 | get {
109 | return _offset;
110 | }
111 |
112 | set {
113 | _offset = value;
114 | }
115 | }
116 |
117 | internal int SyncRead {
118 | get {
119 | return _syncRead;
120 | }
121 |
122 | set {
123 | _syncRead = value;
124 | }
125 | }
126 |
127 | #endregion
128 |
129 | #region Public Properties
130 |
131 | public object AsyncState {
132 | get {
133 | return _state;
134 | }
135 | }
136 |
137 | public WaitHandle AsyncWaitHandle {
138 | get {
139 | lock (_sync)
140 | return _waitHandle ?? (_waitHandle = new ManualResetEvent (_completed));
141 | }
142 | }
143 |
144 | public bool CompletedSynchronously {
145 | get {
146 | return _syncRead == _count;
147 | }
148 | }
149 |
150 | public bool IsCompleted {
151 | get {
152 | lock (_sync)
153 | return _completed;
154 | }
155 | }
156 |
157 | #endregion
158 |
159 | #region Internal Methods
160 |
161 | internal void Complete ()
162 | {
163 | lock (_sync) {
164 | if (_completed)
165 | return;
166 |
167 | _completed = true;
168 | if (_waitHandle != null)
169 | _waitHandle.Set ();
170 |
171 | if (_callback != null)
172 | _callback.BeginInvoke (this, ar => _callback.EndInvoke (ar), null);
173 | }
174 | }
175 |
176 | internal void Complete (Exception exception)
177 | {
178 | _exception = exception;
179 | Complete ();
180 | }
181 |
182 | #endregion
183 | }
184 | }
185 |
--------------------------------------------------------------------------------
/UnityWebRTC/Assets/WebSocketSharp/Net/AuthenticationChallenge.cs:
--------------------------------------------------------------------------------
1 | #region License
2 | /*
3 | * AuthenticationChallenge.cs
4 | *
5 | * The MIT License
6 | *
7 | * Copyright (c) 2013-2014 sta.blockhead
8 | *
9 | * Permission is hereby granted, free of charge, to any person obtaining a copy
10 | * of this software and associated documentation files (the "Software"), to deal
11 | * in the Software without restriction, including without limitation the rights
12 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
13 | * copies of the Software, and to permit persons to whom the Software is
14 | * furnished to do so, subject to the following conditions:
15 | *
16 | * The above copyright notice and this permission notice shall be included in
17 | * all copies or substantial portions of the Software.
18 | *
19 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
22 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
24 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
25 | * THE SOFTWARE.
26 | */
27 | #endregion
28 |
29 | using System;
30 | using System.Collections.Specialized;
31 | using System.Text;
32 |
33 | namespace WebSocketSharp.Net
34 | {
35 | internal class AuthenticationChallenge : AuthenticationBase
36 | {
37 | #region Private Constructors
38 |
39 | private AuthenticationChallenge (AuthenticationSchemes scheme, NameValueCollection parameters)
40 | : base (scheme, parameters)
41 | {
42 | }
43 |
44 | #endregion
45 |
46 | #region Internal Constructors
47 |
48 | internal AuthenticationChallenge (AuthenticationSchemes scheme, string realm)
49 | : base (scheme, new NameValueCollection ())
50 | {
51 | Parameters["realm"] = realm;
52 | if (scheme == AuthenticationSchemes.Digest) {
53 | Parameters["nonce"] = CreateNonceValue ();
54 | Parameters["algorithm"] = "MD5";
55 | Parameters["qop"] = "auth";
56 | }
57 | }
58 |
59 | #endregion
60 |
61 | #region Public Properties
62 |
63 | public string Domain {
64 | get {
65 | return Parameters["domain"];
66 | }
67 | }
68 |
69 | public string Stale {
70 | get {
71 | return Parameters["stale"];
72 | }
73 | }
74 |
75 | #endregion
76 |
77 | #region Internal Methods
78 |
79 | internal static AuthenticationChallenge CreateBasicChallenge (string realm)
80 | {
81 | return new AuthenticationChallenge (AuthenticationSchemes.Basic, realm);
82 | }
83 |
84 | internal static AuthenticationChallenge CreateDigestChallenge (string realm)
85 | {
86 | return new AuthenticationChallenge (AuthenticationSchemes.Digest, realm);
87 | }
88 |
89 | internal static AuthenticationChallenge Parse (string value)
90 | {
91 | var chal = value.Split (new[] { ' ' }, 2);
92 | if (chal.Length != 2)
93 | return null;
94 |
95 | var schm = chal[0].ToLower ();
96 | return schm == "basic"
97 | ? new AuthenticationChallenge (
98 | AuthenticationSchemes.Basic, ParseParameters (chal[1]))
99 | : schm == "digest"
100 | ? new AuthenticationChallenge (
101 | AuthenticationSchemes.Digest, ParseParameters (chal[1]))
102 | : null;
103 | }
104 |
105 | internal override string ToBasicString ()
106 | {
107 | return String.Format ("Basic realm=\"{0}\"", Parameters["realm"]);
108 | }
109 |
110 | internal override string ToDigestString ()
111 | {
112 | var output = new StringBuilder (128);
113 |
114 | var domain = Parameters["domain"];
115 | if (domain != null)
116 | output.AppendFormat (
117 | "Digest realm=\"{0}\", domain=\"{1}\", nonce=\"{2}\"",
118 | Parameters["realm"],
119 | domain,
120 | Parameters["nonce"]);
121 | else
122 | output.AppendFormat (
123 | "Digest realm=\"{0}\", nonce=\"{1}\"", Parameters["realm"], Parameters["nonce"]);
124 |
125 | var opaque = Parameters["opaque"];
126 | if (opaque != null)
127 | output.AppendFormat (", opaque=\"{0}\"", opaque);
128 |
129 | var stale = Parameters["stale"];
130 | if (stale != null)
131 | output.AppendFormat (", stale={0}", stale);
132 |
133 | var algo = Parameters["algorithm"];
134 | if (algo != null)
135 | output.AppendFormat (", algorithm={0}", algo);
136 |
137 | var qop = Parameters["qop"];
138 | if (qop != null)
139 | output.AppendFormat (", qop=\"{0}\"", qop);
140 |
141 | return output.ToString ();
142 | }
143 |
144 | #endregion
145 | }
146 | }
147 |
--------------------------------------------------------------------------------
/UnityWebRTC/Assets/WebSocketSharp/LogData.cs:
--------------------------------------------------------------------------------
1 | #region License
2 | /*
3 | * LogData.cs
4 | *
5 | * The MIT License
6 | *
7 | * Copyright (c) 2013-2015 sta.blockhead
8 | *
9 | * Permission is hereby granted, free of charge, to any person obtaining a copy
10 | * of this software and associated documentation files (the "Software"), to deal
11 | * in the Software without restriction, including without limitation the rights
12 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
13 | * copies of the Software, and to permit persons to whom the Software is
14 | * furnished to do so, subject to the following conditions:
15 | *
16 | * The above copyright notice and this permission notice shall be included in
17 | * all copies or substantial portions of the Software.
18 | *
19 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
22 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
24 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
25 | * THE SOFTWARE.
26 | */
27 | #endregion
28 |
29 | using System;
30 | using System.Diagnostics;
31 | using System.Text;
32 |
33 | namespace WebSocketSharp
34 | {
35 | ///
36 | /// Represents a log data used by the class.
37 | ///
38 | public class LogData
39 | {
40 | #region Private Fields
41 |
42 | private StackFrame _caller;
43 | private DateTime _date;
44 | private LogLevel _level;
45 | private string _message;
46 |
47 | #endregion
48 |
49 | #region Internal Constructors
50 |
51 | internal LogData (LogLevel level, StackFrame caller, string message)
52 | {
53 | _level = level;
54 | _caller = caller;
55 | _message = message ?? String.Empty;
56 | _date = DateTime.Now;
57 | }
58 |
59 | #endregion
60 |
61 | #region Public Properties
62 |
63 | ///
64 | /// Gets the information of the logging method caller.
65 | ///
66 | ///
67 | /// A that provides the information of the logging method caller.
68 | ///
69 | public StackFrame Caller {
70 | get {
71 | return _caller;
72 | }
73 | }
74 |
75 | ///
76 | /// Gets the date and time when the log data was created.
77 | ///
78 | ///
79 | /// A that represents the date and time when the log data was created.
80 | ///
81 | public DateTime Date {
82 | get {
83 | return _date;
84 | }
85 | }
86 |
87 | ///
88 | /// Gets the logging level of the log data.
89 | ///
90 | ///
91 | /// One of the enum values, indicates the logging level of the log data.
92 | ///
93 | public LogLevel Level {
94 | get {
95 | return _level;
96 | }
97 | }
98 |
99 | ///
100 | /// Gets the message of the log data.
101 | ///
102 | ///
103 | /// A that represents the message of the log data.
104 | ///
105 | public string Message {
106 | get {
107 | return _message;
108 | }
109 | }
110 |
111 | #endregion
112 |
113 | #region Public Methods
114 |
115 | ///
116 | /// Returns a that represents the current .
117 | ///
118 | ///
119 | /// A that represents the current .
120 | ///
121 | public override string ToString ()
122 | {
123 | var header = String.Format ("{0}|{1,-5}|", _date, _level);
124 | var method = _caller.GetMethod ();
125 | var type = method.DeclaringType;
126 | #if DEBUG
127 | var lineNum = _caller.GetFileLineNumber ();
128 | var headerAndCaller =
129 | String.Format ("{0}{1}.{2}:{3}|", header, type.Name, method.Name, lineNum);
130 | #else
131 | var headerAndCaller = String.Format ("{0}{1}.{2}|", header, type.Name, method.Name);
132 | #endif
133 | var msgs = _message.Replace ("\r\n", "\n").TrimEnd ('\n').Split ('\n');
134 | if (msgs.Length <= 1)
135 | return String.Format ("{0}{1}", headerAndCaller, _message);
136 |
137 | var buff = new StringBuilder (String.Format ("{0}{1}\n", headerAndCaller, msgs[0]), 64);
138 |
139 | var fmt = String.Format ("{{0,{0}}}{{1}}\n", header.Length);
140 | for (var i = 1; i < msgs.Length; i++)
141 | buff.AppendFormat (fmt, "", msgs[i]);
142 |
143 | buff.Length--;
144 | return buff.ToString ();
145 | }
146 |
147 | #endregion
148 | }
149 | }
150 |
--------------------------------------------------------------------------------
/UnityWebRTC/Assets/WebSocketSharp/CloseStatusCode.cs:
--------------------------------------------------------------------------------
1 | #region License
2 | /*
3 | * CloseStatusCode.cs
4 | *
5 | * The MIT License
6 | *
7 | * Copyright (c) 2012-2016 sta.blockhead
8 | *
9 | * Permission is hereby granted, free of charge, to any person obtaining a copy
10 | * of this software and associated documentation files (the "Software"), to deal
11 | * in the Software without restriction, including without limitation the rights
12 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
13 | * copies of the Software, and to permit persons to whom the Software is
14 | * furnished to do so, subject to the following conditions:
15 | *
16 | * The above copyright notice and this permission notice shall be included in
17 | * all copies or substantial portions of the Software.
18 | *
19 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
22 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
24 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
25 | * THE SOFTWARE.
26 | */
27 | #endregion
28 |
29 | using System;
30 |
31 | namespace WebSocketSharp
32 | {
33 | ///
34 | /// Indicates the status code for the WebSocket connection close.
35 | ///
36 | ///
37 | ///
38 | /// The values of this enumeration are defined in
39 | ///
40 | /// Section 7.4 of RFC 6455.
41 | ///
42 | ///
43 | /// "Reserved value" cannot be sent as a status code in
44 | /// closing handshake by an endpoint.
45 | ///
46 | ///
47 | public enum CloseStatusCode : ushort
48 | {
49 | ///
50 | /// Equivalent to close status 1000. Indicates normal close.
51 | ///
52 | Normal = 1000,
53 | ///
54 | /// Equivalent to close status 1001. Indicates that an endpoint is
55 | /// going away.
56 | ///
57 | Away = 1001,
58 | ///
59 | /// Equivalent to close status 1002. Indicates that an endpoint is
60 | /// terminating the connection due to a protocol error.
61 | ///
62 | ProtocolError = 1002,
63 | ///
64 | /// Equivalent to close status 1003. Indicates that an endpoint is
65 | /// terminating the connection because it has received a type of
66 | /// data that it cannot accept.
67 | ///
68 | UnsupportedData = 1003,
69 | ///
70 | /// Equivalent to close status 1004. Still undefined. A Reserved value.
71 | ///
72 | Undefined = 1004,
73 | ///
74 | /// Equivalent to close status 1005. Indicates that no status code was
75 | /// actually present. A Reserved value.
76 | ///
77 | NoStatus = 1005,
78 | ///
79 | /// Equivalent to close status 1006. Indicates that the connection was
80 | /// closed abnormally. A Reserved value.
81 | ///
82 | Abnormal = 1006,
83 | ///
84 | /// Equivalent to close status 1007. Indicates that an endpoint is
85 | /// terminating the connection because it has received a message that
86 | /// contains data that is not consistent with the type of the message.
87 | ///
88 | InvalidData = 1007,
89 | ///
90 | /// Equivalent to close status 1008. Indicates that an endpoint is
91 | /// terminating the connection because it has received a message that
92 | /// violates its policy.
93 | ///
94 | PolicyViolation = 1008,
95 | ///
96 | /// Equivalent to close status 1009. Indicates that an endpoint is
97 | /// terminating the connection because it has received a message that
98 | /// is too big to process.
99 | ///
100 | TooBig = 1009,
101 | ///
102 | /// Equivalent to close status 1010. Indicates that a client is
103 | /// terminating the connection because it has expected the server to
104 | /// negotiate one or more extension, but the server did not return
105 | /// them in the handshake response.
106 | ///
107 | MandatoryExtension = 1010,
108 | ///
109 | /// Equivalent to close status 1011. Indicates that a server is
110 | /// terminating the connection because it has encountered an unexpected
111 | /// condition that prevented it from fulfilling the request.
112 | ///
113 | ServerError = 1011,
114 | ///
115 | /// Equivalent to close status 1015. Indicates that the connection was
116 | /// closed due to a failure to perform a TLS handshake. A Reserved value.
117 | ///
118 | TlsHandshakeFailure = 1015
119 | }
120 | }
121 |
--------------------------------------------------------------------------------
/.gitattributes:
--------------------------------------------------------------------------------
1 | * text=auto
2 |
3 | *.cs diff=csharp text
4 | *.cginc text
5 | *.shader text
6 |
7 | # Unity YAML
8 | *.anim -text merge=unityyamlmerge diff
9 | *.asset -text merge=unityyamlmerge diff
10 | *.controller -text merge=unityyamlmerge diff
11 | *.mat -text merge=unityyamlmerge diff
12 | *.meta -text merge=unityyamlmerge diff
13 | *.physicMaterial -text merge=unityyamlmerge diff
14 | *.physicsMaterial2D -text merge=unityyamlmerge diff
15 | *.prefab -text merge=unityyamlmerge diff
16 | *.unity -text merge=unityyamlmerge diff
17 |
18 | # Unity LFS
19 | *.cubemap filter=lfs diff=lfs merge=lfs -text
20 | *.unitypackage filter=lfs diff=lfs merge=lfs -text
21 |
22 | # 2D formats
23 | *.[aA][iI] filter=lfs diff=lfs merge=lfs -text
24 | *.[bB][mM][pP] filter=lfs diff=lfs merge=lfs -text
25 | *.[dD][dD][sS] filter=lfs diff=lfs merge=lfs -text
26 | *.[eE][xX][rR] filter=lfs diff=lfs merge=lfs -text
27 | *.[gG][iI][fF] filter=lfs diff=lfs merge=lfs -text
28 | *.[hH][dD][rR] filter=lfs diff=lfs merge=lfs -text
29 | *.[iI][fF][fF] filter=lfs diff=lfs merge=lfs -text
30 | *.[jJ][pP][eE][gG] filter=lfs diff=lfs merge=lfs -text
31 | *.[jJ][pP][gG] filter=lfs diff=lfs merge=lfs -text
32 | *.[pP][iI][cC][tT] filter=lfs diff=lfs merge=lfs -text
33 | *.[pP][nN][gG] filter=lfs diff=lfs merge=lfs -text
34 | *.[pP][sS][dD] filter=lfs diff=lfs merge=lfs -text
35 | *.[tT][gG][aA] filter=lfs diff=lfs merge=lfs -text
36 | *.[tT][iI][fF] filter=lfs diff=lfs merge=lfs -text
37 | *.[tT][iI][fF][fF] filter=lfs diff=lfs merge=lfs -text
38 |
39 | # 3D formats
40 | *.3[dD][mM] filter=lfs diff=lfs merge=lfs -text
41 | *.3[dD][sS] filter=lfs diff=lfs merge=lfs -text
42 | *.[aA][bB][cC] filter=lfs diff=lfs merge=lfs -text
43 | *.[bB][lL][eE][nN][dD] filter=lfs diff=lfs merge=lfs -text
44 | *.[cC]4[dD] filter=lfs diff=lfs merge=lfs -text
45 | *.[cC][oO][lL][lL][aA][dD][aA] filter=lfs diff=lfs merge=lfs -text
46 | *.[dD][aA][eE] filter=lfs diff=lfs merge=lfs -text
47 | *.[dD][xX][fF] filter=lfs diff=lfs merge=lfs -text
48 | *.[fF][bB][xX] filter=lfs diff=lfs merge=lfs -text
49 | *.[jJ][aA][sS] filter=lfs diff=lfs merge=lfs -text
50 | *.[lL][wW][oO] filter=lfs diff=lfs merge=lfs -text
51 | *.[lL][wW][oO]2 filter=lfs diff=lfs merge=lfs -text
52 | *.[lL][wW][sS] filter=lfs diff=lfs merge=lfs -text
53 | *.[lL][xX][oO] filter=lfs diff=lfs merge=lfs -text
54 | *.[mM][aA] filter=lfs diff=lfs merge=lfs -text
55 | *.[mM][aA][xX] filter=lfs diff=lfs merge=lfs -text
56 | *.[mM][bB] filter=lfs diff=lfs merge=lfs -text
57 | *.[oO][bB][jJ] filter=lfs diff=lfs merge=lfs -text
58 | *.[pP][lL][yY] filter=lfs diff=lfs merge=lfs -text
59 | *.[sS][kK][pP] filter=lfs diff=lfs merge=lfs -text
60 | *.[sS][tT][lL] filter=lfs diff=lfs merge=lfs -text
61 | *.[zZ][tT][lL] filter=lfs diff=lfs merge=lfs -text
62 |
63 | # Audio formats
64 | *.[aA][iI][fF] filter=lfs diff=lfs merge=lfs -text
65 | *.[aA][iI][fF][fF] filter=lfs diff=lfs merge=lfs -text
66 | *.[bB][aA][nN][kK] filter=lfs diff=lfs merge=lfs -text
67 | *.[iI][tT] filter=lfs diff=lfs merge=lfs -text
68 | *.[mM][oO][dD] filter=lfs diff=lfs merge=lfs -text
69 | *.[mM][pP]3 filter=lfs diff=lfs merge=lfs -text
70 | *.[oO][gG][gG] filter=lfs diff=lfs merge=lfs -text
71 | *.[sS]3[mM] filter=lfs diff=lfs merge=lfs -text
72 | *.[wW][aA][vV] filter=lfs diff=lfs merge=lfs -text
73 | *.[xX][mM] filter=lfs diff=lfs merge=lfs -text
74 |
75 | # Video formats
76 | *.[aA][sS][fF] filter=lfs diff=lfs merge=lfs -text
77 | *.[aA][vV][iI] filter=lfs diff=lfs merge=lfs -text
78 | *.[fF][lL][vV] filter=lfs diff=lfs merge=lfs -text
79 | *.[mM][oO][vV] filter=lfs diff=lfs merge=lfs -text
80 | *.[mM][pP]4 filter=lfs diff=lfs merge=lfs -text
81 | *.[mM][pP][eE][gG] filter=lfs diff=lfs merge=lfs -text
82 | *.[mM][pP][gG] filter=lfs diff=lfs merge=lfs -text
83 | *.[oO][gG][vV] filter=lfs diff=lfs merge=lfs -text
84 | *.[wW][mM][vV] filter=lfs diff=lfs merge=lfs -text
85 |
86 | # Build
87 | *.[dD][lL][lL] filter=lfs diff=lfs merge=lfs -text
88 | *.[mM][dD][bB] filter=lfs diff=lfs merge=lfs -text
89 | *.[pP][dD][bB] filter=lfs diff=lfs merge=lfs -text
90 | *.[sS][oO] filter=lfs diff=lfs merge=lfs -text
91 |
92 | # Packaging
93 | *.7[zZ] filter=lfs diff=lfs merge=lfs -text
94 | *.[bB][zZ]2 filter=lfs diff=lfs merge=lfs -text
95 | *.[gG][zZ] filter=lfs diff=lfs merge=lfs -text
96 | *.[rR][aA][rR] filter=lfs diff=lfs merge=lfs -text
97 | *.[tT][aA][rR] filter=lfs diff=lfs merge=lfs -text
98 | *.[tT][aA][rR].[gG][zZ] filter=lfs diff=lfs merge=lfs -text
99 | *.[zZ][iI][pP] filter=lfs diff=lfs merge=lfs -text
100 |
101 | # Fonts
102 | *.[oO][tT][fF] filter=lfs diff=lfs merge=lfs -text
103 | *.[tT][tT][fF] filter=lfs diff=lfs merge=lfs -text
104 |
105 | # Documents
106 | *.[pP][dD][fF] filter=lfs diff=lfs merge=lfs -text
107 |
108 | # Collapse Unity-generated files on GitHub
109 | *.asset linguist-generated
110 | *.mat linguist-generated
111 | *.meta linguist-generated
112 | *.prefab linguist-generated
113 | *.unity linguist-generated
114 |
115 | # Binary files
116 | *.a filter=lfs diff=lfs merge=lfs -text
117 | *.so filter=lfs diff=lfs merge=lfs -text
118 | *.dll filter=lfs diff=lfs merge=lfs -text
119 |
120 | # ARCore specific
121 | augmented_image_cli_linux filter=lfs diff=lfs merge=lfs -text
122 | augmented_image_cli_osx filter=lfs diff=lfs merge=lfs -text
123 | augmented_image_cli_win.exe filter=lfs diff=lfs merge=lfs -text
124 | *.aar filter=lfs diff=lfs merge=lfs -text
125 |
--------------------------------------------------------------------------------
/UnityWebRTC/Assets/WebSocketSharp/Net/HttpListenerAsyncResult.cs:
--------------------------------------------------------------------------------
1 | #region License
2 | /*
3 | * HttpListenerAsyncResult.cs
4 | *
5 | * This code is derived from ListenerAsyncResult.cs (System.Net) of Mono
6 | * (http://www.mono-project.com).
7 | *
8 | * The MIT License
9 | *
10 | * Copyright (c) 2005 Ximian, Inc. (http://www.ximian.com)
11 | * Copyright (c) 2012-2016 sta.blockhead
12 | *
13 | * Permission is hereby granted, free of charge, to any person obtaining a copy
14 | * of this software and associated documentation files (the "Software"), to deal
15 | * in the Software without restriction, including without limitation the rights
16 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
17 | * copies of the Software, and to permit persons to whom the Software is
18 | * furnished to do so, subject to the following conditions:
19 | *
20 | * The above copyright notice and this permission notice shall be included in
21 | * all copies or substantial portions of the Software.
22 | *
23 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
24 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
25 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
26 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
27 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
28 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
29 | * THE SOFTWARE.
30 | */
31 | #endregion
32 |
33 | #region Authors
34 | /*
35 | * Authors:
36 | * - Gonzalo Paniagua Javier
37 | */
38 | #endregion
39 |
40 | #region Contributors
41 | /*
42 | * Contributors:
43 | * - Nicholas Devenish
44 | */
45 | #endregion
46 |
47 | using System;
48 | using System.Threading;
49 |
50 | namespace WebSocketSharp.Net
51 | {
52 | internal class HttpListenerAsyncResult : IAsyncResult
53 | {
54 | #region Private Fields
55 |
56 | private AsyncCallback _callback;
57 | private bool _completed;
58 | private HttpListenerContext _context;
59 | private bool _endCalled;
60 | private Exception _exception;
61 | private bool _inGet;
62 | private object _state;
63 | private object _sync;
64 | private bool _syncCompleted;
65 | private ManualResetEvent _waitHandle;
66 |
67 | #endregion
68 |
69 | #region Internal Constructors
70 |
71 | internal HttpListenerAsyncResult (AsyncCallback callback, object state)
72 | {
73 | _callback = callback;
74 | _state = state;
75 | _sync = new object ();
76 | }
77 |
78 | #endregion
79 |
80 | #region Internal Properties
81 |
82 | internal bool EndCalled {
83 | get {
84 | return _endCalled;
85 | }
86 |
87 | set {
88 | _endCalled = value;
89 | }
90 | }
91 |
92 | internal bool InGet {
93 | get {
94 | return _inGet;
95 | }
96 |
97 | set {
98 | _inGet = value;
99 | }
100 | }
101 |
102 | #endregion
103 |
104 | #region Public Properties
105 |
106 | public object AsyncState {
107 | get {
108 | return _state;
109 | }
110 | }
111 |
112 | public WaitHandle AsyncWaitHandle {
113 | get {
114 | lock (_sync)
115 | return _waitHandle ?? (_waitHandle = new ManualResetEvent (_completed));
116 | }
117 | }
118 |
119 | public bool CompletedSynchronously {
120 | get {
121 | return _syncCompleted;
122 | }
123 | }
124 |
125 | public bool IsCompleted {
126 | get {
127 | lock (_sync)
128 | return _completed;
129 | }
130 | }
131 |
132 | #endregion
133 |
134 | #region Private Methods
135 |
136 | private static void complete (HttpListenerAsyncResult asyncResult)
137 | {
138 | lock (asyncResult._sync) {
139 | asyncResult._completed = true;
140 |
141 | var waitHandle = asyncResult._waitHandle;
142 | if (waitHandle != null)
143 | waitHandle.Set ();
144 | }
145 |
146 | var callback = asyncResult._callback;
147 | if (callback == null)
148 | return;
149 |
150 | ThreadPool.QueueUserWorkItem (
151 | state => {
152 | try {
153 | callback (asyncResult);
154 | }
155 | catch {
156 | }
157 | },
158 | null
159 | );
160 | }
161 |
162 | #endregion
163 |
164 | #region Internal Methods
165 |
166 | internal void Complete (Exception exception)
167 | {
168 | _exception = _inGet && (exception is ObjectDisposedException)
169 | ? new HttpListenerException (995, "The listener is closed.")
170 | : exception;
171 |
172 | complete (this);
173 | }
174 |
175 | internal void Complete (HttpListenerContext context)
176 | {
177 | Complete (context, false);
178 | }
179 |
180 | internal void Complete (HttpListenerContext context, bool syncCompleted)
181 | {
182 | _context = context;
183 | _syncCompleted = syncCompleted;
184 |
185 | complete (this);
186 | }
187 |
188 | internal HttpListenerContext GetContext ()
189 | {
190 | if (_exception != null)
191 | throw _exception;
192 |
193 | return _context;
194 | }
195 |
196 | #endregion
197 | }
198 | }
199 |
--------------------------------------------------------------------------------
/UnityWebRTC/Assets/WebSocketSharp/MessageEventArgs.cs:
--------------------------------------------------------------------------------
1 | #region License
2 | /*
3 | * MessageEventArgs.cs
4 | *
5 | * The MIT License
6 | *
7 | * Copyright (c) 2012-2016 sta.blockhead
8 | *
9 | * Permission is hereby granted, free of charge, to any person obtaining a copy
10 | * of this software and associated documentation files (the "Software"), to deal
11 | * in the Software without restriction, including without limitation the rights
12 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
13 | * copies of the Software, and to permit persons to whom the Software is
14 | * furnished to do so, subject to the following conditions:
15 | *
16 | * The above copyright notice and this permission notice shall be included in
17 | * all copies or substantial portions of the Software.
18 | *
19 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
22 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
24 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
25 | * THE SOFTWARE.
26 | */
27 | #endregion
28 |
29 | using System;
30 |
31 | namespace WebSocketSharp
32 | {
33 | ///
34 | /// Represents the event data for the event.
35 | ///
36 | ///
37 | ///
38 | /// That event occurs when the receives
39 | /// a message or a ping if the
40 | /// property is set to true.
41 | ///
42 | ///
43 | /// If you would like to get the message data, you should access
44 | /// the or property.
45 | ///
46 | ///
47 | public class MessageEventArgs : EventArgs
48 | {
49 | #region Private Fields
50 |
51 | private string _data;
52 | private bool _dataSet;
53 | private Opcode _opcode;
54 | private byte[] _rawData;
55 |
56 | #endregion
57 |
58 | #region Internal Constructors
59 |
60 | internal MessageEventArgs (WebSocketFrame frame)
61 | {
62 | _opcode = frame.Opcode;
63 | _rawData = frame.PayloadData.ApplicationData;
64 | }
65 |
66 | internal MessageEventArgs (Opcode opcode, byte[] rawData)
67 | {
68 | if ((ulong) rawData.LongLength > PayloadData.MaxLength)
69 | throw new WebSocketException (CloseStatusCode.TooBig);
70 |
71 | _opcode = opcode;
72 | _rawData = rawData;
73 | }
74 |
75 | #endregion
76 |
77 | #region Internal Properties
78 |
79 | ///
80 | /// Gets the opcode for the message.
81 | ///
82 | ///
83 | /// , ,
84 | /// or .
85 | ///
86 | internal Opcode Opcode {
87 | get {
88 | return _opcode;
89 | }
90 | }
91 |
92 | #endregion
93 |
94 | #region Public Properties
95 |
96 | ///
97 | /// Gets the message data as a .
98 | ///
99 | ///
100 | /// A that represents the message data if its type is
101 | /// text or ping and if decoding it to a string has successfully done;
102 | /// otherwise, .
103 | ///
104 | public string Data {
105 | get {
106 | setData ();
107 | return _data;
108 | }
109 | }
110 |
111 | ///
112 | /// Gets a value indicating whether the message type is binary.
113 | ///
114 | ///
115 | /// true if the message type is binary; otherwise, false.
116 | ///
117 | public bool IsBinary {
118 | get {
119 | return _opcode == Opcode.Binary;
120 | }
121 | }
122 |
123 | ///
124 | /// Gets a value indicating whether the message type is ping.
125 | ///
126 | ///
127 | /// true if the message type is ping; otherwise, false.
128 | ///
129 | public bool IsPing {
130 | get {
131 | return _opcode == Opcode.Ping;
132 | }
133 | }
134 |
135 | ///
136 | /// Gets a value indicating whether the message type is text.
137 | ///
138 | ///
139 | /// true if the message type is text; otherwise, false.
140 | ///
141 | public bool IsText {
142 | get {
143 | return _opcode == Opcode.Text;
144 | }
145 | }
146 |
147 | ///
148 | /// Gets the message data as an array of .
149 | ///
150 | ///
151 | /// An array of that represents the message data.
152 | ///
153 | public byte[] RawData {
154 | get {
155 | setData ();
156 | return _rawData;
157 | }
158 | }
159 |
160 | #endregion
161 |
162 | #region Private Methods
163 |
164 | private void setData ()
165 | {
166 | if (_dataSet)
167 | return;
168 |
169 | if (_opcode == Opcode.Binary) {
170 | _dataSet = true;
171 | return;
172 | }
173 |
174 | string data;
175 | if (_rawData.TryGetUTF8DecodedString (out data))
176 | _data = data;
177 |
178 | _dataSet = true;
179 | }
180 |
181 | #endregion
182 | }
183 | }
184 |
--------------------------------------------------------------------------------
/UnityWebRTC/Assets/Scripts/Signaler.cs:
--------------------------------------------------------------------------------
1 |
2 | using System.Collections.Generic;
3 | using Microsoft.MixedReality.WebRTC;
4 | using Newtonsoft.Json.Linq;
5 | using System.Threading.Tasks;
6 |
7 | using UnityEngine;
8 | public abstract class Signaler
9 | {
10 | private PeerConnection _peerConnection;
11 | public PeerConnection PeerConnection { get => _peerConnection; }
12 | ///
13 | /// Event invoked when an ICE candidate message has been received from the remote peer's signaler.
14 | ///
15 | public PeerConnection.IceCandidateReadytoSendDelegate IceCandidateReceived;
16 |
17 | ///
18 | /// Event invoked when an SDP offer or answer message has been received from the remote peer's signaler.
19 | ///
20 | public PeerConnection.LocalSdpReadyToSendDelegate SdpMessageReceived;
21 |
22 | public System.Action ClientConnected;
23 | public System.Action ClientDisconnected;
24 | public readonly List IceServers = new List { };
25 |
26 | protected abstract void SendMessage(JObject json);
27 | public abstract void Start();
28 | public abstract void Stop();
29 |
30 |
31 | public Signaler()
32 | {
33 | SdpMessageReceived += ProcessSdpMessage;
34 | ClientConnected += SetUpPeer;
35 | ClientDisconnected += TearDownPeer;
36 | }
37 |
38 | private async void SetUpPeer()
39 | {
40 | _peerConnection = new PeerConnection();
41 |
42 | var config = new PeerConnectionConfiguration
43 | {
44 | IceServers = IceServers
45 | };
46 |
47 | await _peerConnection.InitializeAsync(config);
48 | PeerConnection.LocalSdpReadytoSend += PeerConnection_LocalSdpReadytoSend;
49 | PeerConnection.IceCandidateReadytoSend += PeerConnection_IceCandidateReadytoSend;
50 | PeerConnection.Connected += () => { Debug.Log("PeerConnection: connected."); };
51 | PeerConnection.IceStateChanged += (IceConnectionState newState) =>
52 | {
53 | Debug.Log($"ICE state: {newState}");
54 | if (newState == IceConnectionState.Disconnected)
55 | {
56 | // we cannot dispose peer connection from WITHIN a callback
57 | // start thread and to it later (by emitting ClientDisconnected event)
58 | Task.Factory.StartNew(async () => { await Task.Delay(100); ClientDisconnected?.Invoke(); });
59 | };
60 | };
61 | }
62 |
63 | private void TearDownPeer()
64 | {
65 | Debug.Log("Dispose PeerConnection.");
66 | _peerConnection?.Dispose();
67 | }
68 |
69 | private void PeerConnection_IceCandidateReadytoSend(IceCandidate candidate)
70 | {
71 | // See ProcessIncomingMessages() for the message format
72 |
73 |
74 | JObject iceCandidate = new JObject {
75 | { "type", "ice" },
76 | { "candidate", candidate.Content },
77 | { "sdpMLineindex", candidate.SdpMlineIndex },
78 | { "sdpMid", candidate.SdpMid }
79 | };
80 |
81 | // Debug.Log($"Ice Candidate {iceCandidate}");
82 | SendMessage(iceCandidate);
83 | }
84 |
85 | private void PeerConnection_LocalSdpReadytoSend(SdpMessage message)
86 | {
87 | // See ProcessIncomingMessages() for the message format
88 | string typeStr = SdpMessage.TypeToString(message.Type);
89 |
90 | // https://github.com/microsoft/MixedReality-WebRTC/issues/501#issuecomment-674469381
91 | // sdp message headeer is deprecated and needs fixing
92 | JObject sdpMessage = new JObject {
93 | { "type", "sdp"},
94 | { typeStr, message.Content.Replace("msid-semantic: WMS\r", "msid-semantic: WMS local_av_stream\r").Replace("msid:-", "msid:-local_av_stream") }
95 | };
96 | SendMessage(sdpMessage);
97 | }
98 |
99 |
100 | protected void ProcessIncomingMessage(JObject json)
101 | {
102 | if ((string)json["type"] == "ice")
103 | {
104 | string sdpMid = json["sdpMid"].Value();
105 | int sdpMlineindex = json["sdpMLineindex"].Value();
106 | string candidate = json["candidate"].Value();
107 | // Debug.Log($"[<-] ICE candidate: {sdpMid} {sdpMlineindex} {candidate}");
108 | var iceCandidate = new IceCandidate
109 | {
110 | SdpMid = sdpMid,
111 | SdpMlineIndex = sdpMlineindex,
112 | Content = candidate
113 | };
114 | PeerConnection.AddIceCandidate(iceCandidate);
115 | }
116 | if ((string)json["type"] == "sdp")
117 | {
118 | string sdp;
119 | string type;
120 | if (json.ContainsKey("offer"))
121 | {
122 | sdp = json["offer"].Value();
123 | type = "offer";
124 | }
125 | else
126 | {
127 | type = "answer";
128 | sdp = (string)json["answer"];
129 | }
130 | // Debug.Log($"[<-] SDP message: {type} {sdp}");
131 | var message = new SdpMessage { Type = SdpMessage.StringToType(type), Content = sdp };
132 | SdpMessageReceived?.Invoke(message);
133 | }
134 | }
135 |
136 | private async void ProcessSdpMessage(SdpMessage message)
137 | {
138 | await PeerConnection.SetRemoteDescriptionAsync(message);
139 | if (message.Type == SdpMessageType.Offer)
140 | {
141 | PeerConnection.CreateAnswer();
142 | }
143 | }
144 | }
145 |
--------------------------------------------------------------------------------
/UnityWebRTC/Assets/WebSocketSharp/PayloadData.cs:
--------------------------------------------------------------------------------
1 | #region License
2 | /*
3 | * PayloadData.cs
4 | *
5 | * The MIT License
6 | *
7 | * Copyright (c) 2012-2019 sta.blockhead
8 | *
9 | * Permission is hereby granted, free of charge, to any person obtaining a copy
10 | * of this software and associated documentation files (the "Software"), to deal
11 | * in the Software without restriction, including without limitation the rights
12 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
13 | * copies of the Software, and to permit persons to whom the Software is
14 | * furnished to do so, subject to the following conditions:
15 | *
16 | * The above copyright notice and this permission notice shall be included in
17 | * all copies or substantial portions of the Software.
18 | *
19 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
22 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
24 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
25 | * THE SOFTWARE.
26 | */
27 | #endregion
28 |
29 | using System;
30 | using System.Collections;
31 | using System.Collections.Generic;
32 |
33 | namespace WebSocketSharp
34 | {
35 | internal class PayloadData : IEnumerable
36 | {
37 | #region Private Fields
38 |
39 | private byte[] _data;
40 | private long _extDataLength;
41 | private long _length;
42 |
43 | #endregion
44 |
45 | #region Public Fields
46 |
47 | ///
48 | /// Represents the empty payload data.
49 | ///
50 | public static readonly PayloadData Empty;
51 |
52 | ///
53 | /// Represents the allowable max length of payload data.
54 | ///
55 | ///
56 | ///
57 | /// A will occur when the length of
58 | /// incoming payload data is greater than the value of this field.
59 | ///
60 | ///
61 | /// If you would like to change the value of this field, it must be
62 | /// a number between and
63 | /// inclusive.
64 | ///
65 | ///
66 | public static readonly ulong MaxLength;
67 |
68 | #endregion
69 |
70 | #region Static Constructor
71 |
72 | static PayloadData ()
73 | {
74 | Empty = new PayloadData (WebSocket.EmptyBytes, 0);
75 | MaxLength = Int64.MaxValue;
76 | }
77 |
78 | #endregion
79 |
80 | #region Internal Constructors
81 |
82 | internal PayloadData (byte[] data)
83 | : this (data, data.LongLength)
84 | {
85 | }
86 |
87 | internal PayloadData (byte[] data, long length)
88 | {
89 | _data = data;
90 | _length = length;
91 | }
92 |
93 | internal PayloadData (ushort code, string reason)
94 | {
95 | _data = code.Append (reason);
96 | _length = _data.LongLength;
97 | }
98 |
99 | #endregion
100 |
101 | #region Internal Properties
102 |
103 | internal ushort Code {
104 | get {
105 | return _length >= 2
106 | ? _data.SubArray (0, 2).ToUInt16 (ByteOrder.Big)
107 | : (ushort) 1005;
108 | }
109 | }
110 |
111 | internal long ExtensionDataLength {
112 | get {
113 | return _extDataLength;
114 | }
115 |
116 | set {
117 | _extDataLength = value;
118 | }
119 | }
120 |
121 | internal bool HasReservedCode {
122 | get {
123 | return _length >= 2 && Code.IsReserved ();
124 | }
125 | }
126 |
127 | internal string Reason {
128 | get {
129 | if (_length <= 2)
130 | return String.Empty;
131 |
132 | var raw = _data.SubArray (2, _length - 2);
133 |
134 | string reason;
135 | return raw.TryGetUTF8DecodedString (out reason)
136 | ? reason
137 | : String.Empty;
138 | }
139 | }
140 |
141 | #endregion
142 |
143 | #region Public Properties
144 |
145 | public byte[] ApplicationData {
146 | get {
147 | return _extDataLength > 0
148 | ? _data.SubArray (_extDataLength, _length - _extDataLength)
149 | : _data;
150 | }
151 | }
152 |
153 | public byte[] ExtensionData {
154 | get {
155 | return _extDataLength > 0
156 | ? _data.SubArray (0, _extDataLength)
157 | : WebSocket.EmptyBytes;
158 | }
159 | }
160 |
161 | public ulong Length {
162 | get {
163 | return (ulong) _length;
164 | }
165 | }
166 |
167 | #endregion
168 |
169 | #region Internal Methods
170 |
171 | internal void Mask (byte[] key)
172 | {
173 | for (long i = 0; i < _length; i++)
174 | _data[i] = (byte) (_data[i] ^ key[i % 4]);
175 | }
176 |
177 | #endregion
178 |
179 | #region Public Methods
180 |
181 | public IEnumerator GetEnumerator ()
182 | {
183 | foreach (var b in _data)
184 | yield return b;
185 | }
186 |
187 | public byte[] ToArray ()
188 | {
189 | return _data;
190 | }
191 |
192 | public override string ToString ()
193 | {
194 | return BitConverter.ToString (_data);
195 | }
196 |
197 | #endregion
198 |
199 | #region Explicit Interface Implementations
200 |
201 | IEnumerator IEnumerable.GetEnumerator ()
202 | {
203 | return GetEnumerator ();
204 | }
205 |
206 | #endregion
207 | }
208 | }
209 |
--------------------------------------------------------------------------------
/UnityWebRTC/Assets/WebSocketSharp/Net/CookieException.cs:
--------------------------------------------------------------------------------
1 | #region License
2 | /*
3 | * CookieException.cs
4 | *
5 | * This code is derived from CookieException.cs (System.Net) of Mono
6 | * (http://www.mono-project.com).
7 | *
8 | * The MIT License
9 | *
10 | * Copyright (c) 2012-2019 sta.blockhead
11 | *
12 | * Permission is hereby granted, free of charge, to any person obtaining a copy
13 | * of this software and associated documentation files (the "Software"), to deal
14 | * in the Software without restriction, including without limitation the rights
15 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
16 | * copies of the Software, and to permit persons to whom the Software is
17 | * furnished to do so, subject to the following conditions:
18 | *
19 | * The above copyright notice and this permission notice shall be included in
20 | * all copies or substantial portions of the Software.
21 | *
22 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
23 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
24 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
25 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
26 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
27 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
28 | * THE SOFTWARE.
29 | */
30 | #endregion
31 |
32 | #region Authors
33 | /*
34 | * Authors:
35 | * - Lawrence Pit
36 | */
37 | #endregion
38 |
39 | using System;
40 | using System.Runtime.Serialization;
41 | using System.Security.Permissions;
42 |
43 | namespace WebSocketSharp.Net
44 | {
45 | ///
46 | /// The exception that is thrown when a gets an error.
47 | ///
48 | [Serializable]
49 | public class CookieException : FormatException, ISerializable
50 | {
51 | #region Internal Constructors
52 |
53 | internal CookieException (string message)
54 | : base (message)
55 | {
56 | }
57 |
58 | internal CookieException (string message, Exception innerException)
59 | : base (message, innerException)
60 | {
61 | }
62 |
63 | #endregion
64 |
65 | #region Protected Constructors
66 |
67 | ///
68 | /// Initializes a new instance of the class
69 | /// with the serialized data.
70 | ///
71 | ///
72 | /// A that holds the serialized object data.
73 | ///
74 | ///
75 | /// A that specifies the source for
76 | /// the deserialization.
77 | ///
78 | ///
79 | /// is .
80 | ///
81 | protected CookieException (
82 | SerializationInfo serializationInfo, StreamingContext streamingContext
83 | )
84 | : base (serializationInfo, streamingContext)
85 | {
86 | }
87 |
88 | #endregion
89 |
90 | #region Public Constructors
91 |
92 | ///
93 | /// Initializes a new instance of the class.
94 | ///
95 | public CookieException ()
96 | : base ()
97 | {
98 | }
99 |
100 | #endregion
101 |
102 | #region Public Methods
103 |
104 | ///
105 | /// Populates the specified instance with
106 | /// the data needed to serialize the current instance.
107 | ///
108 | ///
109 | /// A that holds the serialized object data.
110 | ///
111 | ///
112 | /// A that specifies the destination for
113 | /// the serialization.
114 | ///
115 | ///
116 | /// is .
117 | ///
118 | [
119 | SecurityPermission (
120 | SecurityAction.LinkDemand,
121 | Flags = SecurityPermissionFlag.SerializationFormatter
122 | )
123 | ]
124 | public override void GetObjectData (
125 | SerializationInfo serializationInfo, StreamingContext streamingContext
126 | )
127 | {
128 | base.GetObjectData (serializationInfo, streamingContext);
129 | }
130 |
131 | #endregion
132 |
133 | #region Explicit Interface Implementation
134 |
135 | ///
136 | /// Populates the specified instance with
137 | /// the data needed to serialize the current instance.
138 | ///
139 | ///
140 | /// A that holds the serialized object data.
141 | ///
142 | ///
143 | /// A that specifies the destination for
144 | /// the serialization.
145 | ///
146 | ///
147 | /// is .
148 | ///
149 | [
150 | SecurityPermission (
151 | SecurityAction.LinkDemand,
152 | Flags = SecurityPermissionFlag.SerializationFormatter,
153 | SerializationFormatter = true
154 | )
155 | ]
156 | void ISerializable.GetObjectData (
157 | SerializationInfo serializationInfo, StreamingContext streamingContext
158 | )
159 | {
160 | base.GetObjectData (serializationInfo, streamingContext);
161 | }
162 |
163 | #endregion
164 | }
165 | }
166 |
--------------------------------------------------------------------------------