-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathLivekitSamples.cs
More file actions
433 lines (362 loc) · 12.5 KB
/
LivekitSamples.cs
File metadata and controls
433 lines (362 loc) · 12.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
using System.Collections;
using UnityEngine;
using LiveKit;
using LiveKit.Proto;
using UnityEngine.UI;
using RoomOptions = LiveKit.RoomOptions;
using StreamTextOptions = LiveKit.StreamTextOptions;
using System.Collections.Generic;
using Application = UnityEngine.Application;
using TMPro;
public class LivekitSamples : MonoBehaviour
{
public string url = "ws://localhost:7880";
public string token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE3MTkyODQ5NzgsImlzcyI6IkFQSXJramtRYVZRSjVERSIsIm5hbWUiOiJ1bml0eSIsIm5iZiI6MTcxNzQ4NDk3OCwic3ViIjoidW5pdHkiLCJ2aWRlbyI6eyJjYW5VcGRhdGVPd25NZXRhZGF0YSI6dHJ1ZSwicm9vbSI6ImxpdmUiLCJyb29tSm9pbiI6dHJ1ZX19.WHt9VItlQj0qaKEB_EIxyFf2UwlqdEdWIiuA_tM0QmI";
private Room room = null;
private WebCamTexture webCamTexture = null;
private int frameRate = 30;
Dictionary<string, GameObject> _videoObjects = new();
Dictionary<string, GameObject> _audioObjects = new();
List<RtcVideoSource> _rtcVideoSources = new();
List<RtcAudioSource> _rtcAudioSources = new();
List<VideoStream> _videoStreams = new();
public GridLayoutGroup layoutGroup; //Component
public TMP_Text statusText;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
}
public void UpdateStatusText(string newText)
{
if (statusText != null)
{
statusText.text = newText;
}
}
public void OnClickPublishAudio()
{
StartCoroutine(publishMicrophone());
Debug.Log("OnClickPublishAudio clicked!");
}
public void OnClickPublishVideo()
{
StartCoroutine(publishVideo());
Debug.Log("OnClickPublishVideo clicked!");
}
public void onClickPublishData()
{
publishData();
Debug.Log("onClickPublishData clicked!");
}
public void onClickMakeCall()
{
Debug.Log("onClickMakeCall clicked!");
if(webCamTexture == null)
{
StartCoroutine(OpenCamera());
}
StartCoroutine(MakeCall());
}
public void onClickHangup()
{
Debug.Log("onClickHangup clicked!");
room.Disconnect();
CleanUp();
room = null;
UpdateStatusText("Disconnected");
}
IEnumerator MakeCall()
{
if(room == null)
{
room = new Room();
room.TrackSubscribed += TrackSubscribed;
room.TrackUnsubscribed += UnTrackSubscribed;
room.DataReceived += DataReceived;
var options = new RoomOptions();
var connect = room.Connect(url, token, options);
yield return connect;
if (!connect.IsError)
{
Debug.Log("Connected to " + room.Name);
UpdateStatusText("Connected");
}
}
}
void CleanUp()
{
foreach(var item in _audioObjects)
{
var source = item.Value.GetComponent<AudioSource>();
source.Stop();
Destroy(item.Value);
}
_audioObjects.Clear();
foreach (var item in _rtcAudioSources)
{
item.Stop();
}
foreach (var item in _videoObjects)
{
RawImage img = item.Value.GetComponent<RawImage>();
if (img != null)
{
img.texture = null;
Destroy(img);
}
Destroy(item.Value);
}
foreach (var item in _videoStreams)
{
item.Stop();
item.Dispose();
}
foreach (var item in _rtcVideoSources)
{
item.Stop();
item.Dispose();
}
_videoObjects.Clear();
_videoStreams.Clear();
}
void AddVideoTrack(RemoteVideoTrack videoTrack)
{
Debug.Log("AddVideoTrack " + videoTrack.Sid);
GameObject imgObject = new GameObject(videoTrack.Sid);
RectTransform trans = imgObject.AddComponent<RectTransform>();
trans.localScale = Vector3.one;
trans.sizeDelta = new Vector2(180, 120);
trans.rotation = Quaternion.AngleAxis(Mathf.Lerp(0f, 180f, 50), Vector3.forward);
RawImage image = imgObject.AddComponent<RawImage>();
var stream = new VideoStream(videoTrack);
stream.TextureReceived += (tex) =>
{
if(image != null)
{
image.texture = tex;
}
};
_videoObjects[videoTrack.Sid] = imgObject;
imgObject.transform.SetParent(layoutGroup.gameObject.transform, false);
stream.Start();
StartCoroutine(stream.Update());
_videoStreams.Add(stream);
}
void TrackSubscribed(IRemoteTrack track, RemoteTrackPublication publication, RemoteParticipant participant)
{
if (track is RemoteVideoTrack videoTrack)
{
AddVideoTrack(videoTrack);
}
else if (track is RemoteAudioTrack audioTrack)
{
GameObject audObject = new GameObject(audioTrack.Sid);
var source = audObject.AddComponent<AudioSource>();
var stream = new AudioStream(audioTrack, source);
_audioObjects[audioTrack.Sid] = audObject;
_rtcAudioSources.Add(stream.AudioSource);
}
}
void UnTrackSubscribed(IRemoteTrack track, RemoteTrackPublication publication, RemoteParticipant participant)
{
if (track is RemoteVideoTrack videoTrack)
{
var imgObject = _videoObjects[videoTrack.Sid];
if(imgObject != null)
{
Destroy(imgObject);
}
_videoObjects.Remove(videoTrack.Sid);
}
else if (track is RemoteAudioTrack audioTrack)
{
var audObject = _audioObjects[audioTrack.Sid];
if (audObject != null)
{
var source = audObject.GetComponent<AudioSource>();
source.Stop();
Destroy(audObject);
}
_audioObjects.Remove(audioTrack.Sid);
}
}
void DataReceived(byte[] data, Participant participant, DataPacketKind kind, string topic)
{
var str = System.Text.Encoding.Default.GetString(data);
Debug.Log("DataReceived: from " + participant.Identity + ", data " + str);
UpdateStatusText("DataReceived: from " + participant.Identity + ", data " + str);
}
public IEnumerator publishMicrophone()
{
Debug.Log("publicMicrophone!");
// Publish Microphone
var localSid = "my-audio-source";
GameObject audObject = new GameObject(localSid);
_audioObjects[localSid] = audObject;
var rtcSource = new MicrophoneSource(audObject.AddComponent<AudioSource>());
rtcSource.Configure(Microphone.devices[0], true, 2, (int)RtcAudioSource.DefaultMirophoneSampleRate);
Debug.Log($"CreateAudioTrack");
var track = LocalAudioTrack.CreateAudioTrack("my-audio-track", rtcSource, room);
var options = new TrackPublishOptions();
options.AudioEncoding = new AudioEncoding();
options.AudioEncoding.MaxBitrate = 64000;
options.Source = TrackSource.SourceMicrophone;
Debug.Log("PublishTrack!");
var publish = room.LocalParticipant.PublishTrack(track, options);
yield return publish;
if (!publish.IsError)
{
Debug.Log("Track published!");
}
_rtcAudioSources.Add(rtcSource);
yield return rtcSource.PrepareAndStart();
}
public IEnumerator publishVideo()
{
//var rt = new RenderTexture(1280, 720, 24, RenderTextureFormat.ARGB32);
//rt.Create();
//var source = new TextureVideoSource(rt);
var source = new WebCameraSource(webCamTexture);
//var source = new ScreenVideoSource();
//Camera.main.enabled = true;
//var source = new CameraVideoSource(Camera.main);
GameObject imgObject = new GameObject("camera");
RectTransform trans = imgObject.AddComponent<RectTransform>();
trans.localScale = Vector3.one;
trans.sizeDelta = new Vector2(180, 120);
RawImage image = imgObject.AddComponent<RawImage>();
source.TextureReceived += (txt) => {
image.texture = txt;
};
imgObject.transform.SetParent(layoutGroup.gameObject.transform, false);
//var source = new TextureVideoSource(webCamTexture);
var track = LocalVideoTrack.CreateVideoTrack("my-video-track", source, room);
var options = new TrackPublishOptions();
options.VideoCodec = VideoCodec.H264;
var videoCoding = new VideoEncoding();
videoCoding.MaxBitrate = 512000;
videoCoding.MaxFramerate = frameRate;
options.VideoEncoding = videoCoding;
options.Simulcast = true;
options.Source = TrackSource.SourceCamera;
var publish = room.LocalParticipant.PublishTrack(track, options);
yield return publish;
if (!publish.IsError)
{
Debug.Log("Track published!");
}
source.Start();
StartCoroutine(source.Update());
_rtcVideoSources.Add(source);
}
public void publishData()
{
var str = "hello from unity!";
// Option 1: Using data streams
StartCoroutine(PerformSendText(str));
// Option 2: Using publish data
// PerformPublishData(str);
}
private IEnumerator PerformSendText(string message)
{
var sendTextCall = room.LocalParticipant.SendText(message, "my-topic");
yield return sendTextCall;
if (sendTextCall.IsError)
{
Debug.LogError("Failed to send text: " + sendTextCall.Error);
yield break;
}
Debug.Log("Text sent successfully");
}
private void PerformPublishData(string message)
{
var enc = System.Text.Encoding.Default.GetBytes(message);
room.LocalParticipant.PublishData(enc);
}
private IEnumerator HandleTextStream(TextStreamReader reader, string identity)
{
var readAllCall = reader.ReadAll();
yield return readAllCall;
if (readAllCall.IsError)
{
Debug.LogError("Failed to read stream: " + readAllCall.Error);
yield break;
}
var message = readAllCall.Text;
Debug.Log($"Received message from {identity}: {message}");
}
public IEnumerator OpenCamera()
{
int maxl = Screen.width;
if (Screen.height > Screen.width)
{
maxl = Screen.height;
}
yield return Application.RequestUserAuthorization(UserAuthorization.WebCam);
if (Application.HasUserAuthorization(UserAuthorization.WebCam))
{
if (webCamTexture != null)
{
webCamTexture.Stop();
}
int i = 0;
while (WebCamTexture.devices.Length <= 0 && 1 < 300)
{
yield return new WaitForEndOfFrame();
i++;
}
WebCamDevice[] devices = WebCamTexture.devices;
if (WebCamTexture.devices.Length <= 0)
{
Debug.LogError("No camera device available, please check");
}
else
{
string devicename = devices[0].name;
webCamTexture = new WebCamTexture(devicename, maxl, maxl == Screen.height ? Screen.width : Screen.height, frameRate)
{
wrapMode = TextureWrapMode.Repeat
};
/*
GameObject imgObject = new GameObject("camera");
RectTransform trans = imgObject.AddComponent<RectTransform>();
trans.localScale = Vector3.one;
trans.sizeDelta = new Vector2(180, 120);
RawImage image = imgObject.AddComponent<RawImage>();
image.texture = webCamTexture;
imgObject.transform.SetParent(layoutGroup.gameObject.transform, false);
*/
webCamTexture.Play();
}
}
else
{
Debug.LogError("Camera permission not obtained");
}
}
private void OnApplicationPause(bool pause)
{
if (webCamTexture != null)
{
if (pause)
{
webCamTexture.Pause();
}
else
{
webCamTexture.Play();
}
}
}
private void OnDestroy()
{
if (webCamTexture != null)
{
webCamTexture.Stop();
}
}
}