This repository has been archived by the owner on Jun 23, 2023. It is now read-only.
forked from chris-morgan/tty-player
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tty-player.js
1719 lines (1513 loc) · 55.2 KB
/
tty-player.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 'webcomponents-lite';
import Terminal from 'term.js/src/term.js';
// W069 is “['x'] is better written in dot notation”, but Closure Compiler wants ['x'].
// jshint -W069
// jshint bitwise: false
// ==ClosureCompiler==
// @output_file_name tty-player.min.js
// @compilation_level ADVANCED_OPTIMIZATIONS
// ==/ClosureCompiler==
/* global MediaError, TimeRanges, Terminal, HTMLElement */
;(function() {
"use strict";
var textDecoder = "TextDecoder" in window ? new TextDecoder() : null;
/// @param {Array<number>|Uint8Array} array
function decodeUTF8(array) {
if (array instanceof Array || !textDecoder) {
return decodeURIComponent(Array.prototype.map.call(array, function(ord) {
return "%" + ("0" + ord.toString(16)).substr(-2);
}).join(""));
} else {
return textDecoder.decode(array);
}
}
/// parseDataURI("data:foo/bar;base64,MTIzNA==#foo") === "1234"
/// @param {string} uri
function parseDataURI(uri) {
// [whole uri, "base64" or undefined, data]
var chunks = /^data:([^,]*),([^#]+)/.exec(uri);
if (chunks === null) {
return null;
}
var data = decodeURIComponent(chunks[2]);
var mime = chunks[1].replace(/;base64$/, "");
return [mime, mime === chunks[1] ? data : atob(data)];
}
/// @param {Array<number>|Uint8Array} array
function byteArrayToString(array) {
// String.fromCharCode.apply can for too large values overflow the call stack.
// Hence this, though I doubt we actually use large enough strings to worry.
// http://stackoverflow.com/a/12713326
var CHUNK_SIZE = 0x8000;
var c = [];
for (var i = 0; i < array.length; i += CHUNK_SIZE) {
c.push(String.fromCharCode.apply(null, array["subarray" in array ? "subarray" : "slice"](i, i + CHUNK_SIZE)));
}
return c.join("");
}
function parseNPT(npt) {
// Format: [npt:]([h:]mm:ss|seconds)[.subsecond]
// I’ve decided to be lazy and allow "1:2:3.4" as well as "1:02:03.4"
// This makes it [npt:][[h:]m:]s[.subsecond]
var match = /^(?:npt:)?(?:(?:(\d+):)?(\d+):)?(\d+(?:\.\d+)?)$/i.exec(npt);
return match ? (match[1] || 0) * 3600 + (match[2] || 0) * 60 + match[3] : null;
}
function classifyPosterURL(url) {
if (!url) {
// There is no poster.
return {type: null};
}
switch (/^(?:(.*):)?/.exec(url)[1]) {
case "npt":
var time = parseNPT(url);
return time ? {type: "npt", time: time} : {type: null};
case "data":
var data = parseDataURI(url);
if (/^text\/plain$/i.test(data[0])) {
return {type: "text", data: data[1]};
}
}
// TODO: treat all the other possibilities as images.
return {type: null};
}
/// @param {ArrayBuffer|Array<number>} source
function parseTTYRec(source) {
var isArray = source instanceof Array;
var utf8 = true;
var dimensions = null;
var data = [];
var byteOffset = 0;
var timeOffset = 0;
var sourceLength = isArray ? source.length : source.byteLength;
while (byteOffset < sourceLength) {
var sec, usec, len;
if (!isArray) {
var header = new DataView(source, byteOffset);
sec = header.getUint32(0, true);
usec = header.getUint32(4, true);
len = header.getUint32(8, true);
} else {
sec = source[byteOffset] +
(source[byteOffset + 1] << 8) +
(source[byteOffset + 2] << 16) +
(source[byteOffset + 3] << 24);
usec = source[byteOffset + 4] +
(source[byteOffset + 5] << 8) +
(source[byteOffset + 6] << 16) +
(source[byteOffset + 7] << 24);
len = source[byteOffset + 8] +
(source[byteOffset + 9] << 8) +
(source[byteOffset + 10] << 16) +
(source[byteOffset + 11] << 24);
}
var time = sec + (usec / 1000000);
byteOffset += 12;
var payload = isArray ? source.slice(byteOffset, byteOffset + len)
: new Uint8Array(source, byteOffset, len);
payload = utf8 ? decodeUTF8(payload) : byteArrayToString(payload);
if (byteOffset === 12) {
// First chunk might be metadata; this is how termrec does it, for example.
timeOffset = time;
var metadata = /^\x1b%(G|@)\x1b\[8;([0-9]+);([0-9]+)t$/.exec(payload);
if (metadata) {
utf8 = metadata[1] === "G";
dimensions = {
rows: +metadata[2],
cols: +metadata[3]
};
}
}
time -= timeOffset;
byteOffset += len;
data.push([payload, time]);
}
return {
// Heuristic: if the time offset is large enough, it’s probably a timestamp.
startDate: timeOffset >= 1e8 ? new Date(timeOffset * 1000) : null,
dimensions: dimensions,
data: data
};
}
function formatTime(time) {
var seconds = time | 0;
var minutes = seconds / 60 | 0;
seconds = ("0" + (seconds % 60)).substr(-2);
if (minutes >= 60) {
var hours = minutes / 60 | 0;
minutes = ("0" + (minutes % 60)).substr(-2);
return hours + ":" + minutes + ":" + seconds;
} else {
return minutes + ":" + seconds;
}
}
function blankableAttributeProperty(name) {
return {
get: function() {
var value = this.getAttribute(name);
return value === null ? "" : value.trim();
},
set: function(value) {
this.setAttribute(name, value);
}
};
}
function attributeBooleanProperty(name) {
return {
get: function() {
return this.hasAttribute(name);
},
set: function(bool) {
if (bool) {
this.setAttribute(name, "");
} else {
this.removeAttribute(name);
}
}
};
}
function invalidStateError() {
document.createElement("video").currentTime = 1;
}
/** @const */ var NETWORK_EMPTY = 0;
/** @const */ var NETWORK_IDLE = 1;
/** @const */ var NETWORK_LOADING = 2;
/** @const */ var NETWORK_NO_SOURCE = 3;
/** @const */ var HAVE_NOTHING = 0;
/** @const */ var HAVE_METADATA = 1;
/** @const */ var HAVE_CURRENT_DATA = 2;
/** @const */ var HAVE_FUTURE_DATA = 3;
/** @const */ var HAVE_ENOUGH_DATA = 4;
// Annoyingly, with things like MediaError, one apparently can’t construct them in any way.
// So we fake it like this.
// Note that the constants on MediaError are *not* on MyMediaError, though they are on instances.
var MyMediaError = /** @constructor */ function MediaError(code) {
Object.defineProperty(this, "code", {value: code});
};
MyMediaError.prototype = Object.create(MediaError.prototype);
/** @const */ var EMPTY_TIME_RANGES = document.createElement("video").played;
var MyTimeRanges = /** @constructor */ function TimeRanges(ranges) {
Object.defineProperty(this, "length", {value: ranges.length});
this["_"] = ranges;
};
MyTimeRanges.prototype = Object.create(TimeRanges.prototype);
MyTimeRanges.prototype["start"] = function(i) {
if (i < this["length"]) {
return this["_"][i][0];
} else {
return EMPTY_TIME_RANGES["end"](0); // Throws IndexSizeError
}
};
MyTimeRanges.prototype["end"] = function(i) {
if (i < this["length"]) {
return this["_"][i][1];
} else {
return EMPTY_TIME_RANGES["end"](0); // Throws IndexSizeError
}
};
/** @const */ var MEDIA_ERR_ABORTED = 1;
/** @const */ var MEDIA_ERR_NETWORK = 2;
/** @const */ var MEDIA_ERR_DECODE = 3;
/** @const */ var MEDIA_ERR_SRC_NOT_SUPPORTED = 4;
/** @const */ var ERROR_DETAILS = {
1: ["MEDIA_ERR_ABORTED", "The fetching process for the media resource was aborted by the user agent at the user's request."],
2: ["MEDIA_ERR_NETWORK", "A network error of some description caused the user agent to stop fetching the media resource, after the resource was established to be usable."],
3: ["MEDIA_ERR_DECODE", "An error of some description occurred while decoding the media resource, after the resource was established to be usable."],
4: ["MEDIA_ERR_SRC_NOT_SUPPORTED", "The media resource indicated by the \x1b[4msrc\x1b[24m attribute was not suitable."]
};
/** @const */ var FANCY_TECHNICAL_ERROR_EXPLANATIONS = true;
var menuIdSequence = 0;
function makeMenu(ttyPlayer) {
// Make a context menu with these items:
// - Play/Pause
// - Show/Hide Controls
//
// Firefox also has the following ones deemed unnecessary:
//
// - Mute/Unmute
// - Play Speed >
// - Slow Motion (0.5×)
// - Normal Speed (1×)
// - High Speed (1.5×)
// - Ludicrous Speed (2×)
// - Show Statistics
// - Full Screen
//
// Chrome has Show controls (lowercase c) as a toggle and adds a Loop item.
var menu = document.createElement("menu");
if (!("type" in menu)) {
return null;
}
try {
menu.type = "context";
} catch (e) {
// IE 11, "Invalid argument."
}
if (menu.type !== "context") {
return null;
}
menu.id = "treplay-contextmenu-" + menuIdSequence++;
var playPause = document.createElement("menuitem");
playPause.onclick = function() {
if (ttyPlayer["paused"]) {
ttyPlayer["play"]();
} else {
ttyPlayer["pause"]();
}
};
function setPlayPauseDetails(label, path) {
playPause.label = label;
playPause.icon = "data:image/svg+xml,%3C?xml version='1.0' encoding='UTF-8' standalone='no'?%3E%3Csvg xmlns='http://www.w3.org/2000/svg' width='16' height='16'%3E%3Cpath stroke='%23999' stroke-width='1' fill='%23eee' d='" + path + "'/%3E%3C/svg%3E";
}
function onPlay() {
setPlayPauseDetails("Pause", "m2.5,1.5 0,13 4,0 0,-13zm7,0 0,13 4,0 0,-13z");
}
function onPause() {
setPlayPauseDetails("Play", "m2.5,2 0,12 11,-6z");
}
onPause();
ttyPlayer.addEventListener("play", onPlay);
ttyPlayer.addEventListener("pause", onPause);
var controls = document.createElement("menuitem");
menu.onControlsShownOrHidden = function() {
if (ttyPlayer["controls"]) {
controls.label = "Hide Controls";
} else {
controls.label = "Show Controls";
}
};
menu.onControlsShownOrHidden();
controls.onclick = function() {
ttyPlayer["controls"] = !ttyPlayer["controls"];
};
menu.appendChild(playPause);
menu.appendChild(controls);
return menu;
}
// TODO: reset() hides the cursor; patch term.js so if useFocus === false it is shown by default?
var stockReset = Terminal.prototype["reset"];
Terminal.prototype["reset"] = function() {
stockReset.call(this);
if ("useFocus" in this["options"] && !this["options"]["useFocus"]) {
this["showCursor"]();
}
};
// IDL for this code:
//
// interface HTMLTTYPlayerElement : HTMLMediaElement {
// attribute DOMString defaultTitle;
// attribute DOMString title;
//
// readonly attribute unsigned long cols;
// readonly attribute unsigned long rows;
// void resize(unsigned long cols, unsigned long rows);
//
// attribute EventHandler ontitlechange;
//
// // This one is straight from HTMLVideoElement.
// attribute DOMString poster;
//
// // s/void/avoid/
// void pretendToBeAVideo();
// }
//
// IDL taken from HTML 5 spec:
//
// enum CanPlayTypeEnum { "" /* empty string */, "maybe", "probably" };
// interface HTMLMediaElement : HTMLElement {
//
// // error state
// readonly attribute MediaError? error;
//
// // network state
// attribute DOMString src;
// readonly attribute DOMString currentSrc;
// attribute DOMString crossOrigin;
// const unsigned short NETWORK_EMPTY = 0;
// const unsigned short NETWORK_IDLE = 1;
// const unsigned short NETWORK_LOADING = 2;
// const unsigned short NETWORK_NO_SOURCE = 3;
// readonly attribute unsigned short networkState;
// attribute DOMString preload;
// readonly attribute TimeRanges buffered;
// void load();
// CanPlayTypeEnum canPlayType(DOMString type);
//
// // ready state
// const unsigned short HAVE_NOTHING = 0;
// const unsigned short HAVE_METADATA = 1;
// const unsigned short HAVE_CURRENT_DATA = 2;
// const unsigned short HAVE_FUTURE_DATA = 3;
// const unsigned short HAVE_ENOUGH_DATA = 4;
// readonly attribute unsigned short readyState;
// readonly attribute boolean seeking;
//
// // playback state
// attribute double currentTime;
// readonly attribute unrestricted double duration;
// Date getStartDate();
// readonly attribute boolean paused;
// attribute double defaultPlaybackRate;
// attribute double playbackRate;
// readonly attribute TimeRanges played;
// readonly attribute TimeRanges seekable;
// readonly attribute boolean ended;
// attribute boolean autoplay;
// attribute boolean loop;
// void play();
// void pause();
//
// // media controller
// attribute DOMString mediaGroup;
// attribute MediaController? controller;
//
// // controls
// attribute boolean controls;
// attribute double volume;
// attribute boolean muted;
// attribute boolean defaultMuted;
//
// // tracks
// readonly attribute AudioTrackList audioTracks;
// readonly attribute VideoTrackList videoTracks;
// readonly attribute TextTrackList textTracks;
// TextTrack addTextTrack(TextTrackKind kind, optional DOMString label = "", optional DOMString language = "");
// };
//
// interface HTMLVideoElement : HTMLMediaElement {
// attribute unsigned long width;
// attribute unsigned long height;
// readonly attribute unsigned long videoWidth;
// readonly attribute unsigned long videoHeight;
// attribute DOMString poster;
// };
/** @constructor */
function TTYPlayerInternalState(ttyPlayer) {
this.ttyPlayer = ttyPlayer;
}
var ISP = TTYPlayerInternalState.prototype;
ISP.setUp = function() {
var self = this;
var ttyPlayer = self.ttyPlayer;
self.titleElement = document.createElement("div");
self.titleElement.className = "title";
ttyPlayer.appendChild(self.titleElement);
self.terminal = new Terminal({"useFocus": false});
self.terminal.on("title", function(newTitle) {
ttyPlayer["title"] = newTitle;
});
self.terminal.open(ttyPlayer);
if (FANCY_TECHNICAL_ERROR_EXPLANATIONS) {
ttyPlayer.addEventListener("error", function() {
var details = ERROR_DETAILS[self.error.code];
self.terminal.reset();
self.terminal.write(
"\x1b]2;Error :-(\x07" +
"\r\n\x1b[1mMediaError.\x1b[31m" + details[0] + "\x1b[m " +
"(numeric value " + self.error.code + ")\r\n\r\n" +
" " + details[1] + "\r\n\r\n(Sorry ’bout that.)");
});
}
var rows = +ttyPlayer.getAttribute("rows");
var cols = +ttyPlayer.getAttribute("cols");
ttyPlayer["resize"](cols > 0 ? cols : ttyPlayer["cols"],
rows > 0 ? rows : ttyPlayer["rows"]);
// XXX: properties with names used in the DOM don’t get shrunk by Closure
// Compiler’s advanced optimizations, for safety. We could get size down a
// smidgeon more by renaming them all, but that’d be uglier.
// Candidates: defaultPlaybackRate, playbackRate, currentSrc, readyState, networkState, paused, duration.
self.defaultPlaybackRate = self.playbackRate = 1;
self.defaultPlaybackStartPosition = 0;
self.currentSrc = "";
self.readyState = HAVE_NOTHING;
self.networkState = NETWORK_EMPTY;
self.paused = true;
self.duration = NaN;
self.defaultTitle = ttyPlayer.getAttribute("window-title") || "";
self.posterOverlay = document.createElement("tty-player-poster");
self.posterOverlay.onclick = function() {
ttyPlayer["play"]();
};
self.terminal.on("resize", function() {
// ttyPlayer.rows and ttyPlayer.cols have changed, fire an appropriate event
self.fireSimpleEvent("resize");
});
self.menu = makeMenu(ttyPlayer);
if (self.menu) {
ttyPlayer.appendChild(self.menu);
ttyPlayer.setAttribute("contextmenu", self.menu.id);
}
self.controlsElement = document.createElement("tty-player-controls");
var play = document.createElement("button");
play.className = "play";
play.onclick = function() {
if (ttyPlayer["paused"]) {
ttyPlayer["play"]();
} else {
ttyPlayer["pause"]();
}
};
ttyPlayer.addEventListener("play", function() {
play.className = "pause";
});
ttyPlayer.addEventListener("pause", function() {
play.className = "play";
});
self.currentTimeElement = document.createElement("span");
self.currentTimeElement.className = "current-time";
self.currentTimeElement.textContent = "0:00";
self.durationElement = document.createElement("span");
self.durationElement.className = "duration";
self.durationElement.textContent = "0:00";
self.progressElement = document.createElement("input");
self.progressElement.type = "range";
self.progressElement.value = 0;
self.progressElement.min = 0;
self.progressElement.step = "any";
var skipChange = false;
self.progressElement.addEventListener("input", function() {
if (!skipChange) {
skipChange = true;
self.semipaused = true;
ttyPlayer["currentTime"] = self.progressElement.value;
self.updateCurrentTimeElement();
skipChange = false;
}
});
self.progressElement.addEventListener("change", function() {
if (!skipChange) {
skipChange = true;
self.semipaused = false;
ttyPlayer["currentTime"] = self.progressElement.value;
self.updateCurrentTimeElement();
skipChange = false;
}
});
ttyPlayer.addEventListener("durationchange", function() {
self.progressElement.max = self.duration;
self.durationElement.textContent = formatTime(self.duration);
});
ttyPlayer.addEventListener("timeupdate", function() {
if (!skipChange) {
skipChange = true;
self.progressElement.value = self.currentTime;
self.updateCurrentTimeElement();
skipChange = false;
}
});
self.controlsElement.appendChild(play);
self.controlsElement.appendChild(self.currentTimeElement);
self.controlsElement.appendChild(self.progressElement);
self.controlsElement.appendChild(self.durationElement);
ttyPlayer.appendChild(self.posterOverlay);
ttyPlayer.appendChild(self.controlsElement);
self.showPoster = true;
};
Object.defineProperties(ISP, {
/** @lends {ISP} */
showPoster: {
get: function() {
return this._showPoster;
},
set: function(newValue) {
// TODO: this is problematic because it doesn’t keep track of what
// poster is active, it just uses the current value of poster. We
// should probably store the value of poster and use it for
// removing it.
var self = this;
var oldValue = self._showPoster;
newValue = !!newValue;
var newPoster = classifyPosterURL(self.ttyPlayer["poster"]);
self._showPoster = !!newValue;
// We don’t show the overlay if there is an error
var showOverlay = newValue && !self.error;
self.posterOverlay.style.display = showOverlay ? "" : "none";
self.controlsElement.classList[showOverlay ? "add" : "remove"]("poster");
self.progressElement.disabled = newValue;
self.controlsShownOrHidden();
if (oldValue === newValue && self.activePoster === newPoster) {
// No change to make
return;
}
// If we need to do anything special to remove a poster, here’s what we’ll do:
// if (oldValue) {
// switch (self.activePoster.type) {
// case "foo":
// …
// }
// }
self.activePoster = newPoster;
if (oldValue || newValue) {
// Yes, we’re missing the optimisation possibility of poster=npt:X
// changing to poster=npt:Y where Y > X. Seriously, adjusting
// poster *at all* is rare enough that I don’t care.
self.resetTerminal();
}
if (newValue) {
// Show the new poster
switch (newPoster.type) {
case "npt":
// We have an NPT poster to create.
self.resetTerminal();
var realShowPoster = function() {
if (newValue !== self._showPoster) {
// Sorry, you took too long and I don’t want to do anything now;
// something else is doing it.
return;
}
if (newValue) {
var currentTime = self.currentTime;
var semipaused = self.semipaused;
self.semipaused = true;
self.currentTime = newPoster.time;
self.nextDataIndex = 0;
self.render();
self.semipaused = semipaused;
self.currentTime = currentTime;
}
};
if (self.data) {
realShowPoster();
} else {
var loaded = function() {
self.ttyPlayer.removeEventListener("canplaythrough", loaded);
realShowPoster();
};
self.ttyPlayer.addEventListener("canplaythrough", loaded);
self.loadIfNotLoading();
}
break;
case "text":
self.resetTerminal();
self.terminal.write(newPoster.data);
}
}
}
}
});
/// Firing a simple event named e means that a trusted event with the name
/// e, which does not bubble (except where otherwise stated) and is not
/// cancelable (except where otherwise stated), and which uses the Event
/// interface, must be created and dispatched at the given target.
/// INCONSISTENCY: isTrusted = false
ISP.fireSimpleEvent = function(name) {
var event = document.createEvent("HTMLEvents");
event.initEvent(name, false, false);
var f = this.ttyPlayer["on" + name];
if (typeof f === "function") {
f(event);
}
this.ttyPlayer.dispatchEvent(event);
};
ISP.controlsShownOrHidden = function() {
this.updateCurrentTimeElement();
if (this.menu) {
this.menu.onControlsShownOrHidden();
}
};
ISP.updateCurrentTimeElement = function() {
this.currentTimeElement.textContent = formatTime(this.currentTime);
var left = this.progressElement.offsetLeft - (this.currentTimeElement.offsetWidth / 2);
if (!isNaN(this.duration)) {
left += this.currentTime / this.duration * this.progressElement.offsetWidth;
}
this.currentTimeElement.style.left = left + "px";
};
/** @const */ var TICK = 16;
/** @const */ var TIME_UPDATE_FREQUENCY = 100;
ISP.lastTimeUpdate = 0;
ISP.render = function() {
// Should the currently rendered frame (next - 1) be drawn?
if (this.nextDataIndex > 0 && this.data[this.nextDataIndex - 1][1] > this.currentTime) {
// No, but undoing isn’t possible, so we must replay from the start.
// This is highly inefficient; for large scripts it’s utterly untenable.
this.resetTerminal();
this.nextDataIndex = 0;
}
while (this.nextDataIndex < this.data.length && this.data[this.nextDataIndex][1] <= this.currentTime) {
this.terminal.write(this.data[this.nextDataIndex][0]);
this.nextDataIndex++;
}
if (this.semipaused) {
return;
}
// Have we reached the end? Let’s stop.
if ((this.currentTime >= this.duration && this.playbackRate > 0) ||
(this.currentTime <= 0 && this.playbackRate < 0)) {
if (this.ttyPlayer["loop"]) {
this.ttyPlayer["currentTime"] = this.playbackRate > 0 ? 0 : this.duration;
} else {
this.fireSimpleEvent("timeupdate");
this.ttyPlayer["pause"]();
this.fireSimpleEvent("ended");
}
} else {
// Do we need to fire a timeupdate event? We should do them every 66–350ms; Firefox does 250 for video, but because the average length is going to be shorter and because I can, I’m going for 100ms.
var time = +new Date();
if (time - this.lastTimeUpdate >= TIME_UPDATE_FREQUENCY) {
this.lastTimeUpdate = time;
this.fireSimpleEvent("timeupdate");
}
}
};
ISP.resetTerminal = function() {
this.terminal.reset();
this.ttyPlayer["title"] = this.defaultTitle;
};
ISP.loadIfNotLoading = function() {
if (this.networkState < NETWORK_LOADING) {
this.mediaLoadAlgorithm();
}
};
ISP.mediaLoadAlgorithm = function() {
this.resetTerminal();
// > The media load algorithm consists of the following steps.
// > 1. Abort any already-running instance of the resource selection
// > algorithm for this element.
if (this.resourceFetchXHR) {
this.resourceFetchXHR.abort();
}
// > 2. If there are any tasks from the media element's media element
// > event task source in one of the task queues, then remove those
// > tasks.
// >
// > If there are any tasks that were queued by the resource
// > selection algorithm (including the algorithms that it itself
// > invokes) for this same media element from the DOM manipulation
// > task source in one of the task queues, then remove those tasks.
// >
// > Note: Basically, pending events and callbacks for the media
// > element are discarded when the media element starts loading a
// > new resource.
//
// [Nothing to do, we aren’t queuing events.]
// > 3. If the media element's networkState is set to NETWORK_LOADING
// > or NETWORK_IDLE, queue a task to fire a simple event named
// > abort at the media element.
if (this.networkState === NETWORK_LOADING ||
this.networkState === NETWORK_IDLE) {
this.fireSimpleEvent("abort");
}
// > 4. If the media element's networkState is not set to
// > NETWORK_EMPTY, then run these substeps:
if (this.networkState !== NETWORK_EMPTY) {
// > 1. Queue a task to fire a simple event named emptied at the
// > media element.
this.fireSimpleEvent("emptied");
// > 2. If a fetching process is in progress for the media element,
// > the user agent should stop it.
// TODO.
// > 3. Forget the media element's media-resource-specific tracks.
// [Not applicable.]
// > 4. If readyState is not set to HAVE_NOTHING, then set it to
// > that state.
this.readyState = HAVE_NOTHING;
// > 5. If the paused attribute is false, then set it to true.
this.paused = true;
clearInterval(this.ticker);
// > 6. If seeking is true, set it to false.
// [Not applicable.]
// > 7. Set the current playback position to 0.
// >
// > Set the official playback position to 0.
// >
// > If this changed the official playback position, then queue
// > a task to fire a simple event named timeupdate at the
// > media element.
var oldTime = this.currentTime;
this.currentTime = 0;
this.nextDataIndex = 0;
if (oldTime !== 0) {
this.fireSimpleEvent("timeupdate");
}
// > 8. Set the initial playback position to 0.
// Not applicable (TODO? Might be useful?)
// > 9. Set the timeline offset to Not-a-Number (NaN).
// TODO (haven’t finished supporting timeline offsets)
// > 10. Update the duration attribute to Not-a-Number (NaN).
// >
// > The user agent will not fire a durationchange event for
// > this particular change of the duration.
this.data = null;
this.duration = NaN;
}
// > 5. Set the playbackRate attribute to the value of the defaultPlaybackRate attribute.
this.playbackRate = this.defaultPlaybackRate;
// > 6. Set the error attribute to null and the autoplaying flag to true.
this.error = null;
// TODO.
// > 7. Invoke the media element's resource selection algorithm.
this.resourceSelectionAlgorithm();
// > 8. Note: Playback of any previously playing media resource for this element stops.
// Already done.
};
ISP.resourceSelectionAlgorithm = function() {
var self = this;
// We use a simplified version of the resource selection algorithm,
// as we support only one type, don’t use <source> (src only) and
// handle synchronosity differently.
// > 1. Set the element's networkState attribute to the
// > NETWORK_NO_SOURCE value.
self.networkState = NETWORK_NO_SOURCE;
// > 2. Set the element's show poster flag to true.
self.showPoster = true;
// > 3. Set the media element's delaying-the-load-event flag to
// > true (this delays the load event).
// TODO.
// > 4. Asynchronously await a stable state, allowing the task that
// > invoked this algorithm to continue. The synchronous section
// > consists of all the remaining steps of this algorithm until
// > the algorithm says the synchronous section has ended.
// > (Steps in synchronous sections are marked with ⌛.)
// > 5. ⌛ If the media element's blocked-on-parser flag is false,
// > then populate the list of pending text tracks.
// [Not applicable.]
// > 6. ⌛ If the media element has a src attribute, then let mode
// > be attribute.
// >
// > ⌛ Otherwise, if the media element does not have a src
// > attribute but has a source element child, then let mode be
// > children and let candidate be the first such source element
// > child in tree order.
// >
// > ⌛ Otherwise the media element has neither a src attribute
// > nor a source element child: set the networkState to
// > NETWORK_EMPTY, and abort these steps; the synchronous
// > section ends.
//
// We don’t support <source> at present, so this is simpler.
var src = self.ttyPlayer.getAttribute("src");
if (src === null) {
self.networkState = NETWORK_EMPTY;
return;
}
// > 7. ⌛ Set the media element's networkState to NETWORK_LOADING.
self.networkState = NETWORK_LOADING;
// > 8. ⌛ Queue a task to fire a simple event named loadstart at
// > the media element.
self.fireSimpleEvent("loadstart");
// > 9. If mode is attribute, then run these substeps:
// [We don’t support <source>, so this is guaranteed.]
// > 1. ⌛ If the src attribute's value is the empty string, then
// > end the synchronous section, and jump down to the failed
// > with attribute step below.
if (src === "") {
return self.resourceSelectionAlgorithmFailedWithAttribute();
}
// > 2. ⌛ Let absolute URL be the absolute URL that would have
// > resulted from resolving the URL specified by the src
// > attribute's value relative to the media element when the
// > src attribute was last changed.
var absoluteURL = new URL(src.trim(), self.ttyPlayer.baseURI);
// > 3. ⌛ If absolute URL was obtained successfully, set the
// > currentSrc attribute to absolute URL.
self.currentSrc = absoluteURL.toString();
// > 4. End the synchronous section, continuing the remaining steps
// > asynchronously.
setTimeout(function() {
// > 5. If absolute URL was obtained successfully, run the resource
// > fetch algorithm with absolute URL. If that algorithm
// > returns without aborting this one, then the load failed.
// Due to the simpler model used, supporting aborting isn’t necessary.
self.resourceFetchAlgorithm();
}, 0);
};
ISP.resourceSelectionAlgorithmFailedWithAttribute = function() {
// > 6. Failed with attribute: Reaching this step indicates that
// > the media resource failed to load or that the given URL
// > could not be resolved. Queue a task to run the following
// > steps, using the DOM manipulation task source:
// > 1. Set the error attribute to a new MediaError object whose code attribute is set to MEDIA_ERR_SRC_NOT_SUPPORTED.
this.error = new MyMediaError(MEDIA_ERR_SRC_NOT_SUPPORTED);
// > 2. Forget the media element's media-resource-specific tracks.
// [Nothing to do.]
// > 3. Set the element's networkState attribute to the NETWORK_NO_SOURCE value.
this.networkState = NETWORK_NO_SOURCE;
// > 4. Set the element's show poster flag to true.
this.showPoster = true;
// > 5. Fire a simple event named error at the media element.
this.fireSimpleEvent("error");
// > 6. Set the element's delaying-the-load-event flag to false. This stops delaying the load event.
//this.delayingTheLoadEvent = false;
// > 7. Wait for the task queued by the previous step to have executed.
// [Not queueing tasks, so nothing to do.]
// > 8. Abort these steps. Until the load() method is invoked or the src attribute is changed, the element won't attempt to load another resource.
};
ISP.resourceFetchAlgorithm = function() {
var self = this;
function finishResourceFetchAlgorithm() {
delete self.resourceFetchXHR;
}
function continueResourceFetchAlgorithm(data) {
// > Once enough of the media data has been fetched to determine
// > the duration of the media resource, its dimensions, and other
// > metadata:
// >
// > This indicates that the resource is usable. The user agent
// > must follow these substeps:
// >
// > 1. Establish the media timeline for the purposes of the
// > current playback position, the earliest possible position,
// > and the initial playback position, based on the media data.
// [TODO support such things?]
// > 2. Update the timeline offset to the date and time that
// > corresponds to the zero time in the media timeline
// > established in the previous step, if any. If no explicit
// > time and date is given by the media resource, the timeline
// > offset must be set to Not-a-Number (NaN).
// [Nothing to do.]
// > 3. Set the current playback position and the official playback
// > position to the earliest possible position.
self.currentTime = 0;
self.nextDataIndex = 0;
// > 4. Update the duration attribute with the time of the last
// > frame of the resource, if known, on the media timeline
// > established above. If it is not known (e.g. a stream that
// > is in principle infinite), update the duration attribute to
// > the value positive Infinity.
// >
// > Note: The user agent will queue a task to fire a simple
// > event named durationchange at the element at this point.
self.data = data.data;
self.duration = data.data.length === 0 ? 0 : data.data[data.data.length - 1][1];
self.fireSimpleEvent("durationchange");
// > 5. For video elements, set the videoWidth and videoHeight
// > attributes, and queue a task to fire a simple event named
// > resize at the media element.
// >
// > Note: Further resize events will be fired if the dimensions
// > subsequently change.
// TODO: allow this to be written on the HTML
// TODO: modify the file format to track window sizes, then do
// something like this (ttyWidth and ttyHeight, in chars, I
// think).
// These are taken straight from term.js; TODO: modify it to send resize events.
if (data.dimensions) {
self.ttyPlayer["resize"](data.dimensions.cols, data.dimensions.rows);
}
// XXX: the spec mentions getStartDate(), which data.startDate