forked from pipe/bookclub
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.html
1199 lines (1106 loc) · 51.3 KB
/
index.html
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
<!doctype html>
<html lang="en">
<head>
<title>Textual Relations</title>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" integrity="sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb" crossorigin="anonymous">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<style>
body {
background-image: url("fhp2.jpeg");
background-color: #cccccc;
background-position: center;
background-size: cover;
background-repeat: no-repeat;
}
.footer {
position: fixed;
left: 0;
bottom: 0;
width: 100%;
color: white;
text-align: center;
}
html, body { height: 100%; width: 100%; margin: 0; }
.all { height: 100%; width: 100%;}
</style>
</head>
<body>
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js" crossorigin="anonymous"></script>
<a href="index.html"><h1 id="title" class="text-center">Bookclub session</h1></a>
<div class="card container-fluid all">
<div id="remotes" class="card-header" >
<canvas id="brady" width="1200" height="150"></canvas>
<div id="vids" class="row no-gutters" >
<div class="col" id="-0.9"></div>
<div class="col" id="-0.8"></div>
<div class="col" id="-0.6"></div>
<div class="col" id="-0.4"></div>
<div class="col" id="-0.2"></div>
<div class="col" id="0"></div>
<div class="col" id="0.2"></div>
<div class="col" id="0.4"></div>
<div class="col" id="0.6"></div>
<div class="col" id="0.8"></div>
<div class="col" id="0.9"></div>
</div>
<video id="them" style="width:100%;height:fit-content;" autoplay playsinline > </video>
<audio id="audio" style="display:none;" autoplay playsinline > </audio>
</div>
<video id="bookVideo" muted autoplay="true" class="card-img-top" poster="fhp2.jpeg">Book goes here</video>
<div class="card-body">
<div id="chosenAction" class="row justify-content-around">
<button id="mute" type="button" class="col-4 btn btn-primary btn-lg"><i id="muteIcon" class="fa fa-microphone fa-2x" aria-hidden="true"></i></button>
<button id="stopCall" type="button" class="col-4 btn btn-primary btn-lg"><i id="stopIcon" class="fa fa-stop fa-2x" aria-hidden="true"></i></button>
<button id="recordCall" type="button" class="btn btn-danger" data-toggle="button" aria-pressed="false" autocomplete="off">
Record Call
</button>
</div>
</div>
<div class="card-footer">
<h2><span class="badge badge-primary" id="role"></span><span class="badge badge-primary" id="status"></span></h2>
<!--div style="width: 80px; height: 80px;" id="me">me</div-->
<br/>
<span>See our <a href="https://github.com/pipe/bookclub">Github</a> for source code</span>
<span>See also <a href="https://pi.pe/privacy_policy/index.html">Privacy</a>
and <a href="https://pi.pe/impressum/index.html">Impressum</a></span>
</div>
</div>
<div id="share" class="modal" tabindex="-1" role="dialog">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Send this url to the members. </h5>
</div>
<div class="modal-body" id="shareQR">
<p>Share this URL to start a session</p>
<p>You can use the share icon at the top of the screen</p>
<p>Then email/sms it to each of the book club members</p>
<p>Then press 'done'</p>
</div>
<div class="modal-footer">
<button id="shareDone" type="button" class="btn btn-secondary" data-dismiss="modal" >Done</button>
</div>
</div>
</div>
</div>
<div id="shareScreen" class="modal" tabindex="-1" role="dialog">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Share the book. </h5>
</div>
<div class="modal-body" id="sharePrompt">
<p>If you have an electronic copy of the book on this computer</p>
<p>you can use the 'Share Book' button to select the window containing the book.</p>
<p>This will share your view of the book with the other members.</p>
<p>If you don't have the book, click 'No e-Book'</p>
</div>
<div class="modal-footer">
<button id="shareMyApp" type="button" class="btn btn-secondary" data-dismiss="modal" >Share Book</button>
<button id="noShareApp" type="button" class="btn btn-secondary" data-dismiss="modal" >No e-Book</button>
</div>
</div>
</div>
</div>
<div id="accept" class="modal" tabindex="-1" role="dialog">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Accept a book club session</h5>
</div>
<div class="modal-body">
<p>Click 'accept' to start the call.</p>
<p>You also need to permit access to your microphone</p>
</div>
<div class="modal-footer">
<button id="callAccept" type="button" class="btn btn-secondary" data-dismiss="modal" >Accept</button>
</div>
</div>
</div>
</div>
<div id="nowebrtc" class="modal" tabindex="-1" role="dialog">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Sorry</h5>
</div>
<div class="modal-body">
<p>Unfortunately the browser you are using does not support WebRTC.</p>
<p>Please retry using Safari, Chrome, FireFox, Edge - or pretty much any modern browser</p>
</div>
<div class="modal-footer">
<button id="sadder" type="button" class="btn btn-secondary" data-dismiss="modal" >Accept</button>
</div>
</div>
</div>
</div>
<div id="nomediaapi" class="modal" tabindex="-1" role="dialog">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Sorry</h5>
</div>
<div class="modal-body">
<p>Unfortunately the browser you are using does not support the full webAudio API.</p>
<p>Please try hosting the call with Chrome.</p>
<p>The members can use any modern browser</p>
</div>
<div class="modal-footer">
<button id="sad" type="button" class="btn btn-secondary" data-dismiss="modal" >Accept</button>
</div>
</div>
</div>
</div>
<script type="module">
var socket; // used to set up connection with our peers.
var mid;
var cid;
var myac;
var initiator;
var localStream;
var localdcomp;
var localpanned;
var mute = false;
var peerConnectionOfferAnswerCriteria = {offerToReceiveAudio: true, offerToReceiveVideo: true };
var AudioContext = window.AudioContext || window.webkitAudioContext;
var sessions = {};
var isChrome = ("chrome" in window);
var bookStream = null;
var recorder;
var chunks = [];
var saved = false;
var startRecTime = 0;
var properties = {};
//var myImage = null;
// really feature detection doesn't do it chrome's webaudio bugs are undetectable from the outside.
var pans = [ 0.9, -0.9, 0.2, -0.2, 0.6 , -0.6, 0.8, -0.8, 0.4, -0.4, 0.0];
var canv2d = document.getElementById("brady").getContext( '2d' );
var mcu;
function Session(id,lpan) {
this.checker = null;
this.lastLoss = 0;
this.lastRecv =0;
this.fid = id;
this.panned = null;
this.dcomp = null;
this.peerout = null;
this.peerin = null;
this.statusChannel = null;
this.audio = null;
this.audioLevel =0.0;
//this.img = null;
//this.imageData = null;
if (!lpan) {
this.pan = pans.pop();
console.log("created peer connection for " + id);
this.lcandyStash = [];
} else {
this.pc = null;
this.pan = lpan;
console.log("dummy entry for " + id );
}
console.log("pan is " + this.pan);
this.rdiv = document.createElement("div");
var remoteslot = document.getElementById(""+this.pan);
var canvas = document.getElementById("brady");
var height = canvas.clientHeight;
var width = Math.min(canvas.clientWidth /10,height*0.75);
if (initiator) {
// add an video tag per recipient because chrome needs some suckage on the pipe...
this.audio = document.createElement("video");
//this.audio.setAttribute("style","display: none;");
this.audio.muted = true;
this.audio.setAttribute("autoplay","true");
this.audio.setAttribute("width",width);
this.audio.setAttribute("height",height);
console.log("Set video width x height to "+width+" x "+height);
this.rdiv.appendChild(this.audio);
this.rdiv.setAttribute("style","border-width:medium; border-style:hidden;")
}
//Robohash.render(this.fid,this.rdiv);
remoteslot.appendChild(this.rdiv);
};
Session.prototype.offerDeal = function (data) {
this.setupRTC();
this.pc.setRemoteDescription(data).then(_ =>
this.pc.createAnswer(peerConnectionOfferAnswerCriteria).then(ans => {
ans.sdp = tweakSDP(ans.sdp);
this.pc.setLocalDescription(ans).then(_ =>
sendMessage(this.fid, mid, "answer", ans.sdp)
)
})
).catch((e) => console.log("set Remote offer error", e));
};
Session.prototype.answerDeal = function(data){
this.pc.setRemoteDescription(data)
.then( _ => {
//$("#action").text("hangup");
})
.catch(e => console.log("set Remote answer error", e) );
};
Session.prototype.candidateDeal = function(data){
var jc = {
sdpMLineIndex: 0,
candidate: data.sdp
};
console.log("adding candidate ", jc);
var nc = new RTCIceCandidate(jc);
this.pc.addIceCandidate(nc)
.then( _ => console.log("added remote candidate"))
.catch((e) => console.log("couldn't add candidate ", e));
};
Session.prototype.stopSession = function() {
console.log("removing " + this.fid);
delete sessions[this.fid];
var that = this;
if (initiator) {
Object.entries(sessions).forEach(sessionkva => {
var session = sessionkva[1];
if (that.dcomp && session.panned) {
session.panned.disconnect(that.dcomp);
}
if (that.panned && session.dcomp) {
that.panned.disconnect(session.dcomp);
}
if (session.statusChannel && (session.statusChannel.readyState == 'open')) {
session.statusChannel.send(JSON.stringify({act: 'del', fid: that.fid})); // I hear them
}
});
}
if (localpanned){
localpanned.disconnect(this.dcomp);
}
if (this.panned != null) {
this.panned.disconnect(localdcomp);
this.panned = null;
pans.push(this.pan);
}
if (this.dcomp != null) {
this.dcomp.disconnect();
this.dcomp = null;
}
if (this.peerout != null) {
this.peerout.disconnect();
this.peerout = null;
}
if (this.peerin != null){
this.peerin.disconnect();
this.peerin = null;
}
if (this.checker != null) {
window.clearTimeout(this.checker);
this.checker = null;
}
if(this.pc != null){
var mpc = this.pc;
window.setTimeout(function () {
if (initiator) {
mpc.close();
} else {
stopCall(); // that is if we killed the (only) pc then byebye
}
},5000);
this.pc = null;
}
if (this.rdiv) {
this.audio.srcObject = null;
this.audio.pause();
this.rdiv.removeChild(this.audio);
var remotes = this.rdiv.parentNode;
remotes.removeChild(this.rdiv);
}
var cw = canv2d.canvas.width;
var ch = canv2d.canvas.height;
canv2d.clearRect(0,0, cw, ch);
$("#status").text("Call connected to "+ Object.keys(sessions).length + " member(s).");
};
Session.prototype.setupRTC = function(){
console.log("setting up webRTC for "+this.fid);
this.pc = new RTCPeerConnection(properties.configuration, null);
this.pc.onicecandidate = (e) => {
console.log("local ice candidate", e.candidate);
if (e.candidate != null) {
if (candyProt(e.candidate.candidate).toUpperCase()!="TCP") {
if (this.pc.signalingState == 'stable') {
sendMessage(this.fid, mid, "candidate", e.candidate.candidate);
} else {
console.log("stashing ice candidate");
this.lcandyStash.push(e.candidate);
}
} else {
console.log("skip TCP candidates");
}
}
};
this.pc.oniceconnectionstatechange = (e) => {
console.log("ice state is changed", this.pc.iceConnectionState);
/*
"new" The ICE agent is gathering addresses or is waiting to be given remote candidates through calls to RTCPeerConnection.addIceCandidate() (or both).
"checking" The ICE agent has been given one or more remote candidates and is checking pairs of local and remote candidates against one another to try to find a compatible match, but has not yet found a pair which will allow the peer connection to be made. It's possible that gathering of candidates is also still underway.
"connected" A usable pairing of local and remote candidates has been found for all components of the connection, and the connection has been established. It's possible that gathering is still underway, and it's also possible that the ICE agent is still checking candidates against one another looking for a better connection to use.
"completed" The ICE agent has finished gathering candidates, has checked all pairs against one another, and has found a connection for all components.
"failed" The ICE candidate has checked all candidates pairs against one another and has failed to find compatible matches for all components of the connection. It is, however, possible that the ICE agent did find compatible connections for some components.
"disconnected" Checks to ensure that components are still connected failed for at least one component of the RTCPeerConnection. This is a less stringent test than "failed" and may trigger intermittently and resolve just as spontaneously on less reliable networks, or during temporary disconnections. When the problem resolves, the connection may return to the "connected" state.
"closed"
*/
if (this.pc.iceConnectionState === "failed"){
this.stopSession();
}
if (this.pc.iceConnectionState === "disconnected"){
this.stopSession();
}
};
// specification of WEBRTC is in flux - so we test to see if ontrack callback exists
if ('ontrack' in this.pc) {
// if so we use it
this.pc.ontrack = (event) => {
var stream = event.streams[0];
console.log("got remote track ", event.track.kind);
this.addStream(stream,event.track.kind);
};
} else {
// if not we use add stream instead
this.pc.onaddstream = (event) => {
var stream = event.stream;
console.log("got remote stream ", stream.kind);
this.addStream(stream);
}
}
// use this to determine the state of the 'hangup' button and send any candidates we found quickly
this.pc.onsignalingstatechange = (evt) => {
if (this.pc != null) {
console.log("signalling state is ", this.pc.signalingState);
if (this.pc.signalingState == 'stable') {
var can;
while (can = this.lcandyStash.pop()) {
console.log("popping candidate off stash");
sendMessage(this.fid, mid, "candidate", can.candidate);
}
var act = $("#stopCall");
act.click(_ => stopCall());
window.onbeforeunload = function () {
return this.pc!=null ? "If you leave this page you will end the connection." : null;
}
}
}
};
this.pc.ondatachannel = (evt) => {
console.log("got new datachannel from " +this.fid);
this.statusChannel = evt.channel;
console.log("got new datachannel from " +this.statusChannel.label);
this.statusChannel.onopen = (ev) => {
console.log("got open datachannel from " +this.fid);
that.tellAll();
// don't tell them about us.
// that.statusChannel.send(JSON.stringify({act: 'add', fid: cid, pan: "0"}));
};
var that = this;
this.statusChannel.onmessage = (ev) => {
console.log("got data on datachannel from " +that.fid);
/*var mess = JSON.parse(ev.data);
if (mess.id == that.fid){
console.log("setting image data");
that.setImage(mess.img);
} */
}
};
};
Session.prototype.tellAll = function() {
var that = this;
Object.entries(sessions).forEach(sessionkva => {
var id = sessionkva[0];
var session = sessionkva[1];
// tell them about everyone (including themselves)
that.statusChannel.send(JSON.stringify({act: 'add', fid: session.fid, pan: session.pan}));
if (id != this.fid) {
// tell everyone (except them) about them
if ((session.statusChannel) && (session.statusChannel.readyState=='open')) {
session.statusChannel.send(JSON.stringify({act: 'add', fid: that.fid, pan: that.pan})); // I hear them
}
} else {
console.log("skip me " + id);
}
});
};
Session.prototype.addStream = function(stream,kind) {
if (!kind) {
kind = "audio/video";
}
$("#status").text("Call connected to " + Object.keys(sessions).length + " member(s).");
console.log("got new stream" + stream + " kind =" + kind);
if (kind.indexOf("audio") != -1) {
if (initiator) {
// inbound....
this.peerin = myac.createMediaStreamSource(stream);
this.panned = myac.createStereoPanner();
this.panned.pan.value = this.pan;
console.log("panned to " + this.pan);
this.peerin.connect(this.panned);
// now connect panned to :
// local destination...
// plug the panned output into our dcomp so we get the stereo effect as host.
if (localdcomp != null) {
this.panned.connect(localdcomp);
} else {
console.log("nowhere to plug " + this.fid);
}
var that = this;
// outbound
// for now just add the localpanned stream
this.dcomp = myac.createDynamicsCompressor();
if (localpanned) {
localpanned.connect(this.dcomp);
console.log("connect local stream to dcomp");
}
Object.entries(sessions).forEach(sessionkva => {
var id = sessionkva[0];
if (id != this.fid) {
var session = sessionkva[1];
if (that.panned && session.dcomp) {
that.panned.connect(session.dcomp); // they hear me
}
if (that.dcomp && session.panned) {
session.panned.connect(that.dcomp); // I hear them
}
} else {
console.log("skip me " + id);
}
});
this.peerout = myac.createMediaStreamDestination();
this.dcomp.connect(this.peerout);
var pc = this.pc;
var pstream = this.peerout.stream;
if (pc.addTrack) {
pstream.getTracks().forEach(track => {
pc.addTrack(track, pstream);
console.log("added panned outbound track ", track.id, track.kind, track.label);
});
if (mcu) {
mcu.getTracks().forEach(track => {
pc.addTrack(track, mcu);
console.log("added mcu outbound track ", track.id, track.kind, track.label);
});
}
if (bookStream){
bookStream.getTracks().forEach(track => {
pc.addTrack(track, bookStream);
console.log("added book outbound track ", track.id, track.kind, track.label);
});
}
} else {
pc.addStream(pstream);
console.log("added panned outbound stream");
if (mcu) {
pc.addStream(mcu);
console.log("added mcu outbound stream");
}
}
}
var that = this;
this.checker = window.setInterval(function () {
that.checkLoss();
}, 1000);
// audio together here.
// depends on role
console.log('Audio sample Rate is ' + myac.sampleRate);
$("#chosenAction").show();
$("#statsZone").show();
}
if (initiator) {
this.addVstream(stream, kind);
} else {
if (kind.indexOf("audio") != -1) {
console.log("added remote "+kind+" stream to audio");
var au = document.getElementById("audio");
au.srcObject = stream;
au.play();
} else {
var them = document.getElementById("them");
if (them.srcObject == null) {
console.log("added remote " + kind + " stream to videotag");
them.srcObject = stream;
$("#them").show();
} else {
var book = document.getElementById("bookVideo");
console.log("added remote " + kind + " stream to book");
book.srcObject = stream;
$("#bookVideo").show();
}
}
}
};
Session.prototype.addVstream = function(stream) {
// note that these only exist because chrome is weird and needs an audio tag
// which can (and should) be muted - so this makes no sound. - also video now
if (isChrome) {
this.audio.srcObject = stream;
this.audio.play();
console.log("added stream to local media object");
}
//var settings = getSize(stream);
var that = this;
var drawToCanvas = function () {
// draw the current frame of localVideo onto the canvas,
// starting at 0, 0 (top-left corner) and covering its full
// width and heigth
var cw = canv2d.canvas.clientWidth;
var ch = canv2d.canvas.clientHeight;
var vh = that.audio.videoHeight;
var vw = that.audio.videoWidth;
var rat = vw/vh;
var rw = Math.floor(ch *rat);
var abspan = (1.0 +that.pan) / 2 ;
var x = Math.floor((cw * abspan) - vw/2);
// void ctx.drawImage(image, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight);
canv2d.drawImage(that.audio, 0, 0,vw,vh, x,0,rw,ch);
//console.log("drawing video for +"+that.fid+ " at " + x);
//repeat this every time a new frame becomes available using
//the browser's build-in requestAnimationFrame method
requestAnimationFrame(drawToCanvas);
}
//console.log("drawing video at " + x);
drawToCanvas();
};
Session.prototype.checkLoss = function(){
var that = this;
if (this.pc) {
this.pc.getReceivers()[0].getStats().then(
function (rs) {
var style = "";
rs.forEach(function (d) {
if (d.type === "inbound-rtp") {
var recvd = d.packetsReceived;
var lost = d.packetsLost;
var colour = "grey";
if (lost > that.lastLoss) {
var diffl = lost - that.lastLoss;
var diffp = recvd - that.lastRecv;
var pct = Math.ceil(100.0 * diffl / diffp);
if (pct > 0) {
colour = rgb(128 + pct, 128, 128);
}
}
that.lastLoss = lost;
that.lastRecv = recvd;
style += "background-color:" + colour + "; ";
}
if (d.type === "track") {
that.audioLevel = d.audioLevel;
var bwidth = Math.floor((that.audioLevel * 10.0));
if (bwidth >= 2){
style += " border-style:outset; ";
} else {
style += " border-style:hidden; ";
}
//console.log("bwidth ="+bwidth);
}
/*if ((d.type ==="candidate-pair")&&(d.nominated)){
$("#delay").text(""+d.currentRoundTripTime);
}
if (d.type === "remote-candidate"){
$("#remote").text(d.candidateType);
}
if (d.type === "local-candidate"){
$("#local").text(d.candidateType);
}*/
}
);
//that.rdiv.setAttribute("style", style);
//console.log("style ="+style);
});
}
}
function rgb
(r, g,
b){
r = Math.floor(r);
g = Math.floor(g);
b = Math.floor(b);
return ["rgb(",r,",",g,",",b,")"].join("");
}
// message stuff - used to create direct connection to peer over WEBRTC
function tweakSDP(sdp){
var lines = sdp.split("\r\n");
for (var i=0;i<lines.length;i++){
var line = lines[i];
if (line.startsWith("a=fmtp:111")){
lines[i]= "a=fmtp:111 minptime=20; stereo=1; ptime=60; useinbandfec=1; maxaveragebitrate=32000";
}
}
return (lines.join("\r\n"));
}
function messageDeal(event){
//console.log("message is ", event.data);
var data = JSON.parse(event.data);
console.log("message data is ", data);
if (data.to != mid){
alert("message mixup");
}
var session = sessions[data.from];
switch (data.type) {
case "offer":
if ((session == null) && (initiator)) {
session = new Session(data.from);
sessions[data.from] = session;
}
if (initiator){
session.offerDeal(data);
} else {
console.log("huh? Guests send offers");
}
break;
case "answer":
if ((session) && (!initiator)){
session.answerDeal(data);
}
break;
case "candidate":
if (session) {
session.candidateDeal(data);
} else {
console.log("should stash candidate for "+data.from);
}
break;
}
}
function candyProt(candy){
var ret = "none";
var bits = candy.split(" ");
if (bits.length >= 3){
ret = bits[2];
}
return ret;
}
function sendMessage(to,from,type,data){
var messageJ = {
to:to,
from:from,
type:type,
sdp:data
};
var message = JSON.stringify(messageJ);
console.log("sending ", messageJ);
socket.send(message);
}
// button actions
// this is singular -
function startCall(fid){
var that = sessions[cid];
var pc = that.pc;
that.statusChannel = pc.createDataChannel("status-"+Date.now());
that.statusChannel.onopen = () => {
console.log("guest's status channel opened - sending ping");
that.statusChannel.send(JSON.stringify({act:"ping",date:Date.now()}));
};
that.statusChannel.onclose = (e) => {
console.log("guest's status channel closed "+e);
};
that.statusChannel.onerror = (e) => {
console.log("guest's status channel errored "+e);
};
console.log("created status datachannel");
that.statusChannel.onmessage = (evt) => {
statusDeal(evt);
};
pc.createOffer(peerConnectionOfferAnswerCriteria)
.then(desc => {
console.log("offer created",);
$("#status").text("Making call to host");
desc.sdp = tweakSDP(desc.sdp);
pc.setLocalDescription(desc).then( d => sendMessage(fid, mid, desc.type, desc.sdp));
})
.catch(e => console.log("offer not created due to ", e) );
}
function stopCall(){
$("#status").text("Call ended.");
document.location = "thanks.html";
}
function statusDeal(evt){
console.log("got message "+evt.data);
var mo = JSON.parse(evt.data);
if (mo.act){
if (mo.act =="add"){
if (!sessions[mo.fid]) {
var sess = new Session(mo.fid, mo.pan);
console.log("adding user " + mo.fid);
sessions[mo.fid] = sess;
}
}
if (mo.act =="del"){
console.log("delete user "+mo.fid);
var sess = sessions[mo.fid]
if (sess){
sess.stopSession();
}
}
} else {
console.log("missing action");
}
$("#status").text("Call connected to "+ Object.keys(sessions).length + " member(s).");
}
// mute management
function setMute(m){
var mi = $("#muteIcon");
mute = m;
if (m){
mi.removeClass("fa-microphone");
mi.addClass("fa-microphone-slash");
} else {
mi.removeClass("fa-microphone-slash");
mi.addClass("fa-microphone");
}
var audioTracks = localStream.getAudioTracks();
if (audioTracks[0]) {
audioTracks[0].enabled = !m;
}
}
/*
function repaintDuration(){
var diff = Date.now() - startRecTime;
console.log ("data on at "+diff);
var mins = Math.floor(diff / 60000);
var secs = Math.floor((diff % 60000) / 1000);
$("#duration").text(""+mins+":"+secs);
}
*/
function captureCanvas(){
var can = document.getElementById("brady");
mcu = can.captureStream(5);
console.log("captured canvas stream");
}
// plumb the local audio together.
function setupAudio() {
myac = new AudioContext();
//setNoSleep();
var gumConstraints = {audio: true, video: {
width: { ideal: 240 },
height: { ideal: 320 },
frameRate: {ideal: 5},
//aspectRatio: { ideal: 1.7777777778 }
},};
// connect to our speakers
if (initiator){
// this works beautifully on firefox but fails in chrome
// unless we make a _lot_ of <audio> tags
localdcomp = myac.createDynamicsCompressor();
var dests = myac.createMediaStreamDestination();
localdcomp.connect(dests);
// set up play....
//console.log("local dcomp connected ");
document.getElementById("them").srcObject = dests.stream;
document.getElementById("them").play();
}
var promise = new Promise(function (resolve, reject) {
navigator.mediaDevices.getUserMedia(gumConstraints)
.then((stream) => {
localStream = stream;
// do magic pan stuff here....
if (initiator) {
var localsrc = myac.createMediaStreamSource(stream);
localpanned = myac.createStereoPanner();
localpanned.pan.value = 0.0;
console.log("local stream panned to 0.0 ");
localsrc.connect(localpanned);
// do something with video here - plunk it on our robot....
sessions[mid].addVstream(stream);
$("#brady").show();
$("#recordCall").show();
$("#them").muted = true;
captureCanvas();
} else {
var pc = sessions[cid].pc; // implicit detection of us being a guest
if (pc.addTrack) {
stream.getTracks().forEach(track => {
pc.addTrack(track, stream);
console.log("added local track ", track.id, track.kind);
});
} else {
pc.addStream(stream);
console.log("added local stream");
}
var bookshare = pc.addTransceiver("video", {direction:"recvonly"});
}
resolve(false);
})
.catch((e) => {
console.log('getUserMedia() error:' + e);
reject(e);
});
});
return promise;
}
function setupRTC() {
var session = new Session(cid);
session.setupRTC();
sessions[cid] = session;
}
var playing = false;
function toggleplay(){
var audio = document.getElementById('them');
if (!playing) {
audio.play();
} else {
audio.pause();
}
playing = ! playing;
}
function shared() {
setupRTC();
setupAudio().then(_ => {
console.log("ready for offer");
$("#status").text("Waiting for guests.");
});
}
function accepted() {
setupRTC();
setupAudio().then(_ => {
console.log("ready for offer");
$("#status").text("Mic available");
startCall(cid)
});
}
function repaintDuration(){
var diff = Date.now() - startRecTime;
console.log ("data on at "+diff);
var mins = Math.floor(diff / 60000);
var secs = Math.floor((diff % 60000) / 1000);
$("#recordCall").text(""+mins+":"+secs);
}
function recordCall() {
if (!recorder) {
startRecTime = Date.now();
var recStream = myac.createMediaStreamDestination();
recorder = new MediaRecorder(recStream.stream);
localpanned.connect(recStream);
localdcomp.connect(recStream);
recorder.ondataavailable = function (evt) {
chunks.push(evt.data);
repaintDuration();
};
recorder.onstop = function (evt) {
// Make blob out of our blobs, and open it.
var blob = new Blob(chunks, {'type': 'audio/ogg; codecs=opus'});
saveData(blob)
};
recorder.start(10000);
repaintDuration();
saved = false;
window.onbeforeunload = function() {
return !saved ? "If you leave this page you will lose the recording." : null;
}
} else {
recorder.stop();
recorder = null;
}
}
function saveData(blob) {
var fileName = 'Rendezvous-zone-'+new Date().toISOString() + '.webm';
console.log("Save data ?");
var a = document.createElement("a");
document.body.appendChild(a);
a.style = "display: none";
console.log("saving wav blob as " + fileName);
var burl = window.URL.createObjectURL(blob);
a.href = burl;
a.download = fileName;
a.click();
window.URL.revokeObjectURL(burl);
saved = true;
$("#status").text("Call saved as "+fileName);
}
function noShareApp() {
$('#share').modal('show');
}
async function shareMyApp() {
try {
var displayMediaOptions ={