/
webrtc.js
1199 lines (1085 loc) · 41.3 KB
/
webrtc.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
import * as widgets from '@jupyter-widgets/base';
import * as _ from 'underscore';
require('webrtc-adapter');
import * as html2canvas from 'html2canvas';
import * as mqtt from 'mqtt';
import * as utils from './utils';
var semver_range = '~' + require('../package.json').version;
var MediaStreamModel = widgets.DOMWidgetModel.extend({
defaults: function() {
return _.extend(widgets.DOMWidgetModel.prototype.defaults(), {
_model_module: 'jupyter-webrtc',
_view_module: 'jupyter-webrtc',
_model_name: 'MediaStreamModel',
_view_name: 'MediaStreamView',
_model_module_version: semver_range,
_view_module_version: semver_range,
});
},
});
// Backward compatibility
Object.defineProperty(MediaStreamModel.prototype, 'stream', {
get: function() { return this.captureStream(); }
});
var captureStream = function(widget) {
if(widget.captureStream)
return widget.captureStream()
else
return widget.stream
}
var MediaStreamView = widgets.DOMWidgetView.extend({
render: function() {
MediaStreamView.__super__.render.apply(this, arguments);
window.last_media_stream_view = this;
this.video = document.createElement('video');
this.video.controls = true;
this.pWidget.addClass('jupyter-widgets');
this.pWidget.addClass('widget-image');
this.model.captureStream().then((stream) => {
this.video.srcObject = stream;
this.el.appendChild(this.video);
this.video.play();
}, (error) => {
var text = document.createElement('div');
text.innerHTML = 'Error creating view for mediastream: ' + error.message;
this.el.appendChild(text);
});
},
remove: function() {
this.model.captureStream().then((stream) => {
this.video.pause();
this.video.srcObject = null;
});
return MediaStreamView.__super__.remove.apply(this, arguments);
}
});
import {imageWidgetToCanvas} from './utils';
var ImageStreamModel = MediaStreamModel.extend({
defaults: function() {
return _.extend(MediaStreamModel.prototype.defaults(), {
_model_name: 'ImageStreamModel',
image: null
});
},
initialize: function() {
ImageStreamModel.__super__.initialize.apply(this, arguments);
window.last_image_stream = this;
this.canvas = document.createElement('canvas');
this.context = this.canvas.getContext('2d');
this.canvas.width = this.get('width');
this.canvas.height = this.get('height')
// I was hoping this should do it
imageWidgetToCanvas(this.get('image'), this.canvas)
this.get('image').on('change:value', () => {
this.sync_image()
})
},
sync_image: function() {
// not sure if firefox uses moz prefix also on a canvas
if(this.canvas.captureStream) {
// TODO: add a fps trait
// but for some reason we need to do it again
imageWidgetToCanvas(this.get('image'), this.canvas)
} else {
reject(new Error('captureStream not supported for this browser'));
}
},
captureStream: async function() {
this.sync_image()
return this.canvas.captureStream();
},
close: function() {
var returnValue = ImageStreamModel.__super__.close.apply(this, arguments);
return returnValue;
}
}, {
serializers: _.extend({
image: { deserialize: widgets.unpack_models },
}, MediaStreamModel.serializers)
});
var StreamModel = MediaStreamModel.extend({
defaults: function() {
return _.extend(MediaStreamModel.prototype.defaults(), {
playing: true,
});
},
initialize: function() {
StreamModel.__super__.initialize.apply(this, arguments);
this.media = undefined;
this.on('change:playing', this.updatePlay, this);
},
captureStream: async function() {
if (!this.createView) {
this.createView = _.once(() => {
return this.widget_manager.create_view(this.get(this.type)).then((view) => {
this.media_wid = view;
this.media = this.media_wid.el;
});
});
}
let widget = this.get(this.type);
if(!widget)
throw new Error('no media widget passed')
await this.createView();
if(this.media.captureStream || this.media.mozCaptureStream) {
// following https://github.com/webrtc/samples/blob/gh-pages/src/content/capture/video-pc/js/main.js
var makeStream = () => {
this.updatePlay();
if(this.media.captureStream) {
return this.media.captureStream();
} else if(this.media.mozCaptureStream) {
return this.media.mozCaptureStream();
}
};
await utils.onCanPlay(this.media);
return makeStream()
} else {
throw new Error('captureStream not supported for this browser');
}
},
updatePlay: function() {
if(this.get('playing')) {
this.media.play();
} else {
this.media.pause();
}
},
close: function() {
var returnValue = StreamModel.__super__.close.apply(this, arguments);
this.media.pause();
this.media_wid.close();
return returnValue;
}
});
var VideoStreamModel = StreamModel.extend({
defaults: function() {
return _.extend(StreamModel.prototype.defaults(), {
_model_name: 'VideoStreamModel',
video: null,
});
},
initialize: function() {
VideoStreamModel.__super__.initialize.apply(this, arguments);
window.last_video_stream = this;
this.type = 'video';
},
}, {
serializers: _.extend({
video: { deserialize: widgets.unpack_models },
}, StreamModel.serializers)
});
var AudioStreamModel = StreamModel.extend({
defaults: function() {
return _.extend(StreamModel.prototype.defaults(), {
_model_name: 'AudioStreamModel',
_view_name: 'AudioStreamView',
audio: undefined,
});
},
initialize: function() {
AudioStreamModel.__super__.initialize.apply(this, arguments);
window.last_audio_stream = this;
this.type = 'audio';
},
}, {
serializers: _.extend({
audio: { deserialize: widgets.unpack_models },
}, StreamModel.serializers)
});
var AudioStreamView = widgets.DOMWidgetView.extend({
render: function() {
AudioStreamView.__super__.render.apply(this, arguments);
window.last_audio_stream_view = this;
this.audio = document.createElement('audio');
this.audio.controls = true;
this.pWidget.addClass('jupyter-widgets');
this.model.captureStream().then((stream) => {
this.audio.srcObject = stream;
this.el.appendChild(this.audio);
this.audio.play();
}, (error) => {
var text = document.createElement('div');
text.innerHTML = 'Error creating view for mediastream: ' + error.message;
this.el.appendChild(text);
});
},
remove: function() {
this.model.captureStream().then((stream) => {
this.audio.pause();
this.audio.srcObject = null;
});
return widgets.DOMWidgetView.__super__.remove.apply(this, arguments);
}
});
var WidgetStreamModel = MediaStreamModel.extend({
defaults: function() {
return _.extend(MediaStreamModel.prototype.defaults(), {
_model_name: 'WidgetStreamModel',
_view_name: 'WidgetStreamView',
widget: null,
max_fps: null,
_html2canvas_start_streaming: false,
})
},
initialize: function() {
WidgetStreamModel.__super__.initialize.apply(this, arguments);
this.on('change:_html2canvas_start_streaming', this.updateHTML2CanvasStreaming, this);
this.rendered_view = null;
// If the widget already has a captureStream -> use it
if (typeof this.get('widget').captureStream == 'function') {
// TODO: use the fps attr of captureStream once it's here
this.captureStream = () => {
return this.get('widget').captureStream();
};
}
// Else try to stream the first view of this widget
else {
this.captureStream = () => {
var id_views = Object.keys(this.get('widget').views);
if (id_views.length == 0) {
return new Promise((resolve, reject) => {
reject({'message': 'Cannot create WidgetStream if the widget has no view rendered'});
});
}
var first_view = this.get('widget').views[id_views[0]];
return first_view.then((view) => {
this.rendered_view = view;
// If the widget view is a canvas or a video element
var capturable_obj = this.find_capturable_obj(this.rendered_view.el);
if (capturable_obj) {
// TODO: use the fps attr of captureStream once it's here
return this._captureStream(capturable_obj);
}
// Else use html2canvas
this.canvas = document.createElement('canvas');
this.set('_html2canvas_start_streaming', true);
// TODO: use the fps attr of captureStream once it's here
return this._captureStream(this.canvas);
});
};
}
},
_captureStream: function(capturable_obj) {
return new Promise((resolve, reject) => {
var fps = this.get('max_fps');
if (capturable_obj.captureStream) {
if (fps || fps == 0) {
resolve(capturable_obj.captureStream(fps));
} else {
resolve(capturable_obj.captureStream());
}
}
if (capturable_obj.mozCaptureStream) {
if (fps || fps == 0) {
resolve(capturable_obj.mozCaptureStream(fps));
} else {
resolve(capturable_obj.mozCaptureStream());
}
}
reject(new Error('captureStream not supported for this browser'));
});
},
find_capturable_obj: function(element) {
var nb_children = element.children.length;
for (var child_idx = 0; child_idx < nb_children; child_idx++) {
var child = element.children[child_idx];
if (child.captureStream || child.mozCaptureStream) {
return child;
}
var capturable_obj = this.find_capturable_obj(child);
if (capturable_obj) {
return capturable_obj;
}
}
},
updateHTML2CanvasStreaming: function() {
if (this.get('_html2canvas_start_streaming') && !this.html2CanvasStreaming) {
this.html2CanvasStreaming = true;
var lastTime;
var updateStream = (currentTime) => {
if (!this._closed) {
if (!lastTime) {
lastTime = currentTime;
}
var timeSinceLastFrame = currentTime - lastTime;
lastTime = currentTime;
var fps = this.get('max_fps');
if (fps == 0) {
/* TODO: maybe implement the same behavior as here:
https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/captureStream */
} else {
var waitingTime = 0;
if (fps != null) {
waitingTime = 1000/fps - timeSinceLastFrame;
if (waitingTime < 0) {
waitingTime = 0;
}
}
setTimeout(() => {
html2canvas(this.rendered_view.el, {
canvas: this.canvas,
logging: false,
useCORS: true,
ignoreElements: (element) => {
return !(
// Do not ignore if the element contains what we want to render
element.contains(this.rendered_view.el) ||
// Do not ignore if the element is contained by what we want to render
this.rendered_view.el.contains(element) ||
// Do not ignore if the element is contained by the head (style and scripts)
document.head.contains(element)
);
},
}).then(() => {
window.requestAnimationFrame(updateStream);
});
}, waitingTime);
}
}
};
window.requestAnimationFrame(updateStream);
}
}
}, {
serializers: _.extend({
widget: { deserialize: widgets.unpack_models },
}, MediaStreamModel.serializers)
});
var WidgetStreamView = MediaStreamView.extend({
});
var CameraStreamModel = MediaStreamModel.extend({
defaults: function() {
return _.extend(MediaStreamModel.prototype.defaults(), {
_model_name: 'CameraStreamModel',
constraints: {audio: true, video: true}
});
},
captureStream: function() {
if(!this.cameraStream) {
this.cameraStream = navigator.mediaDevices.getUserMedia(this.get('constraints'));
}
return this.cameraStream;
},
close: function() {
if(this.cameraStream) {
this.cameraStream.then((stream) => {
stream.getTracks().forEach((track) => {
track.stop();
});
});
}
return CameraStreamModel.__super__.close.apply(this, arguments);
}
});
var RecorderModel = widgets.DOMWidgetModel.extend({
defaults: function() {
return _.extend(widgets.DOMWidgetModel.prototype.defaults(), {
_model_module: 'jupyter-webrtc',
_view_module: 'jupyter-webrtc',
_model_module_version: semver_range,
_view_module_version: semver_range,
stream: null,
filename: 'record',
format: 'webm',
recording: false,
_data_src: '',
})
},
initialize: function() {
RecorderModel.__super__.initialize.apply(this, arguments);
this.on('msg:custom', _.bind(this.handleCustomMessage, this));
this.on('change:recording', this.updateRecord);
this.mediaRecorder = null;
this.chunks = [];
},
handleCustomMessage: function(content) {
if(content.msg == 'download') {
this.download();
}
},
updateRecord: function() {
var source = this.get('stream');
if(!source) {
new Error('No stream specified');
return;
}
var mimeType = this.type + '/' + this.get('format');
if (!MediaRecorder.isTypeSupported(mimeType)) {
new Error('The mimeType', mimeType, 'is not supported for record on this browser');
return;
}
if(this.get('recording')) {
this.chunks = [];
captureStream(source).then((stream) => {
this.mediaRecorder = new MediaRecorder(stream, {
audioBitsPerSecond: 128000,
videoBitsPerSecond: 2500000,
mimeType: mimeType
});
this.mediaRecorder.start();
this.mediaRecorder.ondataavailable = (event) => {
this.chunks.push(event.data);
};
});
} else {
this.mediaRecorder.onstop = (e) => {
if (this.get('_data_src') != '') {
URL.revokeObjectURL(this.get('_data_src'));
}
var blob = new Blob(this.chunks, { 'type' : mimeType });
this.set('_data_src', window.URL.createObjectURL(blob));
this.save_changes();
var reader = new FileReader();
reader.readAsArrayBuffer(blob);
reader.onloadend = () => {
var bytes = new Uint8Array(reader.result);
this.get(this.type).set('value', new DataView(bytes.buffer));
this.get(this.type).save_changes();
}
}
this.mediaRecorder.stop();
}
},
download: function() {
if (this.chunks.length == 0) {
new Error('Nothing to download');
return;
}
let blob = new Blob(this.chunks, {type: this.type + '/' + this.get('format')});
let filename = this.get('filename');
if (filename.indexOf('.') < 0) {
filename = this.get('filename') + '.' + this.get('format');
}
utils.downloadBlob(blob, filename);
},
close: function() {
if (this.get('_data_src') != '') {
URL.revokeObjectURL(this.get('_data_src'));
}
return RecorderModel.__super__.close.apply(this, arguments);
}
}, {
serializers: _.extend({
stream: { deserialize: widgets.unpack_models },
}, widgets.DOMWidgetModel.serializers)
});
var RecorderView = widgets.DOMWidgetView.extend({
render: function() {
RecorderView.__super__.render.apply(this, arguments);
this.el.classList.add('jupyter-widgets');
this.buttons = document.createElement('div');
this.buttons.classList.add('widget-inline-hbox');
this.buttons.classList.add('widget-play');
this.recordButton = document.createElement('button');
this.downloadButton = document.createElement('button');
this.result = document.createElement(this.tag);
this.result.controls = true;
this.recordButton.className = 'jupyter-button';
this.downloadButton.className = 'jupyter-button';
this.buttons.appendChild(this.recordButton);
this.buttons.appendChild(this.downloadButton);
this.el.appendChild(this.buttons);
this.el.appendChild(this.result);
var recordIcon = document.createElement('i');
recordIcon.className = this.recordIconClass;
this.recordButton.appendChild(recordIcon);
var downloadIcon = document.createElement('i');
downloadIcon.className = 'fa fa-download';
this.downloadButton.appendChild(downloadIcon);
this.recordButton.onclick = () => {
this.model.set('recording', !this.model.get('recording'));
};
this.downloadButton.onclick = this.model.download.bind(this.model);
this.listenTo(this.model, 'change:recording', () => {
if(this.model.get('recording')) {
recordIcon.style.color = 'darkred';
} else {
recordIcon.style.color = '';
}
});
this.listenTo(this.model, 'change:_data_src', () => {
this.result.src = this.model.get('_data_src');
if (this.result.play) {
this.result.play();
}
});
},
});
var ImageRecorderModel = RecorderModel.extend({
defaults: function() {
return _.extend(RecorderModel.prototype.defaults(), {
_model_name: 'ImageRecorderModel',
_view_name: 'ImageRecorderView',
image: null,
_height: '',
_width: '',
})
},
initialize: function() {
ImageRecorderModel.__super__.initialize.apply(this, arguments);
window.last_image_recorder = this;
this.type = 'image';
},
snapshot: async function() {
var mimeType = this.type + '/' + this.get('format');
var mediaStream = await captureStream(this.get('stream'));
// turn the mediastream into a video element
let video = document.createElement('video');
video.srcObject = mediaStream;
video.play()
await utils.onCanPlay(video);
await utils.onLoadedMetaData(video);
// and the video element can be drawn onto a canvas
let canvas = document.createElement('canvas')
let context = canvas.getContext('2d');
let height = video.videoHeight;
let width = video.videoWidth;
canvas.height = height;
canvas.width = width;
context.drawImage(video, 0, 0, canvas.width, canvas.height);
// from the canvas we can get the underlying encoded data
// TODO: check support for toBlob, or find a polyfill
var blob = await utils.canvasToBlob(canvas, mimeType);
this.set('_data_src', window.URL.createObjectURL(blob));
this._last_blob = blob;
var bytes = await utils.blobToBytes(blob);
this.get(this.type).set('value', new DataView(bytes.buffer));
this.get(this.type).save_changes();
this.set('_height', height.toString() + 'px');
this.set('_width', width.toString() + 'px');
this.set('recording', false);
this.save_changes();
},
updateRecord: function() {
var source = this.get('stream');
if(!source) {
new Error('No stream specified');
return;
}
if (this.get('_data_src') != '') {
URL.revokeObjectURL(this.get('_data_src'));
}
if(this.get('recording'))
this.snapshot()
},
download: function() {
let filename = this.get('filename');
let format = this.get('format');
if (filename.indexOf('.') < 0) {
filename = this.get('filename') + '.' + format;
}
utils.downloadBlob(this._last_blob, filename);
},
}, {
serializers: _.extend({
image: { deserialize: widgets.unpack_models },
}, RecorderModel.serializers)
});
var ImageRecorderView = RecorderView.extend({
initialize: function() {
ImageRecorderView.__super__.initialize.apply(this, arguments);
this.tag = 'img';
this.recordIconClass = 'fa fa-camera';
},
});
var VideoRecorderModel = RecorderModel.extend({
defaults: function() {
return _.extend(RecorderModel.prototype.defaults(), {
_model_name: 'VideoRecorderModel',
_view_name: 'VideoRecorderView',
video: null,
})
},
initialize: function() {
VideoRecorderModel.__super__.initialize.apply(this, arguments);
window.last_video_recorder = this;
this.type = 'video';
},
}, {
serializers: _.extend({
video: { deserialize: widgets.unpack_models },
}, RecorderModel.serializers)
});
var VideoRecorderView = RecorderView.extend({
initialize: function() {
VideoRecorderView.__super__.initialize.apply(this, arguments);
this.tag = 'video';
this.recordIconClass = 'fa fa-circle';
},
});
var AudioRecorderModel = RecorderModel.extend({
defaults: function() {
return _.extend(RecorderModel.prototype.defaults(), {
_model_name: 'AudioRecorderModel',
_view_name: 'AudioRecorderView',
audio: null,
})
},
initialize: function() {
AudioRecorderModel.__super__.initialize.apply(this, arguments);
window.last_audio_recorder = this;
this.type = 'audio';
},
}, {
serializers: _.extend({
audio: { deserialize: widgets.unpack_models },
}, RecorderModel.serializers)
});
var AudioRecorderView = RecorderView.extend({
initialize: function() {
AudioRecorderView.__super__.initialize.apply(this, arguments);
this.tag = 'audio';
this.recordIconClass = 'fa fa-circle';
},
});
var WebRTCRoomModel = widgets.DOMWidgetModel.extend({
defaults: function() {
return _.extend(widgets.DOMWidgetModel.prototype.defaults(), {
_model_name: 'WebRTCRoomModel',
//_view_name: 'WebRTCRoomView',
_model_module: 'jupyter-webrtc',
//_view_module: 'jupyter-webrtc',
_model_module_version: semver_range,
_view_module_version: semver_range,
room: 'room',
stream: null,
room_id: widgets.uuid(),
nickname: 'anonymous',
peers: [],
streams: []
})
},
log: function() {
var args = [this.get('nickname') + ' ' +this.get('room_id') +': ']
args = args.concat(Array.prototype.slice.call(arguments))
console.log.apply(null, args);
},
initialize: function() {
WebRTCRoomModel.__super__.initialize.apply(this, arguments);
this.set('room_id', widgets.uuid())
this.room_id = this.get('room_id')
this.room = this.get('room')
this.peers = {} // room_id (string) to WebRTCPeerModel
window['last_webrtc_room_' + this.room_id] = this
var stream = this.get('stream')
if(stream) {
this.set('streams', [stream])
}
this.save_changes()
this.on('msg:custom', _.bind(this.custom_msg, this));
},
custom_msg: function(content) {
if(content.msg == 'close') {
this.close()
}
},
close: function() {
this.get('peers').forEach((peer) => peer.close())
},
create_peer: function(from_id) {
return this.widget_manager.new_widget({
model_name: 'WebRTCPeerModel',
model_module: 'jupyter-webrtc',
model_module_version: semver_range,
view_name: 'WebRTCPeerView',
view_module: 'jupyter-webrtc',
view_module_version: semver_range,
widget_class: 'webrtc.WebRTCPeerModel', // ipywidgets6
}, {
stream_local: this.get('stream'),
id_local: this.get('room_id'),
id_remote: from_id
}).then(_.bind(function(peer) {
peer.peer_msg_send = _.bind(function(msg) {
msg.room_id = this.get('room_id')
msg.to = from_id
this.log('send to peer', msg)
//console.log('sending to room', msg, from_id)
peer.save_changes()
this.room_msg_send(msg)
}, this)
return peer
}, this))
},
listen_to_remote_stream: function(peer) {
peer.on('change:stream_remote', _.once(_.bind(function(){
this.log('add remote stream')
var streams = this.get('streams').slice()
var stream = peer.get('stream_remote')
streams.push(stream)
this.set('streams', streams)
this.save_changes()
}, this)))
peer.on('change:connected', _.bind(function() {
var connected = peer.get('connected')
this.log('changed connected status for ', peer.get('id_remote'), 'to', connected)
if(!connected) {
var streams = this.get('streams').slice()
var stream = peer.get('stream_remote')
streams = _.without(streams, stream)
this.set('streams', streams)
var peers = this.get('peers').slice()
peers = _.without(peers, peer)
this.set('peers', peers)
delete this.peers[peer.get('id_remote')]
this.save_changes()
}
}, this))
},
on_room_msg: function(msg) {
var from_id = msg.room_id;
if(msg.room_id == this.room_id)
return; // skip my own msg'es
if(msg.type == 'join') {
this.log('join from', msg.room_id)
this.peers[from_id] = this.create_peer(from_id).then(_.bind(function(peer) {
this.listen_to_remote_stream(peer)
peer.join().then(_.bind(function() {
var peers = this.get('peers').slice()
peers.push(peer)
this.set('peers', peers)
this.save_changes()
}, this))
return peer
}, this))
this.log(': added peer', from_id)
return peer;
} else if(msg.room_id) {
if(msg.to != this.room_id) {
return
}
if(!this.peers[msg.room_id]) {
this.peers[from_id] = this.create_peer(from_id).then(_.bind(function(peer) {
this.listen_to_remote_stream(peer)
var peers = this.get('peers').slice()
peers.push(peer)
this.set('peers', peers)
this.save_changes()
return peer
}, this))
this.log('added peer', from_id)
}
var peer = this.peers[msg.room_id]
if(peer) {
//console.log(this.room_id, ': peer', msg.room_id, peer, this, this.cid)
peer.then(_.bind(function(peer) {
this.log('sending from', msg.room_id, ' to', msg.to, msg)
peer.on_peer_msg(msg)
}, this))
} else {
console.error('sending to unknown peer', msg.room_id)
}
} else {
console.error('expected a to room_id to be present')
}
}
}, {
serializers: _.extend({
stream: { deserialize: widgets.unpack_models },
peers: { deserialize: widgets.unpack_models },
}, widgets.DOMWidgetModel.serializers)
});
var global_rooms = {}
var WebRTCRoomLocalModel = WebRTCRoomModel.extend({
defaults: function() {
return _.extend(WebRTCRoomModel.prototype.defaults(), {
_model_name: 'WebRTCRoomLocalModel',
})
},
initialize: function() {
WebRTCRoomLocalModel.__super__.initialize.apply(this, arguments);
this.join()
},
join: function() {
var room = this.get('room');
console.log('joining room', room)
var callbacks = global_rooms[room] || []
callbacks.push(_.bind(this.on_room_msg, this))
global_rooms[room] = callbacks
this.room_msg_send({type: 'join', room_id: this.get('room_id')})
},
room_msg_send: function(msg) {
var room = this.get('room');
console.log('send to room', room, msg, global_rooms[room])
_.each(global_rooms[room], function(callback) {
callback(msg)
})
},
});
var WebRTCRoomMqttModel = WebRTCRoomModel.extend({
defaults: function() {
return _.extend(WebRTCRoomModel.prototype.defaults(), {
_model_name: 'WebRTCRoomMqttModel',
server: 'wss://iot.eclipse.org:443/ws'
})
},
initialize: function() {
WebRTCRoomMqttModel.__super__.initialize.apply(this, arguments);
console.log('connecting to', this.get('server'))
this.mqtt_client = mqtt.connect(this.get('server'))
var client = this.mqtt_client
this.topic_join = 'jupyter-webrtc/' + this.get('room') +'/join'
//this.topic_present = 'jupyter-webrtc/' +this.room +'/present'
this.mqtt_client.on('connect', _.bind(function () {
client.subscribe(this.topic_join)
//client.subscribe(this.topic_present)
//client.publish('jupyter-webrtc/room-a/present', 'you|me', {retain:true})
//client.publish('jupyter-webrtc/room-a/join', 'Hello mqtt')
}, this))
client.on('message', _.bind(function (topic, message) {
var msg = JSON.parse(message)
console.log('msg received', message, msg)
if(topic == this.topic_join) {
this.on_room_msg(msg)
}
}, this))
this.join()
},
join: function() {
this.room_msg_send({type: 'join', room_id: this.get('room_id')})
},
room_msg_send: function(msg) {
var text = JSON.stringify(msg)
console.log('send to mqtt channel', msg)
this.mqtt_client.publish(this.topic_join, text)
}
});
var WebRTCPeerModel = widgets.DOMWidgetModel.extend({
defaults: function() {
return _.extend(widgets.DOMWidgetModel.prototype.defaults(), {
_model_name: 'WebRTCPeerModel',
_view_name: 'WebRTCPeerView',
_model_module: 'jupyter-webrtc',
_view_module: 'jupyter-webrtc',
_model_module_version: semver_range,
_view_module_version: semver_range
})
},
log: function() {
var args = [this.get('room_id') +': ']
args = args.concat(Array.prototype.slice.call(arguments))
console.log.apply(null, args);
},
on_peer_msg: function(msg) {
var info = msg;
var that = this;
this.log('peer msg', info)
if(info.sdp) {
// the other party send us the sdp
this.log(name, 'got sdp')
var sdp_remote = new RTCSessionDescription(info.sdp)
var remote_description_set = this.pc.setRemoteDescription(sdp_remote)
if(!this.initiator) {
console.log(this.get('id_local'), 'did not initiate, reply with answer')
// if we didn't initiate, we should respond with an answer
// now we create an answer, and send a sdp back
Promise.all([remote_description_set, this.tracks_added])
.then(() => this.pc.createAnswer())
.then((sdp) => {
console.log('sending sdp', this.room_id)
that.send_sdp(sdp)
that.pc.setLocalDescription(sdp)
})
}
} else if (info.candidate) {
var c = new RTCIceCandidate(info.candidate);
this.pc.addIceCandidate(c)
}
},
initialize: function() {
WebRTCPeerModel.__super__.initialize.apply(this, arguments);
var that = this;
var room_id = this.room_id = this.get('id_local')
this.initiator = false
var pc_config = {"iceServers": [{"urls": ["stun:stun.l.google.com:19302", 'stun:stun1.l.google.com:19302', 'stun:stun2.l.google.com:19302']}]};
//var pc_config = null;