/
anbox-stream-sdk.js
4211 lines (3751 loc) · 143 KB
/
anbox-stream-sdk.js
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
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* This file is part of Anbox Cloud Streaming SDK
*
* Version: 1.21.0
*
* Copyright 2021 Canonical Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Error return when the actual error is unknown
export const ANBOX_STREAM_SDK_ERROR_UNKNOWN = 0;
// Error returned when an invalid argument was provided
export const ANBOX_STREAM_SDK_ERROR_INVALID_ARGUMENT = 1;
// Error returned when signaling has failed
export const ANBOX_STREAM_SDK_ERROR_SIGNALING_FAILED = 2;
// Error returned when the used connector returned an error
export const ANBOX_STREAM_SDK_ERROR_CONNECTOR_FAILED = 3;
// Error returned when a certain operation or environment is not supported
export const ANBOX_STREAM_SDK_ERROR_NOT_SUPPORTED = 4;
// Error returned when an operation is not allowed
export const ANBOX_STREAM_SDK_ERROR_NOT_ALLOWED = 5;
// Error returned when the AnboxStream object has run into an internal error
export const ANBOX_STREAM_SDK_ERROR_INTERNAL = 6;
// Error returned when an operation timed out
export const ANBOX_STREAM_SDK_ERROR_TIMEOUT = 7;
// Error returned when creating or joining a session has failed
export const ANBOX_STREAM_SDK_ERROR_SESSION_FAILED = 8;
// Error returned when WebRTC has failed without further details
export const ANBOX_STREAM_SDK_ERROR_WEBRTC_FAILED = 9;
// Error returned when the WebRTC connection got disconnected
export const ANBOX_STREAM_SDK_ERROR_WEBRTC_LOST_CONNECTION = 10;
// Error returned when the signaling process timed out
export const ANBOX_STREAM_SDK_ERROR_SIGNALING_TIMEOUT = 11;
// Error returned when using the browsers media devices failed
export const ANBOX_STREAM_SDK_ERROR_USER_MEDIA = 12;
// Error returned when an error occured on the WebRTC control data channel
export const ANBOX_STREAM_SDK_ERROR_WEBRTC_CONTROL_FAILED = 13;
// Error returned when the WebRTC connection gets disconnected by the
// server side
export const ANBOX_STREAM_SDK_ERROR_WEBRTC_DISCONNECTED = 14;
// The maximum supported client API version
export const ANBOX_STREAM_SDK_MAX_CLIENT_API_VERSION = 2;
// See https://datatracker.ietf.org/doc/html/rfc4960#section-3.3.10
const SCP_CAUSE_CODE_USER_INITIATED_ABORT = 12;
function newError(msg, code) {
var options = {
cause: {
code: ANBOX_STREAM_SDK_ERROR_UNKNOWN,
},
};
if (Number.isInteger(code)) options.cause.code = code;
return new Error(msg, options);
}
class AnboxStream {
/**
* AnboxStream creates a connection between your client and an Android instance and
* displays its video & audio feed in an HTML5 player
* @param options: {object}
* @param options.connector {object} WebRTC Stream connector.
* @param options.targetElement {string} ID of the DOM element to attach the video to.
* @param [options.fullScreen=false] {boolean} Stream video in full screen mode.
* @param [options.deviceType] {string} Send the type of device the SDK is running on to the Android container.
* @param [options.enableStats] {boolean} Enable collection of statistics. Not recommended in production.
* @param [options.apiVersion=2] {integer} API version to use.
* @param [options.stream] {object} Configuration settings for the streaming.
* @param [options.stream.video=true] {boolean} Enable video stream when starting streaming.
* @param [options.stream.audio=true] {boolean} Enable audio stream when starting streaming.
* @param [options.stunServers] {object[]} List of additional STUN/TURN servers.
* @param [options.stunServers[].urls] {string[]} URLs the same STUN/TURN server can be reached on.
* @param [options.stunServers[].username] {string} Username used when authenticating with the STUN/TURN server.
* @param [options.stunServers[].password] {string} Password used when authenticating with the STUN/TURN server.
* @param [options.devices] {object} Configuration settings for the streaming client device.
* @param [options.devices.microphone=false] {boolean} Enable audio capture from microphone and send it to the remote peer.
* @param [options.devices.camera=false] {boolean} Enable video capture from camera and send it to the remote peer.
* @param [options.devices.speaker=true] {boolean} Enable audio playout through the default audio playback device.
* @param [options.controls] {object} Configuration how the client can interact with the stream.
* @param [options.controls.keyboard=true] {boolean} Send key presses to the Android instance.
* @param [options.controls.emulateTouch=false] {boolean} Emulate touchscreen by converting mouse inputs to touch inputs
* @param [options.controls.mouse=true] {boolean} Send mouse events to the Android instance.
* @param [options.controls.gamepad=true] {boolean} Send gamepad events to the Android instance.
* @param [options.foregroundActivity] {string} Activity to be displayed in the foreground. NOTE: it only works with an application that has APK provided on its creation.
* @param [options.callbacks] {object} A list of callbacks to react on stream lifecycle events.
* @param [options.callbacks.ready=none] {function} Called when the video and audio stream are ready to be inserted in the DOM.
* @param [options.callbacks.error=none] {function} Called on stream error with the message as parameter.
* @param [options.callbacks.done=none] {function} Called when the stream is closed.
* @param [options.callbacks.messageReceived=none] {function} Called when a message is received from Anbox.
* @param [options.callbacks.statsUpdated=none] {function} Called when the overall webrtc peer connection statistics are updated.
* @param [options.callbacks.requestCameraAccess=none] {function} Called when Android application tries to open camera device for video streaming.
* @param [options.callbacks.requestMicrophoneAccess=none] {function} Called when Android application tries to open microphone device for video streaming.
* @param [options.callbacks.vhalReady=none] {function} Called when the VHAL manager has been initialised.
* @param [options.dataChannels] {object} Map of data channels used to exchange out of band data between WebRTC client and application running in Android container.
* @param [options.dataChannels[name].callbacks] {object} A list of event handling callbacks of one specific data channel.
* @param [options.dataChannels[name].callbacks.open=none] {function} A callback function that is triggered when the data channel is opened.
* @param [options.dataChannels[name].callbacks.message=none] {function} A callback function that is triggered when a message has been received from the remote peer.
* @param [options.dataChannels[name].callbacks.close=none] {function} A callback function that is triggered when the data channel has closed.
* @param [options.dataChannels[name].callbacks.error=none] {function} A callback function that is triggered when an error occurs on the data channel.
* @param [options.video] {object} Configuration settings for the video streaming.
* @param [options.video.preferred_decoder_codecs] {object} A list of preferred video decoder codecs that are used by the client. Can be one or more video codecs: AV1, H264, VP8, VP9.
* @param [options.experimental] {object} Experimental features. Not recommended on production.
* @param [options.experimental.disableBrowserBlock=false] {boolean} Don't throw an error if an unsupported browser is detected.
* @param [options.experimental.emulatePointerEvent=true] {boolean} Emulate pointer events when their coordinates are outside of the video element.
* @param [options.experimental.upscaling] {object} Experimental video upscaling features.
* @param [options.experimental.upscaling.enabled=false] {boolean} Enable upscaling for video streaming on the client side. Currently, the upscaling relies on AMD FidelityFX Super Resolution 1.0 (FSR).
* @param [options.experimental.upscaling.fragmentShader] {string} Use a custom fragment shader source for upscaling instead of the default one, which is based on AMD FidelityFX Super Resolution 1.0 (FSR).
* @param [options.experimental.upscaling.useTargetFrameRate=false] {boolean} Use target refresh frame rate for the canvas when rendering video frames rather than relying on HTMLVideoElement.requestVideoFrameCallback() function even if it's supported by the browser due to the fact that the callback can occasionally be fired one v-sync late.
* @param [options.experimental.debug=false] {boolean} Print debug logs
* @param [options.experimental.pointerLock=false] {boolean} Pointer lock provides input events based on the movement of the mouse over time, not the absolute position. If enabled, the mouse will be locked to the stream view.
*/
constructor(options) {
if (this._nullOrUndef(options)) {
throw newError(
"missing options",
ANBOX_STREAM_SDK_ERROR_INVALID_ARGUMENT
);
}
this._fillDefaults(options);
this._validateOptions(options);
this._options = options;
if (!this._options.experimental.disableBrowserBlock)
this._detectUnsupportedBrowser();
this._id = Math.random().toString(36).substr(2, 9);
this._containerID = options.targetElement;
this._videoID = "anbox-stream-video-" + this._id;
this._audioID = "anbox-stream-audio-" + this._id;
this._canvasID = "anbox-stream-canvas-" + this._id;
// WebRTC
this._webrtcManager = new AnboxWebRTCManager({
apiVersion: this._options.apiVersion,
enableSpeakers: this._options.devices.speaker,
enableMic: this._options.devices.microphone,
enableCamera: this._options.devices.camera,
enableAudioStream: this._options.stream.audio,
enableVideoStream: this._options.stream.video,
deviceType: this._options.deviceType,
dataChannels: this._options.dataChannels,
foregroundActivity: this._options.foregroundActivity,
stats: {
overlayID: this._containerID,
enable: this._options.enableStats,
},
debug: this._options.experimental.debug,
preferredVideoDecoderCodecs: this._options.video.preferred_decoder_codecs,
});
this._webrtcManager.onReady(this._webrtcReady.bind(this));
this._webrtcManager.onError((err) => {
this._stopStreamingOnError(err.message, err.cause.code);
});
this._webrtcManager.onClose(this._stopStreaming.bind(this));
this._webrtcManager.onStatsUpdated(this._options.callbacks.statsUpdated);
this._webrtcManager.onMessage(this._options.callbacks.messageReceived);
this._webrtcManager.onCameraRequested(
this._options.callbacks.requestCameraAccess
);
this._webrtcManager.onMicrophoneRequested(
this._options.callbacks.requestMicrophoneAccess
);
this._webrtcManager.onIMEStateChanged(this._IMEStateChanged.bind(this));
this._webrtcManager.onDiscoverMessageReceived((msg) => {
if (this._streamCanvas) this._streamCanvas.setTargetFps(msg.fps);
if (msg.capabilities?.includes?.("vhal")) {
this._vhalManager = new AnboxVhalManager(
this._webrtcManager,
this._options.callbacks.vhalReady
);
this._webrtcManager.onVhalPropConfigsReceived(
this._vhalManager.onVhalPropConfigsReceived.bind(this._vhalManager)
);
this._webrtcManager.onVhalGetAnswerReceived(
this._vhalManager.onVhalGetAnswerReceived.bind(this._vhalManager)
);
this._webrtcManager.onVhalSetAnswerReceived(
this._vhalManager.onVhalSetAnswerReceived.bind(this._vhalManager)
);
}
});
this._webrtcManager.onControlChannelOpen(() => {
this._webrtcManager._isControlChannelOpen = true;
if (this._nullOrUndef(this._vhalManager)) return;
// Request all vhal prop configs from the server to populate the vhal
// manager cache
this._webrtcManager.sendControlMessage("vhal::get-all-prop-configs");
});
// Control options
this._modifierState = 0;
this._dimensions = null;
this._gamepadManager = null;
this._streamCanvas = null;
this._originalOrientation = null;
this._currentRotation = 0;
this._primaryTouchId = 0;
this._pointersOutofBounds = {};
this._activeTouchPointers = [];
this._pointerIdsMapper = {};
this.controls = {
touch: {
pointermove: this._onPointerEvent.bind(this),
pointerdown: this._onPointerEvent.bind(this),
pointerup: this._onPointerEvent.bind(this),
pointercancel: this._onPointerEvent.bind(this),
mousewheel: this._onMouseWheel.bind(this),
},
keyboard: {
keydown: this._onKey.bind(this),
keyup: this._onKey.bind(this),
gamepadconnected: this._queryGamePadEvents.bind(this),
},
};
this.releaseKeyboard = this.releaseKeyboard.bind(this);
this.captureKeyboard = this.captureKeyboard.bind(this);
this._onResize = this._onResize.bind(this);
}
/**
* Connect a new instance for the configured application or attach to an existing one
*/
async connect() {
if (this._options.fullScreen) this._requestFullscreen();
let session = {};
try {
// Create media in the try-catch block in case of an exception being thrown
this._createMedia();
session = await this._options.connector.connect();
} catch (e) {
this._stopStreamingOnError(
"connector failed to connect: " + e.message,
ANBOX_STREAM_SDK_ERROR_CONNECTOR_FAILED
);
return;
}
try {
this._webrtcManager.start(session);
} catch (e) {
this._stopStreamingOnError(e);
return;
}
}
/**
* Disconnect an existing stream and remove the video & audio elements.
*
* This will stop the underlying Android instance.
*/
disconnect() {
this._stopStreaming();
this._options.connector.disconnect();
}
/**
* Show overall statistics in an overlay during the streaming.
* For more detailed information, refer to https://www.w3.org/TR/webrtc-stats/
*
* video: Statistics on the received video track.
* bandwidthMbit: Video traffic received in mbits/s.
* totalBytesReceived: Total cumulated bytes received for the current session.
* fps: Current frames per second.
* decodeTime: Average time in seconds to decode a frame.
* jitter: Total cumulated packet delay in seconds. A high jitter can mean an unstable or congested network.
* avgJitterBufferDelay: Average variance in packet delay in seconds. A high jitter can mean an unstable or congested network.
* packetsReceived: Total number of packets received.
* packetsLost: Total number of packets lost.
* totalAssemblyTime: The sum of the time, in seconds, each video frame takes from the time the first RTP packet is received (reception timestamp) and to the time the last RTP packet of a frame is received.
* framesAssembledFromMultiplePackets: Only exists for video. It represents the total number of frames correctly decoded for this RTP stream that consist of more than one RTP packet. For such frames the totalAssemblyTime is incremented.
* network: Information about the network and WebRTC connections.
* currentRtt: Current round trip time in seconds.
* networkType: Type of network in use (NOTE: It's deprecated to preserve the privacy). Can be one of the following:
* bluetooth: This connection uses bluetooth.
* celullar: The connection uses a cellular data service to connect. This includes all cellular data services including EDGE (2G), HSPA (3G), LTE (4G), and NR (5G).
* ethernet: This connection uses an ethernet network.
* wifi: This connection uses WiFi.
* wimax: This connection uses a Wimax network.
* vpn: This connection uses a VPN which obscures the underlying connection type.
* unknown: The user's browser is unable or unwilling to identify the underlying connection technology used by the described connection.
* transportType: Network protocol in use.
* localCandidateType: Type of the local client WebRTC candidate. Can be one of the following:
* host: Local client is accessible directly via IP.
* srflx: Local client is accessible behind NAT.
* prflx: Local client is accessible behind a symmetric NAT.
* relay: Traffic is relayed to the local client via a TURN server. Relayed traffic can induce poor performance.
* remoteCandidateType: Type of the remote peer (Anbox container) WebRTC candidate. Can be one of the following:
* host: Remote peer is accessed directly via IP.
* srflx: Remote peer is accessed behind NAT.
* prflx: Remote peer is accessed behind a symmetric NAT.
* relay: Traffic is relayed to the remote peer via a TURN server. Relayed traffic can induce poor performance.
* audioInput: Statistics related to the audio sent to the Anbox container
* bandwidthMbit: Audio traffic sent in mbits/s
* totalBytesSent: Total cumulated bytes sent for audio for the current session.
* audioOutput: Information on the received audio track.
* bandwidthMbit: Audio traffic received in mbits/s.
* totalBytesReceived: Total cumulated bytes received for the current session.
* jitter: Total cumulated packet delay in seconds. A high jitter can mean an unstable or congested network.
* avgJitterBufferDelay: Average variance in packet delay in seconds. A high jitter can mean an unstable or congested network.
* totalSamplesReceived: Total number of audio samples received for the current session.
* packetsReceived: Total number of packets received.
* packetsLost: Total number of packets lost.
* rtcConfig: Information on the WebRTC connection
* bundlePolicy: Policy on how to negotiate tracks if the remote peer is not bundle aware. If bundle aware, all tracks are generated on the same transport. Can be one of the following:
* balanced: Gather ICE candidates for each media type in use (audio, video, and data). If the remote endpoint is not bundle-aware, negotiate only one audio and video track on separate transports.
* max-compat: Gather ICE candidates for each track. If the remote endpoint is not bundle-aware, negotiate all media tracks on separate transports.
* max-bundle: Gather ICE candidates for only one track. If the remote endpoint is not bundle-aware, negotiate only one media track.
* rtcpMuxPolicy: Affects what ICE candidates are gathered to support non-multiplexed RTCP. The only value "require".
* sdpSemantics: Describes which style of SDP offers and answers is used.
* iceTransportPolicy: Policy for accepting ICE candidates. Can be one of the following:
* all: Accept all candidates.
* relay: Only accept candidates whose IP are being relayed, such as via a TURN server.
* iceCandidatePoolSize: Size of the prefetched ICE candidate pool.
* experimental: Information on the experimental metrics.
* canvas: Information on the WebGL-based canvas.
* fps: Current frames per second on the rendering on the canavs.
*/
showStatistics(enabled) {
if (enabled) this._webrtcManager.showStatsOverlay();
else this._webrtcManager.hideStatsOverlay();
}
/**
* Toggle fullscreen for the streamed video.
*
* IMPORTANT: fullscreen can only be toggled following a user input.
* If you call this method when your page loads, it will not work.
*/
_requestFullscreen() {
if (!document.fullscreenEnabled) {
console.error("fullscreen not supported");
return;
}
const fullscreenExited = () => {
if (document.fullscreenElement === null) {
const video = document.getElementById(this._videoID);
if (video) {
video.style.width = null;
video.style.height = null;
}
this._onResize();
}
};
// Clean up previous event listeners
document.removeEventListener("fullscreenchange", fullscreenExited, false);
document.addEventListener("fullscreenchange", fullscreenExited, false);
// We don't put the video element itself in fullscreen because of
// https://bugs.chromium.org/p/chromium/issues/detail?id=462164
// To work around it we put the outer container in fullscreen and scale the video
// to fit it. When exiting fullscreen we undo style changes done to the video element
const videoContainer = document.getElementById(this._containerID);
if (videoContainer.requestFullscreen) {
videoContainer.requestFullscreen().catch((err) => {
console.log(
`Failed to enter full-screen mode: ${err.message} (${err.name})`
);
});
} else if (videoContainer.mozRequestFullScreen) {
/* Firefox */
videoContainer.mozRequestFullScreen();
} else if (videoContainer.webkitRequestFullscreen) {
/* Chrome, Safari and Opera */
videoContainer.webkitRequestFullscreen();
} else if (videoContainer.msRequestFullscreen) {
/* IE/Edge */
videoContainer.msRequestFullscreen();
}
}
/**
* Exit fullscreen mode.
*/
exitFullscreen() {
if (document.exitFullscreen) {
document.exitFullscreen();
} else if (document.webkitExitFullscreen) {
document.webkitExitFullscreen();
} else if (document.mozCancelFullScreen) {
document.mozCancelFullScreen();
} else if (document.msExitFullscreen) {
document.msExitFullscreen();
}
}
/**
* Return the stream ID you can use to access video and audio elements with getElementById
* To access the video element, append "anbox-stream-video-" to the ID.
* To access the audio element, append "anbox-stream-audio-" to the ID.
* Ex: 'anbox-stream-video-rk8a12k'
*/
getId() {
return this._id;
}
/**
* Enable touch emulation. All mouse inputs are translated to act like touch inputs.
*/
enableTouchEmulation() {
this._options.controls.emulateTouch = true;
}
/**
* Disable touch emulation
*/
disableTouchEmulation() {
this._options.controls.emulateTouch = false;
}
/**
* Send a location update to the connected Android instance
*
* For WGS84 format gps data, where a numeric latitude or longitude is given, geographic coordinates are
* expressed as decimal fractions. With this system the geo coordinate of Berlin is: latitude 52.520008°, longitude 13.404954°.
*
* For NMEA format gps data, where a numeric latitude or longitude is given, the two digits
* immediately to the left of the decimal point are whole minutes, to the right are decimals of minutes,
* and the remaining digits to the left of the whole minutes are whole degrees.
*
* eg. 4533.35 is 45 degrees and 33.35 minutes. ".35" of a minute is exactly 21 seconds.
*
* @param update: {object}
* @param update.format {string} GPS data format ("nmea" or "wgs84" default: "wgs84")
* @param update.time {number} Time in milliseconds since the start of the epoch
* @param update.latitude {number} Latitude of the location (positive values mean northern hemisphere and negative values mean southern hemisphere)
* @param update.longitude {number} Longitude of the location (positive values mean northern hemisphere and negative values mean southern hemisphere)
* @param update.altitude {number} Altitude in meters
* @param update.speed {number} Current speed in meter per second
* @param update.bearing {number} Current bearing in degree
* @throws {Error} Incomplete location update, some fields are missing.
* @throws {Error} Invalid GPS data format, can only be "wgs84" or "nmea".
* @throws {Error} The stream SDK is not ready yet.
*/
sendLocationUpdate(update) {
if (
this._nullOrUndef(update.time) ||
this._nullOrUndef(update.latitude) ||
this._nullOrUndef(update.longitude) ||
this._nullOrUndef(update.altitude) ||
this._nullOrUndef(update.speed) ||
this._nullOrUndef(update.bearing)
) {
throw newError(
"incomplete location update",
ANBOX_STREAM_SDK_ERROR_INVALID_ARGUMENT
);
}
if (
!this._nullOrUndef(update.format) &&
update.format !== "nmea" &&
update.format !== "wgs84"
) {
throw newError(
"invalid gps data format",
ANBOX_STREAM_SDK_ERROR_INVALID_ARGUMENT
);
}
return this._webrtcManager.sendControlMessage(
"location::update-position",
update
);
}
/**
* VHAL get call for multiple properties.
* @param properties {array} Array of objects, see below.
* @param properties.prop {Number} Property ID
* @param properties.area_id {Number} Area ID
* @param properties.int32_values {Array} Array of integers: required only for some properties.
* @param properties.float_values {Array} Array of floats: required only for some properties.
* @param properties.int64_values {Array} Array of integers: required only for some properties.
* @param properties.bytes {Array} Raw bytes value as array of integers: required only for some properties.
* @param properties.string_value {string} String value: required only for some properties.
*/
async getVhalProperties(properties) {
if (this._nullOrUndef(this._vhalManager))
throw newError(
"vhal not supported",
ANBOX_STREAM_SDK_ERROR_NOT_SUPPORTED
);
return this._vhalManager.get(properties);
}
/**
* VHAL set call for multiple property values.
* At least one of int32_values, float_values, int64_values, bytes or
* string_value must be provided.
* @param properties {array} Array of objects, see below.
* @param properties.prop {Number} Property ID
* @param properties.area_id {Number} Area ID
* @param properties.status {Number} Property status
* @param properties.int32_values {Array} Array of integers
* @param properties.float_values {Array} Array of floats
* @param properties.int64_values {Array} Array of integers
* @param properties.bytes {Array} Raw bytes value as array of integers
* @param properties.string_value {string} String value
*/
async setVhalProperties(properties) {
if (this._nullOrUndef(this._vhalManager))
throw newError(
"vhal not supported",
ANBOX_STREAM_SDK_ERROR_NOT_SUPPORTED
);
return this._vhalManager.set(properties);
}
/**
* Get VHAL property configs for the requested property IDs.
* Returns a copy of the stored configurations.
* @param props {Array} Array of property IDs.
*/
getVhalPropConfigs(props) {
if (this._nullOrUndef(this._vhalManager))
throw newError(
"vhal not supported",
ANBOX_STREAM_SDK_ERROR_NOT_SUPPORTED
);
return this._vhalManager.getPropConfigs(props);
}
/**
* Get all VHAL property configs.
* Returns a copy of the stored configurations.
*/
getAllVhalPropConfigs() {
if (this._nullOrUndef(this._vhalManager))
throw newError(
"vhal not supported",
ANBOX_STREAM_SDK_ERROR_NOT_SUPPORTED
);
return this._vhalManager.getAllPropConfigs();
}
/**
* Check if the VHAL functions are supported and available.
* Returns true if VHAL is supported and available, false otherwise.
*/
isVhalAvailable() {
return (
!this._nullOrUndef(this._vhalManager) && this._vhalManager.hasConfigs()
);
}
_hasWebGLSupported() {
try {
const canvas = document.createElement("canvas");
const ctx =
canvas.getContext("webgl") || canvas.getContext("experimental-webgl");
if (this._nullOrUndef(ctx)) return false;
} catch (e) {
return false;
}
return true;
}
_detectUnsupportedBrowser() {
if (
navigator.userAgent.indexOf("Chrome") === -1 &&
navigator.userAgent.indexOf("Firefox") === -1 &&
navigator.userAgent.indexOf("Safari") === -1
)
throw newError(
"unsupported browser",
ANBOX_STREAM_SDK_ERROR_NOT_SUPPORTED
);
}
_fillDefaults(options) {
if (this._nullOrUndef(options.apiVersion))
options.apiVersion = ANBOX_STREAM_SDK_MAX_CLIENT_API_VERSION;
if (this._nullOrUndef(options.fullScreen)) options.fullScreen = false;
if (this._nullOrUndef(options.controls)) options.controls = {};
if (this._nullOrUndef(options.devices)) options.devices = {};
if (this._nullOrUndef(options.devices.microphone))
options.devices.microphone = false;
if (this._nullOrUndef(options.devices.camera))
options.devices.camera = false;
if (this._nullOrUndef(options.devices.speaker))
options.devices.speaker = true;
if (this._nullOrUndef(options.controls.keyboard))
options.controls.keyboard = true;
if (this._nullOrUndef(options.controls.mouse))
options.controls.mouse = true;
if (this._nullOrUndef(options.controls.emulateTouch))
options.controls.emulateTouch = false;
if (this._nullOrUndef(options.controls.gamepad))
options.controls.gamepad = true;
if (this._nullOrUndef(options.stream)) options.stream = {};
if (this._nullOrUndef(options.stream.video)) options.stream.video = true;
if (this._nullOrUndef(options.stream.audio)) options.stream.audio = true;
if (this._nullOrUndef(options.stunServers)) options.stunServers = [];
if (this._nullOrUndef(options.callbacks)) options.callbacks = {};
if (this._nullOrUndef(options.video)) options.video = {};
if (this._nullOrUndef(options.video.preferred_decoder_codecs)) {
options.video.preferred_decoder_codecs = [];
} else {
options.video.preferred_decoder_codecs.forEach((codec) => {
const supported_codecs = ["AV1", "H264", "VP8", "VP9"];
if (
!supported_codecs.find(
(c) => c === codec || c === codec.toUpperCase()
)
)
throw newError(
"invalid video decoder codec",
ANBOX_STREAM_SDK_ERROR_INVALID_ARGUMENT
);
});
}
if (this._nullOrUndef(options.callbacks.ready))
options.callbacks.ready = () => {};
if (this._nullOrUndef(options.callbacks.error))
options.callbacks.error = () => {};
if (this._nullOrUndef(options.callbacks.done))
options.callbacks.done = () => {};
if (this._nullOrUndef(options.callbacks.messageReceived))
options.callbacks.messageReceived = () => {};
if (this._nullOrUndef(options.callbacks.requestCameraAccess))
options.callbacks.requestCameraAccess = () => false;
if (this._nullOrUndef(options.callbacks.requestMicrophoneAccess))
options.callbacks.requestMicrophoneAccess = () => false;
if (this._nullOrUndef(options.callbacks.vhalReady))
options.callbacks.vhalReady = () => {};
if (!this._nullOrUndef(options.dataChannels)) {
if (Object.keys(options.dataChannels).length > maxNumberOfDataChannels) {
throw newError(
"exceeds the maximum allowed length of data channels",
ANBOX_STREAM_SDK_ERROR_INVALID_ARGUMENT
);
}
Object.keys(options.dataChannels).forEach((name) => {
if (this._nullOrUndef(options.dataChannels[name].callbacks))
options.dataChannels[name].callbacks = {};
if (this._nullOrUndef(options.dataChannels[name].callbacks.open))
options.dataChannels[name].callbacks.open = {};
if (this._nullOrUndef(options.dataChannels[name].callbacks.close))
options.dataChannels[name].callbacks.close = {};
if (this._nullOrUndef(options.dataChannels[name].callbacks.error))
options.dataChannels[name].callbacks.error = {};
if (this._nullOrUndef(options.dataChannels[name].callbacks.message))
options.dataChannels[name].callbacks.message = {};
});
} else options.dataChannels = {};
if (this._nullOrUndef(options.foregroundActivity))
options.foregroundActivity = "";
if (this._nullOrUndef(options.deviceType)) options.deviceType = "";
if (this._nullOrUndef(options.enableStats)) options.enableStats = false;
if (this._nullOrUndef(options.experimental)) options.experimental = {};
if (this._nullOrUndef(options.experimental.disableBrowserBlock))
options.experimental.disableBrowserBlock = false;
if (this._nullOrUndef(options.experimental.emulatePointerEvent))
options.experimental.emulatePointerEvent = true;
if (this._nullOrUndef(options.experimental.upscaling))
options.experimental.upscaling = {};
if (this._nullOrUndef(options.experimental.upscaling.enabled)) {
options.experimental.upscaling.enabled = false;
} else if (
options.experimental.upscaling.enabled &&
!this._hasWebGLSupported()
) {
throw newError(
"can not enable upscaling due to lack of WebGL support",
ANBOX_STREAM_SDK_ERROR_NOT_SUPPORTED
);
}
if (this._nullOrUndef(options.experimental.upscaling.useTargetFrameRate))
options.experimental.upscaling.useTargetFrameRate = false;
if (this._nullOrUndef(options.experimental.debug))
options.experimental.debug = false;
if (this._nullOrUndef(options.experimental.pointerLock))
options.experimental.pointerLock = false;
}
_validateApiVersion(version) {
if (version > ANBOX_STREAM_SDK_MAX_CLIENT_API_VERSION || version < 0)
throw newError(
`invalid API version. Must be >= 0 and <= {ANBOX_STREAM_SDK_MAX_CLIENT_API_VERSION}`,
ANBOX_STREAM_SDK_ERROR_INVALID_ARGUMENT
);
}
_validateOptions(options) {
this._validateApiVersion(options.apiVersion);
if (this._nullOrUndef(options.targetElement)) {
throw newError(
"missing targetElement parameter",
ANBOX_STREAM_SDK_ERROR_INVALID_ARGUMENT
);
}
const container = document.getElementById(options.targetElement);
if (container === null) {
throw newError(
`target element "${options.targetElement}" does not exist`,
ANBOX_STREAM_SDK_ERROR_INVALID_ARGUMENT
);
} else if (container.clientWidth == 0 || container.clientHeight == 0)
console.error(
"AnboxStream: video container element misses size. Please see https://anbox-cloud.io/docs/howto/stream/web-client"
);
if (this._nullOrUndef(options.connector)) {
throw newError(
"missing connector",
ANBOX_STREAM_SDK_ERROR_INVALID_ARGUMENT
);
}
if (typeof options.connector.connect !== "function") {
throw newError(
'missing "connect" method on connector',
ANBOX_STREAM_SDK_ERROR_INVALID_ARGUMENT
);
}
if (typeof options.connector.disconnect !== "function") {
throw newError(
'missing "disconnect" method on connector',
ANBOX_STREAM_SDK_ERROR_INVALID_ARGUMENT
);
}
const _activityNamePattern =
/(^([A-Za-z]{1}[A-Za-z\d_]*\.){2,}|^(\.){1})[A-Za-z][A-Za-z\d_]*$/;
if (
options.foregroundActivity.length > 0 &&
!_activityNamePattern.test(options.foregroundActivity)
) {
throw newError(
"invalid foreground activity name",
ANBOX_STREAM_SDK_ERROR_INVALID_ARGUMENT
);
}
}
_createMedia() {
let mediaContainer = document.getElementById(this._containerID);
// We set the container as relative so the video element is absolute to it and not something else
mediaContainer.style.position = "relative";
// Disable native controls for touch events (zooming, panning)
mediaContainer.style.touchAction = "none";
let pointerLockElement = null;
if (this._options.stream.video) {
const video = document.createElement("video");
video.style.margin = "0";
video.style.height = "auto";
video.style.width = "auto";
// The video element is sized based on the dimensions of its container. Settings its position to "absolute"
// removes it from the flow, so the video element cannot change its parent dimensions.
video.style.position = "absolute";
video.muted = true;
video.autoplay = true;
video.controls = false;
video.id = this._videoID;
video.playsInline = true;
// Disable context menu so we can properly handle right clicks on the video
video.setAttribute("oncontextmenu", "return false;");
video.onplay = () => {
this._onResize();
this._registerControls();
this._options.callbacks.ready();
};
video.onloadedmetadata = () => {
// NOTE: the video frame may not be received or fully decoded yet
// when the onplay callback is fired, which may cause
// - WebGL to fail in reading first frames from the video element.
// - The video.videoWidth and video.videoHeight always stay to zero
// when its display style is none (E.g. the upscaling is enabled)
// Hence we do not start rendering until metadata event is fired.
this._onResize();
if (
this._options.experimental.upscaling.enabled &&
this._streamCanvas
) {
this._streamCanvas.startRendering();
}
};
mediaContainer.appendChild(video);
pointerLockElement = video;
const upscaling = this._options.experimental.upscaling;
if (upscaling.enabled) {
// Hide the video element and only make the canvas
// visible inside of the media container
video.style.display = "none";
this._streamCanvas = new AnboxStreamCanvas({
id: this._canvasID,
video: video,
useTargetFrameRate: upscaling.useTargetFrameRate,
fragmentShader: upscaling.fragmentShader,
});
this._streamCanvas.onFpsMeasured((fps) => {
this._webrtcManager.updateCanvasFpsStats(fps);
});
const canvas = this._streamCanvas.initialize();
mediaContainer.appendChild(canvas);
pointerLockElement = canvas;
}
}
if (this._options.stream.audio && this._options.devices.speaker) {
const audio = document.createElement("audio");
audio.id = this._audioID;
audio.autoplay = true;
audio.controls = false;
if (!this._options.stream.video) {
audio.onplay = () => {
this._options.callbacks.ready();
};
}
mediaContainer.appendChild(audio);
}
if (this._options.experimental.pointerLock && pointerLockElement !== null) {
pointerLockElement.addEventListener("click", async () => {
await pointerLockElement.requestPointerLock({});
});
}
}
_webrtcReady(videoSource, audioSource) {
if (this._options.stream.video) {
const video = document.getElementById(this._videoID);
video.srcObject = videoSource;
// Expliclity to call play() method to the video element if it's hidden,
// otherwise video can be still buffered but not playback, which caused
// the video.onplay callback won't be triggered at all.
if (video.style.display === "none") video.play();
}
if (this._options.stream.audio && this._options.devices.speaker) {
const audio = document.getElementById(this._audioID);
audio.srcObject = audioSource;
}
if (!this._options.stream.video && !this._options.stream.audio) {
this._options.callbacks.ready();
}
}
_removeMedia() {
const video = document.getElementById(this._videoID);
const audio = document.getElementById(this._audioID);
if (video) video.remove();
if (audio) audio.remove();
}
_stopStreaming() {
this._unregisterControls();
if (this._gamepadManager) {
this._gamepadManager.stopPolling();
}
this._webrtcManager.stop();
this._removeMedia();
if (this._options.experimental.upscaling.enabled) {
this._streamCanvas.stop();
const canvas = document.getElementById(this._canvasID);
if (canvas) canvas.remove();
}
this._options.callbacks.done();
}
_registerControls() {
window.addEventListener("resize", this._onResize);
if (this._options.controls.mouse) {
const container = document.getElementById(this._containerID);
if (container) {
for (const controlName in this.controls.touch)
container.addEventListener(
controlName,
this.controls.touch[controlName]
);
}
}
this.captureKeyboard();
}
/**
* Start the capture of keyboard events and send them to the Android container.
* NOTE: While keyboard events are captured, you cannot use keyboard controls outside the SDK stream.
* To re-enable keyboard events, see releaseKeyboard().
* @throws {Error} Throw if keyboard controls are disabled
*/
captureKeyboard() {
if (!this._options.controls.keyboard) {
throw newError(
"keyboard controls are disabled",
ANBOX_STREAM_SDK_ERROR_NOT_ALLOWED
);
}
for (const controlName in this.controls.keyboard)
window.addEventListener(controlName, this.controls.keyboard[controlName]);
}
/**
* Stops capturing keyboard events. Can be used when you want to use a keyboard while a stream is running.
* @throws {Error} Throw if keyboard controls are disabled
*/
releaseKeyboard() {
if (!this._options.controls.keyboard) {
throw newError(
"keyboard controls are disabled",
ANBOX_STREAM_SDK_ERROR_NOT_ALLOWED
);
}
for (const controlName in this.controls.keyboard)
window.removeEventListener(
controlName,
this.controls.keyboard[controlName]
);
}
sendIMECommittedText(text) {
const data = {
text: text,
};
return this._sendIMEMessage(_imeEventType.Text, data);
}
sendIMEComposingText(text) {
const data = {
text: text,
};
return this._sendIMEMessage(_imeEventType.ComposingText, data);