-
Notifications
You must be signed in to change notification settings - Fork 0
/
vtt.js
1344 lines (1218 loc) · 44 KB
/
vtt.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
/**
* Copyright 2013 vtt.js Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */
(function(global) {
function makeColorSet(color, opacity) {
if(opacity === undefined) {
opacity = 1;
}
return "rgba(" + [parseInt(color.substring(0, 2), 16),
parseInt(color.substring(2, 4), 16),
parseInt(color.substring(4, 6), 16),
opacity].join(",") + ")";
}
var WebVTTPrefs = ['webvtt.font.color', 'webvtt.font.opacity', 'webvtt.font.scale',
'webvtt.bg.color', 'webvtt.bg.opacity',
'webvtt.edge.color', 'webvtt.edge.type'];
var fontScale = 1;
function observe(subject, topic, data) {
switch (data) {
case "webvtt.font.color":
case "webvtt.font.opacity":
var fontColor = Services.prefs.getCharPref("webvtt.font.color");
var fontOpacity = Services.prefs.getIntPref("webvtt.font.opacity") / 100;
WebVTTSet.fontSet = makeColorSet(fontColor, fontOpacity);
break;
case "webvtt.font.scale":
fontScale = Services.prefs.getIntPref("webvtt.font.scale") / 100;
break;
case "webvtt.bg.color":
case "webvtt.bg.opacity":
var backgroundColor = Services.prefs.getCharPref("webvtt.bg.color");
var backgroundOpacity = Services.prefs.getIntPref("webvtt.bg.opacity") / 100;
WebVTTSet.backgroundSet = makeColorSet(backgroundColor, backgroundOpacity);
break;
case "webvtt.edge.color":
case "webvtt.edge.type":
var edgeTypeList = ["", "0px 0px ", "4px 4px 4px ", "-2px -2px ", "2px 2px "];
var edgeType = Services.prefs.getIntPref("webvtt.edge.type");
var edgeColor = Services.prefs.getCharPref("webvtt.edge.color");
WebVTTSet.edgeSet = edgeTypeList[edgeType] + makeColorSet(edgeColor);
break;
}
}
if(typeof Services !== "undefined") {
var WebVTTSet = {};
WebVTTPrefs.forEach(function (pref) {
observe(undefined, undefined, pref);
Services.prefs.addObserver(pref, observe, false);
});
}
var _objCreate = Object.create || (function() {
function F() {}
return function(o) {
if (arguments.length !== 1) {
throw new Error('Object.create shim only accepts one parameter.');
}
F.prototype = o;
return new F();
};
})();
// Creates a new ParserError object from an errorData object. The errorData
// object should have default code and message properties. The default message
// property can be overriden by passing in a message parameter.
// See ParsingError.Errors below for acceptable errors.
function ParsingError(errorData, message) {
this.name = "ParsingError";
this.code = errorData.code;
this.message = message || errorData.message;
}
ParsingError.prototype = _objCreate(Error.prototype);
ParsingError.prototype.constructor = ParsingError;
// ParsingError metadata for acceptable ParsingErrors.
ParsingError.Errors = {
BadSignature: {
code: 0,
message: "Malformed WebVTT signature."
},
BadTimeStamp: {
code: 1,
message: "Malformed time stamp."
}
};
// Try to parse input as a time stamp.
function parseTimeStamp(input) {
function computeSeconds(h, m, s, f) {
return (h | 0) * 3600 + (m | 0) * 60 + (s | 0) + (f | 0) / 1000;
}
var m = input.match(/^(\d+):(\d{2})(:\d{2})?\.(\d{3})/);
if (!m) {
return null;
}
if (m[3]) {
// Timestamp takes the form of [hours]:[minutes]:[seconds].[milliseconds]
return computeSeconds(m[1], m[2], m[3].replace(":", ""), m[4]);
} else if (m[1] > 59) {
// Timestamp takes the form of [hours]:[minutes].[milliseconds]
// First position is hours as it's over 59.
return computeSeconds(m[1], m[2], 0, m[4]);
} else {
// Timestamp takes the form of [minutes]:[seconds].[milliseconds]
return computeSeconds(0, m[1], m[2], m[4]);
}
}
// A settings object holds key/value pairs and will ignore anything but the first
// assignment to a specific key.
function Settings() {
this.values = _objCreate(null);
}
Settings.prototype = {
// Only accept the first assignment to any key.
set: function(k, v) {
if (!this.get(k) && v !== "") {
this.values[k] = v;
}
},
// Return the value for a key, or a default value.
// If 'defaultKey' is passed then 'dflt' is assumed to be an object with
// a number of possible default values as properties where 'defaultKey' is
// the key of the property that will be chosen; otherwise it's assumed to be
// a single value.
get: function(k, dflt, defaultKey) {
if (defaultKey) {
return this.has(k) ? this.values[k] : dflt[defaultKey];
}
return this.has(k) ? this.values[k] : dflt;
},
// Check whether we have a value for a key.
has: function(k) {
return k in this.values;
},
// Accept a setting if its one of the given alternatives.
alt: function(k, v, a) {
for (var n = 0; n < a.length; ++n) {
if (v === a[n]) {
this.set(k, v);
break;
}
}
},
// Accept a setting if its a valid (signed) integer.
integer: function(k, v) {
if (/^-?\d+$/.test(v)) { // integer
this.set(k, parseInt(v, 10));
}
},
// Accept a setting if its a valid percentage.
percent: function(k, v) {
var m;
if ((m = v.match(/^([\d]{1,3})(\.[\d]*)?%$/))) {
v = parseFloat(v);
if (v >= 0 && v <= 100) {
this.set(k, v);
return true;
}
}
return false;
}
};
// Helper function to parse input into groups separated by 'groupDelim', and
// interprete each group as a key/value pair separated by 'keyValueDelim'.
function parseOptions(input, callback, keyValueDelim, groupDelim) {
var groups = groupDelim ? input.split(groupDelim) : [input];
for (var i in groups) {
if (typeof groups[i] !== "string") {
continue;
}
var kv = groups[i].split(keyValueDelim);
if (kv.length !== 2) {
continue;
}
var k = kv[0];
var v = kv[1];
callback(k, v);
}
}
function parseCue(input, cue, regionList) {
// Remember the original input if we need to throw an error.
var oInput = input;
// 4.1 WebVTT timestamp
function consumeTimeStamp() {
var ts = parseTimeStamp(input);
if (ts === null) {
throw new ParsingError(ParsingError.Errors.BadTimeStamp,
"Malformed timestamp: " + oInput);
}
// Remove time stamp from input.
input = input.replace(/^[^\sa-zA-Z-]+/, "");
return ts;
}
// 4.4.2 WebVTT cue settings
function consumeCueSettings(input, cue) {
var settings = new Settings();
parseOptions(input, function (k, v) {
switch (k) {
case "region":
// Find the last region we parsed with the same region id.
for (var i = regionList.length - 1; i >= 0; i--) {
if (regionList[i].id === v) {
settings.set(k, regionList[i].region);
break;
}
}
break;
case "vertical":
settings.alt(k, v, ["rl", "lr"]);
break;
case "line":
var vals = v.split(","),
vals0 = vals[0];
settings.integer(k, vals0);
settings.percent(k, vals0) ? settings.set("snapToLines", false) : null;
settings.alt(k, vals0, ["auto"]);
if (vals.length === 2) {
settings.alt("lineAlign", vals[1], ["start", "middle", "end"]);
}
break;
case "position":
vals = v.split(",");
settings.percent(k, vals[0]);
if (vals.length === 2) {
settings.alt("positionAlign", vals[1], ["start", "middle", "end"]);
}
break;
case "size":
settings.percent(k, v);
break;
case "align":
settings.alt(k, v, ["start", "middle", "end", "left", "right"]);
break;
}
}, /:/, /\s/);
// Apply default values for any missing fields.
cue.region = settings.get("region", null);
cue.vertical = settings.get("vertical", "");
cue.line = settings.get("line", "auto");
cue.lineAlign = settings.get("lineAlign", "start");
cue.snapToLines = settings.get("snapToLines", true);
cue.size = settings.get("size", 100);
cue.align = settings.get("align", "middle");
cue.position = settings.get("position", "auto");
cue.positionAlign = settings.get("positionAlign", {
start: "start",
left: "start",
middle: "middle",
end: "end",
right: "end"
}, cue.align);
}
function skipWhitespace() {
input = input.replace(/^\s+/, "");
}
// 4.1 WebVTT cue timings.
skipWhitespace();
cue.startTime = consumeTimeStamp(); // (1) collect cue start time
skipWhitespace();
if (input.substr(0, 3) !== "-->") { // (3) next characters must match "-->"
throw new ParsingError(ParsingError.Errors.BadTimeStamp,
"Malformed time stamp (time stamps must be separated by '-->'): " +
oInput);
}
input = input.substr(3);
skipWhitespace();
cue.endTime = consumeTimeStamp(); // (5) collect cue end time
// 4.1 WebVTT cue settings list.
skipWhitespace();
consumeCueSettings(input, cue);
}
var ESCAPE = {
"&": "&",
"<": "<",
">": ">",
"‎": "\u200e",
"‏": "\u200f",
" ": "\u00a0"
};
var TAG_NAME = {
c: "span",
i: "i",
b: "b",
u: "u",
ruby: "ruby",
rt: "rt",
v: "span",
lang: "span"
};
var TAG_ANNOTATION = {
v: "title",
lang: "lang"
};
var NEEDS_PARENT = {
rt: "ruby"
};
// Parse content into a document fragment.
function parseContent(window, input) {
function nextToken() {
// Check for end-of-string.
if (!input) {
return null;
}
// Consume 'n' characters from the input.
function consume(result) {
input = input.substr(result.length);
return result;
}
var m = input.match(/^([^<]*)(<[^>]+>?)?/);
// If there is some text before the next tag, return it, otherwise return
// the tag.
return consume(m[1] ? m[1] : m[2]);
}
// Unescape a string 's'.
function unescape1(e) {
return ESCAPE[e];
}
function unescape(s) {
while ((m = s.match(/&(amp|lt|gt|lrm|rlm|nbsp);/))) {
s = s.replace(m[0], unescape1);
}
return s;
}
function shouldAdd(current, element) {
return !NEEDS_PARENT[element.localName] ||
NEEDS_PARENT[element.localName] === current.localName;
}
// Create an element for this tag.
function createElement(type, annotation) {
var tagName = TAG_NAME[type];
if (!tagName) {
return null;
}
var element = window.document.createElement(tagName);
element.localName = tagName;
var name = TAG_ANNOTATION[type];
if (name && annotation) {
element[name] = annotation.trim();
}
return element;
}
var rootDiv = window.document.createElement("div"),
current = rootDiv,
t,
tagStack = [];
while ((t = nextToken()) !== null) {
if (t[0] === '<') {
if (t[1] === "/") {
// If the closing tag matches, move back up to the parent node.
if (tagStack.length &&
tagStack[tagStack.length - 1] === t.substr(2).replace(">", "")) {
tagStack.pop();
current = current.parentNode;
}
// Otherwise just ignore the end tag.
continue;
}
var ts = parseTimeStamp(t.substr(1, t.length - 2));
var node;
if (ts) {
// Timestamps are lead nodes as well.
node = window.document.createProcessingInstruction("timestamp", ts);
current.appendChild(node);
continue;
}
var m = t.match(/^<([^.\s/0-9>]+)(\.[^\s\\>]+)?([^>\\]+)?(\\?)>?$/);
// If we can't parse the tag, skip to the next tag.
if (!m) {
continue;
}
// Try to construct an element, and ignore the tag if we couldn't.
node = createElement(m[1], m[3]);
if (!node) {
continue;
}
// Determine if the tag should be added based on the context of where it
// is placed in the cuetext.
if (!shouldAdd(current, node)) {
continue;
}
// Set the class list (as a list of classes, separated by space).
if (m[2]) {
node.className = m[2].substr(1).replace('.', ' ');
}
// Append the node to the current node, and enter the scope of the new
// node.
tagStack.push(m[1]);
current.appendChild(node);
current = node;
continue;
}
// Text nodes are leaf nodes.
current.appendChild(window.document.createTextNode(unescape(t)));
}
return rootDiv;
}
// This is a list of all the Unicode characters that have a strong
// right-to-left category. What this means is that these characters are
// written right-to-left for sure. It was generated by pulling all the strong
// right-to-left characters out of the Unicode data table. That table can
// found at: http://www.unicode.org/Public/UNIDATA/UnicodeData.txt
var strongRTLRanges = [[0x5be, 0x5be], [0x5c0, 0x5c0], [0x5c3, 0x5c3], [0x5c6, 0x5c6],
[0x5d0, 0x5ea], [0x5f0, 0x5f4], [0x608, 0x608], [0x60b, 0x60b], [0x60d, 0x60d],
[0x61b, 0x61b], [0x61e, 0x64a], [0x66d, 0x66f], [0x671, 0x6d5], [0x6e5, 0x6e6],
[0x6ee, 0x6ef], [0x6fa, 0x70d], [0x70f, 0x710], [0x712, 0x72f], [0x74d, 0x7a5],
[0x7b1, 0x7b1], [0x7c0, 0x7ea], [0x7f4, 0x7f5], [0x7fa, 0x7fa], [0x800, 0x815],
[0x81a, 0x81a], [0x824, 0x824], [0x828, 0x828], [0x830, 0x83e], [0x840, 0x858],
[0x85e, 0x85e], [0x8a0, 0x8a0], [0x8a2, 0x8ac], [0x200f, 0x200f],
[0xfb1d, 0xfb1d], [0xfb1f, 0xfb28], [0xfb2a, 0xfb36], [0xfb38, 0xfb3c],
[0xfb3e, 0xfb3e], [0xfb40, 0xfb41], [0xfb43, 0xfb44], [0xfb46, 0xfbc1],
[0xfbd3, 0xfd3d], [0xfd50, 0xfd8f], [0xfd92, 0xfdc7], [0xfdf0, 0xfdfc],
[0xfe70, 0xfe74], [0xfe76, 0xfefc], [0x10800, 0x10805], [0x10808, 0x10808],
[0x1080a, 0x10835], [0x10837, 0x10838], [0x1083c, 0x1083c], [0x1083f, 0x10855],
[0x10857, 0x1085f], [0x10900, 0x1091b], [0x10920, 0x10939], [0x1093f, 0x1093f],
[0x10980, 0x109b7], [0x109be, 0x109bf], [0x10a00, 0x10a00], [0x10a10, 0x10a13],
[0x10a15, 0x10a17], [0x10a19, 0x10a33], [0x10a40, 0x10a47], [0x10a50, 0x10a58],
[0x10a60, 0x10a7f], [0x10b00, 0x10b35], [0x10b40, 0x10b55], [0x10b58, 0x10b72],
[0x10b78, 0x10b7f], [0x10c00, 0x10c48], [0x1ee00, 0x1ee03], [0x1ee05, 0x1ee1f],
[0x1ee21, 0x1ee22], [0x1ee24, 0x1ee24], [0x1ee27, 0x1ee27], [0x1ee29, 0x1ee32],
[0x1ee34, 0x1ee37], [0x1ee39, 0x1ee39], [0x1ee3b, 0x1ee3b], [0x1ee42, 0x1ee42],
[0x1ee47, 0x1ee47], [0x1ee49, 0x1ee49], [0x1ee4b, 0x1ee4b], [0x1ee4d, 0x1ee4f],
[0x1ee51, 0x1ee52], [0x1ee54, 0x1ee54], [0x1ee57, 0x1ee57], [0x1ee59, 0x1ee59],
[0x1ee5b, 0x1ee5b], [0x1ee5d, 0x1ee5d], [0x1ee5f, 0x1ee5f], [0x1ee61, 0x1ee62],
[0x1ee64, 0x1ee64], [0x1ee67, 0x1ee6a], [0x1ee6c, 0x1ee72], [0x1ee74, 0x1ee77],
[0x1ee79, 0x1ee7c], [0x1ee7e, 0x1ee7e], [0x1ee80, 0x1ee89], [0x1ee8b, 0x1ee9b],
[0x1eea1, 0x1eea3], [0x1eea5, 0x1eea9], [0x1eeab, 0x1eebb], [0x10fffd, 0x10fffd]];
function isStrongRTLChar(charCode) {
for (var i = 0; i < strongRTLRanges.length; i++) {
var currentRange = strongRTLRanges[i];
if (charCode >= currentRange[0] && charCode <= currentRange[1]) {
return true;
}
}
return false;
}
function determineBidi(cueDiv) {
var nodeStack = [],
text = "",
charCode;
if (!cueDiv || !cueDiv.childNodes) {
return "ltr";
}
function pushNodes(nodeStack, node) {
for (var i = node.childNodes.length - 1; i >= 0; i--) {
nodeStack.push(node.childNodes[i]);
}
}
function nextTextNode(nodeStack) {
if (!nodeStack || !nodeStack.length) {
return null;
}
var node = nodeStack.pop(),
text = node.textContent || node.innerText;
if (text) {
// TODO: This should match all unicode type B characters (paragraph
// separator characters). See issue #115.
var m = text.match(/^.*(\n|\r)/);
if (m) {
nodeStack.length = 0;
return m[0];
}
return text;
}
if (node.tagName === "ruby") {
return nextTextNode(nodeStack);
}
if (node.childNodes) {
pushNodes(nodeStack, node);
return nextTextNode(nodeStack);
}
}
pushNodes(nodeStack, cueDiv);
while ((text = nextTextNode(nodeStack))) {
for (var i = 0; i < text.length; i++) {
charCode = text.charCodeAt(i);
if (isStrongRTLChar(charCode)) {
return "rtl";
}
}
}
return "ltr";
}
function computeLinePos(cue) {
if (typeof cue.line === "number" &&
(cue.snapToLines || (cue.line >= 0 && cue.line <= 100))) {
return cue.line;
}
if (!cue.track || !cue.track.textTrackList ||
!cue.track.textTrackList.mediaElement) {
return -1;
}
var track = cue.track,
trackList = track.textTrackList,
count = 0;
for (var i = 0; i < trackList.length && trackList[i] !== track; i++) {
if (trackList[i].mode === "showing") {
count++;
}
}
return ++count * -1;
}
function StyleBox() {
}
// Apply styles to a div. If there is no div passed then it defaults to the
// div on 'this'.
StyleBox.prototype.applyStyles = function(styles, div) {
div = div || this.div;
for (var prop in styles) {
if (styles.hasOwnProperty(prop)) {
div.style[prop] = styles[prop];
}
}
};
StyleBox.prototype.formatStyle = function(val, unit) {
return val === 0 ? 0 : val + unit;
};
// Constructs the computed display state of the cue (a div). Places the div
// into the overlay which should be a block level element (usually a div).
function CueStyleBox(window, cue, styleOptions) {
var isIE8 = (typeof navigator !== "undefined") &&
(/MSIE\s8\.0/).test(navigator.userAgent);
var color = "rgba(255, 255, 255, 1)";
var backgroundColor = "rgba(0, 0, 0, 0.8)";
var textShadow = "";
if(typeof WebVTTSet !== "undefined") {
color = WebVTTSet.fontSet;
backgroundColor = WebVTTSet.backgroundSet;
textShadow = WebVTTSet.edgeSet;
}
if (isIE8) {
color = "rgb(255, 255, 255)";
backgroundColor = "rgb(0, 0, 0)";
}
StyleBox.call(this);
this.cue = cue;
// Parse our cue's text into a DOM tree rooted at 'cueDiv'. This div will
// have inline positioning and will function as the cue background box.
this.cueDiv = parseContent(window, cue.text);
var styles = {
color: color,
backgroundColor: backgroundColor,
textShadow: textShadow,
position: "relative",
left: 0,
right: 0,
top: 0,
bottom: 0,
display: "inline"
};
if (!isIE8) {
styles.writingMode = cue.vertical === "" ? "horizontal-tb"
: cue.vertical === "lr" ? "vertical-lr"
: "vertical-rl";
styles.unicodeBidi = "plaintext";
}
this.applyStyles(styles, this.cueDiv);
// Create an absolutely positioned div that will be used to position the cue
// div. Note, all WebVTT cue-setting alignments are equivalent to the CSS
// mirrors of them except "middle" which is "center" in CSS.
this.div = window.document.createElement("div");
styles = {
textAlign: cue.align === "middle" ? "center" : cue.align,
font: styleOptions.font,
whiteSpace: "pre-line",
position: "absolute"
};
if (!isIE8) {
styles.direction = determineBidi(this.cueDiv);
styles.writingMode = cue.vertical === "" ? "horizontal-tb"
: cue.vertical === "lr" ? "vertical-lr"
: "vertical-rl".
stylesunicodeBidi = "plaintext";
}
this.applyStyles(styles);
this.div.appendChild(this.cueDiv);
// Calculate the distance from the reference edge of the viewport to the text
// position of the cue box. The reference edge will be resolved later when
// the box orientation styles are applied.
var textPos = 0;
switch (cue.positionAlign) {
case "start":
textPos = cue.position;
break;
case "middle":
textPos = cue.position - (cue.size / 2);
break;
case "end":
textPos = cue.position - cue.size;
break;
}
// Horizontal box orientation; textPos is the distance from the left edge of the
// area to the left edge of the box and cue.size is the distance extending to
// the right from there.
if (cue.vertical === "") {
this.applyStyles({
left: this.formatStyle(textPos, "%"),
width: this.formatStyle(cue.size, "%")
});
// Vertical box orientation; textPos is the distance from the top edge of the
// area to the top edge of the box and cue.size is the height extending
// downwards from there.
} else {
this.applyStyles({
top: this.formatStyle(textPos, "%"),
height: this.formatStyle(cue.size, "%")
});
}
this.move = function(box) {
this.applyStyles({
top: this.formatStyle(box.top, "px"),
bottom: this.formatStyle(box.bottom, "px"),
left: this.formatStyle(box.left, "px"),
right: this.formatStyle(box.right, "px"),
height: this.formatStyle(box.height, "px"),
width: this.formatStyle(box.width, "px")
});
};
}
CueStyleBox.prototype = _objCreate(StyleBox.prototype);
CueStyleBox.prototype.constructor = CueStyleBox;
// Represents the co-ordinates of an Element in a way that we can easily
// compute things with such as if it overlaps or intersects with another Element.
// Can initialize it with either a StyleBox or another BoxPosition.
function BoxPosition(obj) {
var isIE8 = (typeof navigator !== "undefined") &&
(/MSIE\s8\.0/).test(navigator.userAgent);
// Either a BoxPosition was passed in and we need to copy it, or a StyleBox
// was passed in and we need to copy the results of 'getBoundingClientRect'
// as the object returned is readonly. All co-ordinate values are in reference
// to the viewport origin (top left).
var lh, height, width, top;
if (obj.div) {
height = obj.div.offsetHeight;
width = obj.div.offsetWidth;
top = obj.div.offsetTop;
var rects = (rects = obj.div.childNodes) && (rects = rects[0]) &&
rects.getClientRects && rects.getClientRects();
obj = obj.div.getBoundingClientRect();
// In certain cases the outter div will be slightly larger then the sum of
// the inner div's lines. This could be due to bold text, etc, on some platforms.
// In this case we should get the average line height and use that. This will
// result in the desired behaviour.
lh = rects ? Math.max((rects[0] && rects[0].height) || 0, obj.height / rects.length)
: 0;
}
this.left = obj.left;
this.right = obj.right;
this.top = obj.top || top;
this.height = obj.height || height;
this.bottom = obj.bottom || (top + (obj.height || height));
this.width = obj.width || width;
this.lineHeight = lh !== undefined ? lh : obj.lineHeight;
if (isIE8 && !this.lineHeight) {
this.lineHeight = 13;
}
}
// Move the box along a particular axis. Optionally pass in an amount to move
// the box. If no amount is passed then the default is the line height of the
// box.
BoxPosition.prototype.move = function(axis, toMove) {
toMove = toMove !== undefined ? toMove : this.lineHeight;
switch (axis) {
case "+x":
this.left += toMove;
this.right += toMove;
break;
case "-x":
this.left -= toMove;
this.right -= toMove;
break;
case "+y":
this.top += toMove;
this.bottom += toMove;
break;
case "-y":
this.top -= toMove;
this.bottom -= toMove;
break;
}
};
// Check if this box overlaps another box, b2.
BoxPosition.prototype.overlaps = function(b2) {
return this.left < b2.right &&
this.right > b2.left &&
this.top < b2.bottom &&
this.bottom > b2.top;
};
// Check if this box overlaps any other boxes in boxes.
BoxPosition.prototype.overlapsAny = function(boxes) {
for (var i = 0; i < boxes.length; i++) {
if (this.overlaps(boxes[i])) {
return true;
}
}
return false;
};
// Check if this box is within another box.
BoxPosition.prototype.within = function(container) {
return this.top >= container.top &&
this.bottom <= container.bottom &&
this.left >= container.left &&
this.right <= container.right;
};
// Check if this box is entirely within the container or it is overlapping
// on the edge opposite of the axis direction passed. For example, if "+x" is
// passed and the box is overlapping on the left edge of the container, then
// return true.
BoxPosition.prototype.overlapsOppositeAxis = function(container, axis) {
switch (axis) {
case "+x":
return this.left < container.left;
case "-x":
return this.right > container.right;
case "+y":
return this.top < container.top;
case "-y":
return this.bottom > container.bottom;
}
};
// Find the percentage of the area that this box is overlapping with another
// box.
BoxPosition.prototype.intersectPercentage = function(b2) {
var x = Math.max(0, Math.min(this.right, b2.right) - Math.max(this.left, b2.left)),
y = Math.max(0, Math.min(this.bottom, b2.bottom) - Math.max(this.top, b2.top)),
intersectArea = x * y;
return intersectArea / (this.height * this.width);
};
// Convert the positions from this box to CSS compatible positions using
// the reference container's positions. This has to be done because this
// box's positions are in reference to the viewport origin, whereas, CSS
// values are in referecne to their respective edges.
BoxPosition.prototype.toCSSCompatValues = function(reference) {
return {
top: this.top - reference.top,
bottom: reference.bottom - this.bottom,
left: this.left - reference.left,
right: reference.right - this.right,
height: this.height,
width: this.width
};
};
// Get an object that represents the box's position without anything extra.
// Can pass a StyleBox, HTMLElement, or another BoxPositon.
BoxPosition.getSimpleBoxPosition = function(obj) {
var height = obj.div ? obj.div.offsetHeight : obj.tagName ? obj.offsetHeight : 0;
var width = obj.div ? obj.div.offsetWidth : obj.tagName ? obj.offsetWidth : 0;
var top = obj.div ? obj.div.offsetTop : obj.tagName ? obj.offsetTop : 0;
obj = obj.div ? obj.div.getBoundingClientRect() :
obj.tagName ? obj.getBoundingClientRect() : obj;
var ret = {
left: obj.left,
right: obj.right,
top: obj.top || top,
height: obj.height || height,
bottom: obj.bottom || (top + (obj.height || height)),
width: obj.width || width
};
return ret;
};
// Move a StyleBox to its specified, or next best, position. The containerBox
// is the box that contains the StyleBox, such as a div. boxPositions are
// a list of other boxes that the styleBox can't overlap with.
function moveBoxToLinePosition(window, styleBox, containerBox, boxPositions) {
// Find the best position for a cue box, b, on the video. The axis parameter
// is a list of axis, the order of which, it will move the box along. For example:
// Passing ["+x", "-x"] will move the box first along the x axis in the positive
// direction. If it doesn't find a good position for it there it will then move
// it along the x axis in the negative direction.
function findBestPosition(b, axis) {
var bestPosition,
specifiedPosition = new BoxPosition(b),
percentage = 1; // Highest possible so the first thing we get is better.
for (var i = 0; i < axis.length; i++) {
while (b.overlapsOppositeAxis(containerBox, axis[i]) ||
(b.within(containerBox) && b.overlapsAny(boxPositions))) {
b.move(axis[i]);
}
// We found a spot where we aren't overlapping anything. This is our
// best position.
if (b.within(containerBox)) {
return b;
}
var p = b.intersectPercentage(containerBox);
// If we're outside the container box less then we were on our last try
// then remember this position as the best position.
if (percentage > p) {
bestPosition = new BoxPosition(b);
percentage = p;
}
// Reset the box position to the specified position.
b = new BoxPosition(specifiedPosition);
}
return bestPosition || specifiedPosition;
}
var boxPosition = new BoxPosition(styleBox),
cue = styleBox.cue,
linePos = computeLinePos(cue),
axis = [];
// If we have a line number to align the cue to.
if (cue.snapToLines) {
var size;
switch (cue.vertical) {
case "":
axis = [ "+y", "-y" ];
size = "height";
break;
case "rl":
axis = [ "+x", "-x" ];
size = "width";
break;
case "lr":
axis = [ "-x", "+x" ];
size = "width";
break;
}
var step = boxPosition.lineHeight,
position = step * Math.round(linePos),
maxPosition = containerBox[size] + step,
initialAxis = axis[0];
// If the specified intial position is greater then the max position then
// clamp the box to the amount of steps it would take for the box to
// reach the max position.
if (Math.abs(position) > maxPosition) {
position = position < 0 ? -1 : 1;
position *= Math.ceil(maxPosition / step) * step;
}
// If computed line position returns negative then line numbers are
// relative to the bottom of the video instead of the top. Therefore, we
// need to increase our initial position by the length or width of the
// video, depending on the writing direction, and reverse our axis directions.
if (linePos < 0) {
position += cue.vertical === "" ? containerBox.height : containerBox.width;
axis = axis.reverse();
}
// Move the box to the specified position. This may not be its best
// position.
boxPosition.move(initialAxis, position);
} else {
// If we have a percentage line value for the cue.
var calculatedPercentage = (boxPosition.lineHeight / containerBox.height) * 100;
switch (cue.lineAlign) {
case "middle":
linePos -= (calculatedPercentage / 2);
break;
case "end":
linePos -= calculatedPercentage;
break;
}
// Apply initial line position to the cue box.
switch (cue.vertical) {
case "":
styleBox.applyStyles({
top: styleBox.formatStyle(linePos, "%")
});
break;
case "rl":
styleBox.applyStyles({
left: styleBox.formatStyle(linePos, "%")
});
break;
case "lr":
styleBox.applyStyles({
right: styleBox.formatStyle(linePos, "%")
});
break;
}
axis = [ "+y", "-x", "+x", "-y" ];
// Get the box position again after we've applied the specified positioning
// to it.
boxPosition = new BoxPosition(styleBox);
}
var bestPosition = findBestPosition(boxPosition, axis);
styleBox.move(bestPosition.toCSSCompatValues(containerBox));
}
function WebVTT() {
// Nothing
}
// Helper to allow strings to be decoded instead of the default binary utf8 data.
WebVTT.StringDecoder = function() {
return {
decode: function(data) {
if (!data) {
return "";
}
if (typeof data !== "string") {
throw new Error("Error - expected string data.");
}
return decodeURIComponent(encodeURIComponent(data));
}
};
};
WebVTT.convertCueToDOMTree = function(window, cuetext) {
if (!window || !cuetext) {
return null;
}