vtt.js 55 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870
  1. (function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.vttjs = f()}})(function(){var define,module,exports;return (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){
  2. /**
  3. * Copyright 2013 vtt.js Contributors
  4. *
  5. * Licensed under the Apache License, Version 2.0 (the "License");
  6. * you may not use this file except in compliance with the License.
  7. * You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. */
  17. /* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
  18. /* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */
  19. var document = require('global/document');
  20. var _objCreate = Object.create || (function() {
  21. function F() {}
  22. return function(o) {
  23. if (arguments.length !== 1) {
  24. throw new Error('Object.create shim only accepts one parameter.');
  25. }
  26. F.prototype = o;
  27. return new F();
  28. };
  29. })();
  30. // Creates a new ParserError object from an errorData object. The errorData
  31. // object should have default code and message properties. The default message
  32. // property can be overriden by passing in a message parameter.
  33. // See ParsingError.Errors below for acceptable errors.
  34. function ParsingError(errorData, message) {
  35. this.name = "ParsingError";
  36. this.code = errorData.code;
  37. this.message = message || errorData.message;
  38. }
  39. ParsingError.prototype = _objCreate(Error.prototype);
  40. ParsingError.prototype.constructor = ParsingError;
  41. // ParsingError metadata for acceptable ParsingErrors.
  42. ParsingError.Errors = {
  43. BadSignature: {
  44. code: 0,
  45. message: "Malformed WebVTT signature."
  46. },
  47. BadTimeStamp: {
  48. code: 1,
  49. message: "Malformed time stamp."
  50. }
  51. };
  52. // Try to parse input as a time stamp.
  53. function parseTimeStamp(input) {
  54. function computeSeconds(h, m, s, f) {
  55. return (h | 0) * 3600 + (m | 0) * 60 + (s | 0) + (f | 0) / 1000;
  56. }
  57. var m = input.match(/^(\d+):(\d{1,2})(:\d{1,2})?\.(\d{3})/);
  58. if (!m) {
  59. return null;
  60. }
  61. if (m[3]) {
  62. // Timestamp takes the form of [hours]:[minutes]:[seconds].[milliseconds]
  63. return computeSeconds(m[1], m[2], m[3].replace(":", ""), m[4]);
  64. } else if (m[1] > 59) {
  65. // Timestamp takes the form of [hours]:[minutes].[milliseconds]
  66. // First position is hours as it's over 59.
  67. return computeSeconds(m[1], m[2], 0, m[4]);
  68. } else {
  69. // Timestamp takes the form of [minutes]:[seconds].[milliseconds]
  70. return computeSeconds(0, m[1], m[2], m[4]);
  71. }
  72. }
  73. // A settings object holds key/value pairs and will ignore anything but the first
  74. // assignment to a specific key.
  75. function Settings() {
  76. this.values = _objCreate(null);
  77. }
  78. Settings.prototype = {
  79. // Only accept the first assignment to any key.
  80. set: function(k, v) {
  81. if (!this.get(k) && v !== "") {
  82. this.values[k] = v;
  83. }
  84. },
  85. // Return the value for a key, or a default value.
  86. // If 'defaultKey' is passed then 'dflt' is assumed to be an object with
  87. // a number of possible default values as properties where 'defaultKey' is
  88. // the key of the property that will be chosen; otherwise it's assumed to be
  89. // a single value.
  90. get: function(k, dflt, defaultKey) {
  91. if (defaultKey) {
  92. return this.has(k) ? this.values[k] : dflt[defaultKey];
  93. }
  94. return this.has(k) ? this.values[k] : dflt;
  95. },
  96. // Check whether we have a value for a key.
  97. has: function(k) {
  98. return k in this.values;
  99. },
  100. // Accept a setting if its one of the given alternatives.
  101. alt: function(k, v, a) {
  102. for (var n = 0; n < a.length; ++n) {
  103. if (v === a[n]) {
  104. this.set(k, v);
  105. break;
  106. }
  107. }
  108. },
  109. // Accept a setting if its a valid (signed) integer.
  110. integer: function(k, v) {
  111. if (/^-?\d+$/.test(v)) { // integer
  112. this.set(k, parseInt(v, 10));
  113. }
  114. },
  115. // Accept a setting if its a valid percentage.
  116. percent: function(k, v) {
  117. var m;
  118. if ((m = v.match(/^([\d]{1,3})(\.[\d]*)?%$/))) {
  119. v = parseFloat(v);
  120. if (v >= 0 && v <= 100) {
  121. this.set(k, v);
  122. return true;
  123. }
  124. }
  125. return false;
  126. }
  127. };
  128. // Helper function to parse input into groups separated by 'groupDelim', and
  129. // interprete each group as a key/value pair separated by 'keyValueDelim'.
  130. function parseOptions(input, callback, keyValueDelim, groupDelim) {
  131. var groups = groupDelim ? input.split(groupDelim) : [input];
  132. for (var i in groups) {
  133. if (typeof groups[i] !== "string") {
  134. continue;
  135. }
  136. var kv = groups[i].split(keyValueDelim);
  137. if (kv.length !== 2) {
  138. continue;
  139. }
  140. var k = kv[0].trim();
  141. var v = kv[1].trim();
  142. callback(k, v);
  143. }
  144. }
  145. function parseCue(input, cue, regionList) {
  146. // Remember the original input if we need to throw an error.
  147. var oInput = input;
  148. // 4.1 WebVTT timestamp
  149. function consumeTimeStamp() {
  150. var ts = parseTimeStamp(input);
  151. if (ts === null) {
  152. throw new ParsingError(ParsingError.Errors.BadTimeStamp,
  153. "Malformed timestamp: " + oInput);
  154. }
  155. // Remove time stamp from input.
  156. input = input.replace(/^[^\sa-zA-Z-]+/, "");
  157. return ts;
  158. }
  159. // 4.4.2 WebVTT cue settings
  160. function consumeCueSettings(input, cue) {
  161. var settings = new Settings();
  162. parseOptions(input, function (k, v) {
  163. switch (k) {
  164. case "region":
  165. // Find the last region we parsed with the same region id.
  166. for (var i = regionList.length - 1; i >= 0; i--) {
  167. if (regionList[i].id === v) {
  168. settings.set(k, regionList[i].region);
  169. break;
  170. }
  171. }
  172. break;
  173. case "vertical":
  174. settings.alt(k, v, ["rl", "lr"]);
  175. break;
  176. case "line":
  177. var vals = v.split(","),
  178. vals0 = vals[0];
  179. settings.integer(k, vals0);
  180. settings.percent(k, vals0) ? settings.set("snapToLines", false) : null;
  181. settings.alt(k, vals0, ["auto"]);
  182. if (vals.length === 2) {
  183. settings.alt("lineAlign", vals[1], ["start", "center", "end"]);
  184. }
  185. break;
  186. case "position":
  187. vals = v.split(",");
  188. settings.percent(k, vals[0]);
  189. if (vals.length === 2) {
  190. settings.alt("positionAlign", vals[1], ["start", "center", "end"]);
  191. }
  192. break;
  193. case "size":
  194. settings.percent(k, v);
  195. break;
  196. case "align":
  197. settings.alt(k, v, ["start", "center", "end", "left", "right"]);
  198. break;
  199. }
  200. }, /:/, /\s/);
  201. // Apply default values for any missing fields.
  202. cue.region = settings.get("region", null);
  203. cue.vertical = settings.get("vertical", "");
  204. try {
  205. cue.line = settings.get("line", "auto");
  206. } catch (e) {}
  207. cue.lineAlign = settings.get("lineAlign", "start");
  208. cue.snapToLines = settings.get("snapToLines", true);
  209. cue.size = settings.get("size", 100);
  210. // Safari still uses the old middle value and won't accept center
  211. try {
  212. cue.align = settings.get("align", "center");
  213. } catch (e) {
  214. cue.align = settings.get("align", "middle");
  215. }
  216. try {
  217. cue.position = settings.get("position", "auto");
  218. } catch (e) {
  219. cue.position = settings.get("position", {
  220. start: 0,
  221. left: 0,
  222. center: 50,
  223. middle: 50,
  224. end: 100,
  225. right: 100
  226. }, cue.align);
  227. }
  228. cue.positionAlign = settings.get("positionAlign", {
  229. start: "start",
  230. left: "start",
  231. center: "center",
  232. middle: "center",
  233. end: "end",
  234. right: "end"
  235. }, cue.align);
  236. }
  237. function skipWhitespace() {
  238. input = input.replace(/^\s+/, "");
  239. }
  240. // 4.1 WebVTT cue timings.
  241. skipWhitespace();
  242. cue.startTime = consumeTimeStamp(); // (1) collect cue start time
  243. skipWhitespace();
  244. if (input.substr(0, 3) !== "-->") { // (3) next characters must match "-->"
  245. throw new ParsingError(ParsingError.Errors.BadTimeStamp,
  246. "Malformed time stamp (time stamps must be separated by '-->'): " +
  247. oInput);
  248. }
  249. input = input.substr(3);
  250. skipWhitespace();
  251. cue.endTime = consumeTimeStamp(); // (5) collect cue end time
  252. // 4.1 WebVTT cue settings list.
  253. skipWhitespace();
  254. consumeCueSettings(input, cue);
  255. }
  256. // When evaluating this file as part of a Webpack bundle for server
  257. // side rendering, `document` is an empty object.
  258. var TEXTAREA_ELEMENT = document.createElement && document.createElement("textarea");
  259. var TAG_NAME = {
  260. c: "span",
  261. i: "i",
  262. b: "b",
  263. u: "u",
  264. ruby: "ruby",
  265. rt: "rt",
  266. v: "span",
  267. lang: "span"
  268. };
  269. // 5.1 default text color
  270. // 5.2 default text background color is equivalent to text color with bg_ prefix
  271. var DEFAULT_COLOR_CLASS = {
  272. white: 'rgba(255,255,255,1)',
  273. lime: 'rgba(0,255,0,1)',
  274. cyan: 'rgba(0,255,255,1)',
  275. red: 'rgba(255,0,0,1)',
  276. yellow: 'rgba(255,255,0,1)',
  277. magenta: 'rgba(255,0,255,1)',
  278. blue: 'rgba(0,0,255,1)',
  279. black: 'rgba(0,0,0,1)'
  280. };
  281. var TAG_ANNOTATION = {
  282. v: "title",
  283. lang: "lang"
  284. };
  285. var NEEDS_PARENT = {
  286. rt: "ruby"
  287. };
  288. // Parse content into a document fragment.
  289. function parseContent(window, input) {
  290. function nextToken() {
  291. // Check for end-of-string.
  292. if (!input) {
  293. return null;
  294. }
  295. // Consume 'n' characters from the input.
  296. function consume(result) {
  297. input = input.substr(result.length);
  298. return result;
  299. }
  300. var m = input.match(/^([^<]*)(<[^>]*>?)?/);
  301. // If there is some text before the next tag, return it, otherwise return
  302. // the tag.
  303. return consume(m[1] ? m[1] : m[2]);
  304. }
  305. function unescape(s) {
  306. TEXTAREA_ELEMENT.innerHTML = s;
  307. s = TEXTAREA_ELEMENT.textContent;
  308. TEXTAREA_ELEMENT.textContent = "";
  309. return s;
  310. }
  311. function shouldAdd(current, element) {
  312. return !NEEDS_PARENT[element.localName] ||
  313. NEEDS_PARENT[element.localName] === current.localName;
  314. }
  315. // Create an element for this tag.
  316. function createElement(type, annotation) {
  317. var tagName = TAG_NAME[type];
  318. if (!tagName) {
  319. return null;
  320. }
  321. var element = window.document.createElement(tagName);
  322. var name = TAG_ANNOTATION[type];
  323. if (name && annotation) {
  324. element[name] = annotation.trim();
  325. }
  326. return element;
  327. }
  328. var rootDiv = window.document.createElement("div"),
  329. current = rootDiv,
  330. t,
  331. tagStack = [];
  332. while ((t = nextToken()) !== null) {
  333. if (t[0] === '<') {
  334. if (t[1] === "/") {
  335. // If the closing tag matches, move back up to the parent node.
  336. if (tagStack.length &&
  337. tagStack[tagStack.length - 1] === t.substr(2).replace(">", "")) {
  338. tagStack.pop();
  339. current = current.parentNode;
  340. }
  341. // Otherwise just ignore the end tag.
  342. continue;
  343. }
  344. var ts = parseTimeStamp(t.substr(1, t.length - 2));
  345. var node;
  346. if (ts) {
  347. // Timestamps are lead nodes as well.
  348. node = window.document.createProcessingInstruction("timestamp", ts);
  349. current.appendChild(node);
  350. continue;
  351. }
  352. var m = t.match(/^<([^.\s/0-9>]+)(\.[^\s\\>]+)?([^>\\]+)?(\\?)>?$/);
  353. // If we can't parse the tag, skip to the next tag.
  354. if (!m) {
  355. continue;
  356. }
  357. // Try to construct an element, and ignore the tag if we couldn't.
  358. node = createElement(m[1], m[3]);
  359. if (!node) {
  360. continue;
  361. }
  362. // Determine if the tag should be added based on the context of where it
  363. // is placed in the cuetext.
  364. if (!shouldAdd(current, node)) {
  365. continue;
  366. }
  367. // Set the class list (as a list of classes, separated by space).
  368. if (m[2]) {
  369. var classes = m[2].split('.');
  370. classes.forEach(function(cl) {
  371. var bgColor = /^bg_/.test(cl);
  372. // slice out `bg_` if it's a background color
  373. var colorName = bgColor ? cl.slice(3) : cl;
  374. if (DEFAULT_COLOR_CLASS.hasOwnProperty(colorName)) {
  375. var propName = bgColor ? 'background-color' : 'color';
  376. var propValue = DEFAULT_COLOR_CLASS[colorName];
  377. node.style[propName] = propValue;
  378. }
  379. });
  380. node.className = classes.join(' ');
  381. }
  382. // Append the node to the current node, and enter the scope of the new
  383. // node.
  384. tagStack.push(m[1]);
  385. current.appendChild(node);
  386. current = node;
  387. continue;
  388. }
  389. // Text nodes are leaf nodes.
  390. current.appendChild(window.document.createTextNode(unescape(t)));
  391. }
  392. return rootDiv;
  393. }
  394. // This is a list of all the Unicode characters that have a strong
  395. // right-to-left category. What this means is that these characters are
  396. // written right-to-left for sure. It was generated by pulling all the strong
  397. // right-to-left characters out of the Unicode data table. That table can
  398. // found at: http://www.unicode.org/Public/UNIDATA/UnicodeData.txt
  399. var strongRTLRanges = [[0x5be, 0x5be], [0x5c0, 0x5c0], [0x5c3, 0x5c3], [0x5c6, 0x5c6],
  400. [0x5d0, 0x5ea], [0x5f0, 0x5f4], [0x608, 0x608], [0x60b, 0x60b], [0x60d, 0x60d],
  401. [0x61b, 0x61b], [0x61e, 0x64a], [0x66d, 0x66f], [0x671, 0x6d5], [0x6e5, 0x6e6],
  402. [0x6ee, 0x6ef], [0x6fa, 0x70d], [0x70f, 0x710], [0x712, 0x72f], [0x74d, 0x7a5],
  403. [0x7b1, 0x7b1], [0x7c0, 0x7ea], [0x7f4, 0x7f5], [0x7fa, 0x7fa], [0x800, 0x815],
  404. [0x81a, 0x81a], [0x824, 0x824], [0x828, 0x828], [0x830, 0x83e], [0x840, 0x858],
  405. [0x85e, 0x85e], [0x8a0, 0x8a0], [0x8a2, 0x8ac], [0x200f, 0x200f],
  406. [0xfb1d, 0xfb1d], [0xfb1f, 0xfb28], [0xfb2a, 0xfb36], [0xfb38, 0xfb3c],
  407. [0xfb3e, 0xfb3e], [0xfb40, 0xfb41], [0xfb43, 0xfb44], [0xfb46, 0xfbc1],
  408. [0xfbd3, 0xfd3d], [0xfd50, 0xfd8f], [0xfd92, 0xfdc7], [0xfdf0, 0xfdfc],
  409. [0xfe70, 0xfe74], [0xfe76, 0xfefc], [0x10800, 0x10805], [0x10808, 0x10808],
  410. [0x1080a, 0x10835], [0x10837, 0x10838], [0x1083c, 0x1083c], [0x1083f, 0x10855],
  411. [0x10857, 0x1085f], [0x10900, 0x1091b], [0x10920, 0x10939], [0x1093f, 0x1093f],
  412. [0x10980, 0x109b7], [0x109be, 0x109bf], [0x10a00, 0x10a00], [0x10a10, 0x10a13],
  413. [0x10a15, 0x10a17], [0x10a19, 0x10a33], [0x10a40, 0x10a47], [0x10a50, 0x10a58],
  414. [0x10a60, 0x10a7f], [0x10b00, 0x10b35], [0x10b40, 0x10b55], [0x10b58, 0x10b72],
  415. [0x10b78, 0x10b7f], [0x10c00, 0x10c48], [0x1ee00, 0x1ee03], [0x1ee05, 0x1ee1f],
  416. [0x1ee21, 0x1ee22], [0x1ee24, 0x1ee24], [0x1ee27, 0x1ee27], [0x1ee29, 0x1ee32],
  417. [0x1ee34, 0x1ee37], [0x1ee39, 0x1ee39], [0x1ee3b, 0x1ee3b], [0x1ee42, 0x1ee42],
  418. [0x1ee47, 0x1ee47], [0x1ee49, 0x1ee49], [0x1ee4b, 0x1ee4b], [0x1ee4d, 0x1ee4f],
  419. [0x1ee51, 0x1ee52], [0x1ee54, 0x1ee54], [0x1ee57, 0x1ee57], [0x1ee59, 0x1ee59],
  420. [0x1ee5b, 0x1ee5b], [0x1ee5d, 0x1ee5d], [0x1ee5f, 0x1ee5f], [0x1ee61, 0x1ee62],
  421. [0x1ee64, 0x1ee64], [0x1ee67, 0x1ee6a], [0x1ee6c, 0x1ee72], [0x1ee74, 0x1ee77],
  422. [0x1ee79, 0x1ee7c], [0x1ee7e, 0x1ee7e], [0x1ee80, 0x1ee89], [0x1ee8b, 0x1ee9b],
  423. [0x1eea1, 0x1eea3], [0x1eea5, 0x1eea9], [0x1eeab, 0x1eebb], [0x10fffd, 0x10fffd]];
  424. function isStrongRTLChar(charCode) {
  425. for (var i = 0; i < strongRTLRanges.length; i++) {
  426. var currentRange = strongRTLRanges[i];
  427. if (charCode >= currentRange[0] && charCode <= currentRange[1]) {
  428. return true;
  429. }
  430. }
  431. return false;
  432. }
  433. function determineBidi(cueDiv) {
  434. var nodeStack = [],
  435. text = "",
  436. charCode;
  437. if (!cueDiv || !cueDiv.childNodes) {
  438. return "ltr";
  439. }
  440. function pushNodes(nodeStack, node) {
  441. for (var i = node.childNodes.length - 1; i >= 0; i--) {
  442. nodeStack.push(node.childNodes[i]);
  443. }
  444. }
  445. function nextTextNode(nodeStack) {
  446. if (!nodeStack || !nodeStack.length) {
  447. return null;
  448. }
  449. var node = nodeStack.pop(),
  450. text = node.textContent || node.innerText;
  451. if (text) {
  452. // TODO: This should match all unicode type B characters (paragraph
  453. // separator characters). See issue #115.
  454. var m = text.match(/^.*(\n|\r)/);
  455. if (m) {
  456. nodeStack.length = 0;
  457. return m[0];
  458. }
  459. return text;
  460. }
  461. if (node.tagName === "ruby") {
  462. return nextTextNode(nodeStack);
  463. }
  464. if (node.childNodes) {
  465. pushNodes(nodeStack, node);
  466. return nextTextNode(nodeStack);
  467. }
  468. }
  469. pushNodes(nodeStack, cueDiv);
  470. while ((text = nextTextNode(nodeStack))) {
  471. for (var i = 0; i < text.length; i++) {
  472. charCode = text.charCodeAt(i);
  473. if (isStrongRTLChar(charCode)) {
  474. return "rtl";
  475. }
  476. }
  477. }
  478. return "ltr";
  479. }
  480. function computeLinePos(cue) {
  481. if (typeof cue.line === "number" &&
  482. (cue.snapToLines || (cue.line >= 0 && cue.line <= 100))) {
  483. return cue.line;
  484. }
  485. if (!cue.track || !cue.track.textTrackList ||
  486. !cue.track.textTrackList.mediaElement) {
  487. return -1;
  488. }
  489. var track = cue.track,
  490. trackList = track.textTrackList,
  491. count = 0;
  492. for (var i = 0; i < trackList.length && trackList[i] !== track; i++) {
  493. if (trackList[i].mode === "showing") {
  494. count++;
  495. }
  496. }
  497. return ++count * -1;
  498. }
  499. function StyleBox() {
  500. }
  501. // Apply styles to a div. If there is no div passed then it defaults to the
  502. // div on 'this'.
  503. StyleBox.prototype.applyStyles = function(styles, div) {
  504. div = div || this.div;
  505. for (var prop in styles) {
  506. if (styles.hasOwnProperty(prop)) {
  507. div.style[prop] = styles[prop];
  508. }
  509. }
  510. };
  511. StyleBox.prototype.formatStyle = function(val, unit) {
  512. return val === 0 ? 0 : val + unit;
  513. };
  514. // Constructs the computed display state of the cue (a div). Places the div
  515. // into the overlay which should be a block level element (usually a div).
  516. function CueStyleBox(window, cue, styleOptions) {
  517. StyleBox.call(this);
  518. this.cue = cue;
  519. // Parse our cue's text into a DOM tree rooted at 'cueDiv'. This div will
  520. // have inline positioning and will function as the cue background box.
  521. this.cueDiv = parseContent(window, cue.text);
  522. var styles = {
  523. color: "rgba(255, 255, 255, 1)",
  524. backgroundColor: "rgba(0, 0, 0, 0.8)",
  525. position: "relative",
  526. left: 0,
  527. right: 0,
  528. top: 0,
  529. bottom: 0,
  530. display: "inline",
  531. writingMode: cue.vertical === "" ? "horizontal-tb"
  532. : cue.vertical === "lr" ? "vertical-lr"
  533. : "vertical-rl",
  534. unicodeBidi: "plaintext"
  535. };
  536. this.applyStyles(styles, this.cueDiv);
  537. // Create an absolutely positioned div that will be used to position the cue
  538. // div. Note, all WebVTT cue-setting alignments are equivalent to the CSS
  539. // mirrors of them except middle instead of center on Safari.
  540. this.div = window.document.createElement("div");
  541. styles = {
  542. direction: determineBidi(this.cueDiv),
  543. writingMode: cue.vertical === "" ? "horizontal-tb"
  544. : cue.vertical === "lr" ? "vertical-lr"
  545. : "vertical-rl",
  546. unicodeBidi: "plaintext",
  547. textAlign: cue.align === "middle" ? "center" : cue.align,
  548. font: styleOptions.font,
  549. whiteSpace: "pre-line",
  550. position: "absolute"
  551. };
  552. this.applyStyles(styles);
  553. this.div.appendChild(this.cueDiv);
  554. // Calculate the distance from the reference edge of the viewport to the text
  555. // position of the cue box. The reference edge will be resolved later when
  556. // the box orientation styles are applied.
  557. var textPos = 0;
  558. switch (cue.positionAlign) {
  559. case "start":
  560. textPos = cue.position;
  561. break;
  562. case "center":
  563. textPos = cue.position - (cue.size / 2);
  564. break;
  565. case "end":
  566. textPos = cue.position - cue.size;
  567. break;
  568. }
  569. // Horizontal box orientation; textPos is the distance from the left edge of the
  570. // area to the left edge of the box and cue.size is the distance extending to
  571. // the right from there.
  572. if (cue.vertical === "") {
  573. this.applyStyles({
  574. left: this.formatStyle(textPos, "%"),
  575. width: this.formatStyle(cue.size, "%")
  576. });
  577. // Vertical box orientation; textPos is the distance from the top edge of the
  578. // area to the top edge of the box and cue.size is the height extending
  579. // downwards from there.
  580. } else {
  581. this.applyStyles({
  582. top: this.formatStyle(textPos, "%"),
  583. height: this.formatStyle(cue.size, "%")
  584. });
  585. }
  586. this.move = function(box) {
  587. this.applyStyles({
  588. top: this.formatStyle(box.top, "px"),
  589. bottom: this.formatStyle(box.bottom, "px"),
  590. left: this.formatStyle(box.left, "px"),
  591. right: this.formatStyle(box.right, "px"),
  592. height: this.formatStyle(box.height, "px"),
  593. width: this.formatStyle(box.width, "px")
  594. });
  595. };
  596. }
  597. CueStyleBox.prototype = _objCreate(StyleBox.prototype);
  598. CueStyleBox.prototype.constructor = CueStyleBox;
  599. // Represents the co-ordinates of an Element in a way that we can easily
  600. // compute things with such as if it overlaps or intersects with another Element.
  601. // Can initialize it with either a StyleBox or another BoxPosition.
  602. function BoxPosition(obj) {
  603. // Either a BoxPosition was passed in and we need to copy it, or a StyleBox
  604. // was passed in and we need to copy the results of 'getBoundingClientRect'
  605. // as the object returned is readonly. All co-ordinate values are in reference
  606. // to the viewport origin (top left).
  607. var lh, height, width, top;
  608. if (obj.div) {
  609. height = obj.div.offsetHeight;
  610. width = obj.div.offsetWidth;
  611. top = obj.div.offsetTop;
  612. var rects = (rects = obj.div.childNodes) && (rects = rects[0]) &&
  613. rects.getClientRects && rects.getClientRects();
  614. obj = obj.div.getBoundingClientRect();
  615. // In certain cases the outter div will be slightly larger then the sum of
  616. // the inner div's lines. This could be due to bold text, etc, on some platforms.
  617. // In this case we should get the average line height and use that. This will
  618. // result in the desired behaviour.
  619. lh = rects ? Math.max((rects[0] && rects[0].height) || 0, obj.height / rects.length)
  620. : 0;
  621. }
  622. this.left = obj.left;
  623. this.right = obj.right;
  624. this.top = obj.top || top;
  625. this.height = obj.height || height;
  626. this.bottom = obj.bottom || (top + (obj.height || height));
  627. this.width = obj.width || width;
  628. this.lineHeight = lh !== undefined ? lh : obj.lineHeight;
  629. }
  630. // Move the box along a particular axis. Optionally pass in an amount to move
  631. // the box. If no amount is passed then the default is the line height of the
  632. // box.
  633. BoxPosition.prototype.move = function(axis, toMove) {
  634. toMove = toMove !== undefined ? toMove : this.lineHeight;
  635. switch (axis) {
  636. case "+x":
  637. this.left += toMove;
  638. this.right += toMove;
  639. break;
  640. case "-x":
  641. this.left -= toMove;
  642. this.right -= toMove;
  643. break;
  644. case "+y":
  645. this.top += toMove;
  646. this.bottom += toMove;
  647. break;
  648. case "-y":
  649. this.top -= toMove;
  650. this.bottom -= toMove;
  651. break;
  652. }
  653. };
  654. // Check if this box overlaps another box, b2.
  655. BoxPosition.prototype.overlaps = function(b2) {
  656. return this.left < b2.right &&
  657. this.right > b2.left &&
  658. this.top < b2.bottom &&
  659. this.bottom > b2.top;
  660. };
  661. // Check if this box overlaps any other boxes in boxes.
  662. BoxPosition.prototype.overlapsAny = function(boxes) {
  663. for (var i = 0; i < boxes.length; i++) {
  664. if (this.overlaps(boxes[i])) {
  665. return true;
  666. }
  667. }
  668. return false;
  669. };
  670. // Check if this box is within another box.
  671. BoxPosition.prototype.within = function(container) {
  672. return this.top >= container.top &&
  673. this.bottom <= container.bottom &&
  674. this.left >= container.left &&
  675. this.right <= container.right;
  676. };
  677. // Check if this box is entirely within the container or it is overlapping
  678. // on the edge opposite of the axis direction passed. For example, if "+x" is
  679. // passed and the box is overlapping on the left edge of the container, then
  680. // return true.
  681. BoxPosition.prototype.overlapsOppositeAxis = function(container, axis) {
  682. switch (axis) {
  683. case "+x":
  684. return this.left < container.left;
  685. case "-x":
  686. return this.right > container.right;
  687. case "+y":
  688. return this.top < container.top;
  689. case "-y":
  690. return this.bottom > container.bottom;
  691. }
  692. };
  693. // Find the percentage of the area that this box is overlapping with another
  694. // box.
  695. BoxPosition.prototype.intersectPercentage = function(b2) {
  696. var x = Math.max(0, Math.min(this.right, b2.right) - Math.max(this.left, b2.left)),
  697. y = Math.max(0, Math.min(this.bottom, b2.bottom) - Math.max(this.top, b2.top)),
  698. intersectArea = x * y;
  699. return intersectArea / (this.height * this.width);
  700. };
  701. // Convert the positions from this box to CSS compatible positions using
  702. // the reference container's positions. This has to be done because this
  703. // box's positions are in reference to the viewport origin, whereas, CSS
  704. // values are in referecne to their respective edges.
  705. BoxPosition.prototype.toCSSCompatValues = function(reference) {
  706. return {
  707. top: this.top - reference.top,
  708. bottom: reference.bottom - this.bottom,
  709. left: this.left - reference.left,
  710. right: reference.right - this.right,
  711. height: this.height,
  712. width: this.width
  713. };
  714. };
  715. // Get an object that represents the box's position without anything extra.
  716. // Can pass a StyleBox, HTMLElement, or another BoxPositon.
  717. BoxPosition.getSimpleBoxPosition = function(obj) {
  718. var height = obj.div ? obj.div.offsetHeight : obj.tagName ? obj.offsetHeight : 0;
  719. var width = obj.div ? obj.div.offsetWidth : obj.tagName ? obj.offsetWidth : 0;
  720. var top = obj.div ? obj.div.offsetTop : obj.tagName ? obj.offsetTop : 0;
  721. obj = obj.div ? obj.div.getBoundingClientRect() :
  722. obj.tagName ? obj.getBoundingClientRect() : obj;
  723. var ret = {
  724. left: obj.left,
  725. right: obj.right,
  726. top: obj.top || top,
  727. height: obj.height || height,
  728. bottom: obj.bottom || (top + (obj.height || height)),
  729. width: obj.width || width
  730. };
  731. return ret;
  732. };
  733. // Move a StyleBox to its specified, or next best, position. The containerBox
  734. // is the box that contains the StyleBox, such as a div. boxPositions are
  735. // a list of other boxes that the styleBox can't overlap with.
  736. function moveBoxToLinePosition(window, styleBox, containerBox, boxPositions) {
  737. // Find the best position for a cue box, b, on the video. The axis parameter
  738. // is a list of axis, the order of which, it will move the box along. For example:
  739. // Passing ["+x", "-x"] will move the box first along the x axis in the positive
  740. // direction. If it doesn't find a good position for it there it will then move
  741. // it along the x axis in the negative direction.
  742. function findBestPosition(b, axis) {
  743. var bestPosition,
  744. specifiedPosition = new BoxPosition(b),
  745. percentage = 1; // Highest possible so the first thing we get is better.
  746. for (var i = 0; i < axis.length; i++) {
  747. while (b.overlapsOppositeAxis(containerBox, axis[i]) ||
  748. (b.within(containerBox) && b.overlapsAny(boxPositions))) {
  749. b.move(axis[i]);
  750. }
  751. // We found a spot where we aren't overlapping anything. This is our
  752. // best position.
  753. if (b.within(containerBox)) {
  754. return b;
  755. }
  756. var p = b.intersectPercentage(containerBox);
  757. // If we're outside the container box less then we were on our last try
  758. // then remember this position as the best position.
  759. if (percentage > p) {
  760. bestPosition = new BoxPosition(b);
  761. percentage = p;
  762. }
  763. // Reset the box position to the specified position.
  764. b = new BoxPosition(specifiedPosition);
  765. }
  766. return bestPosition || specifiedPosition;
  767. }
  768. var boxPosition = new BoxPosition(styleBox),
  769. cue = styleBox.cue,
  770. linePos = computeLinePos(cue),
  771. axis = [];
  772. // If we have a line number to align the cue to.
  773. if (cue.snapToLines) {
  774. var size;
  775. switch (cue.vertical) {
  776. case "":
  777. axis = [ "+y", "-y" ];
  778. size = "height";
  779. break;
  780. case "rl":
  781. axis = [ "+x", "-x" ];
  782. size = "width";
  783. break;
  784. case "lr":
  785. axis = [ "-x", "+x" ];
  786. size = "width";
  787. break;
  788. }
  789. var step = boxPosition.lineHeight,
  790. position = step * Math.round(linePos),
  791. maxPosition = containerBox[size] + step,
  792. initialAxis = axis[0];
  793. // If the specified intial position is greater then the max position then
  794. // clamp the box to the amount of steps it would take for the box to
  795. // reach the max position.
  796. if (Math.abs(position) > maxPosition) {
  797. position = position < 0 ? -1 : 1;
  798. position *= Math.ceil(maxPosition / step) * step;
  799. }
  800. // If computed line position returns negative then line numbers are
  801. // relative to the bottom of the video instead of the top. Therefore, we
  802. // need to increase our initial position by the length or width of the
  803. // video, depending on the writing direction, and reverse our axis directions.
  804. if (linePos < 0) {
  805. position += cue.vertical === "" ? containerBox.height : containerBox.width;
  806. axis = axis.reverse();
  807. }
  808. // Move the box to the specified position. This may not be its best
  809. // position.
  810. boxPosition.move(initialAxis, position);
  811. } else {
  812. // If we have a percentage line value for the cue.
  813. var calculatedPercentage = (boxPosition.lineHeight / containerBox.height) * 100;
  814. switch (cue.lineAlign) {
  815. case "center":
  816. linePos -= (calculatedPercentage / 2);
  817. break;
  818. case "end":
  819. linePos -= calculatedPercentage;
  820. break;
  821. }
  822. // Apply initial line position to the cue box.
  823. switch (cue.vertical) {
  824. case "":
  825. styleBox.applyStyles({
  826. top: styleBox.formatStyle(linePos, "%")
  827. });
  828. break;
  829. case "rl":
  830. styleBox.applyStyles({
  831. left: styleBox.formatStyle(linePos, "%")
  832. });
  833. break;
  834. case "lr":
  835. styleBox.applyStyles({
  836. right: styleBox.formatStyle(linePos, "%")
  837. });
  838. break;
  839. }
  840. axis = [ "+y", "-x", "+x", "-y" ];
  841. // Get the box position again after we've applied the specified positioning
  842. // to it.
  843. boxPosition = new BoxPosition(styleBox);
  844. }
  845. var bestPosition = findBestPosition(boxPosition, axis);
  846. styleBox.move(bestPosition.toCSSCompatValues(containerBox));
  847. }
  848. function WebVTT() {
  849. // Nothing
  850. }
  851. // Helper to allow strings to be decoded instead of the default binary utf8 data.
  852. WebVTT.StringDecoder = function() {
  853. return {
  854. decode: function(data) {
  855. if (!data) {
  856. return "";
  857. }
  858. if (typeof data !== "string") {
  859. throw new Error("Error - expected string data.");
  860. }
  861. return decodeURIComponent(encodeURIComponent(data));
  862. }
  863. };
  864. };
  865. WebVTT.convertCueToDOMTree = function(window, cuetext) {
  866. if (!window || !cuetext) {
  867. return null;
  868. }
  869. return parseContent(window, cuetext);
  870. };
  871. var FONT_SIZE_PERCENT = 0.05;
  872. var FONT_STYLE = "sans-serif";
  873. var CUE_BACKGROUND_PADDING = "1.5%";
  874. // Runs the processing model over the cues and regions passed to it.
  875. // @param overlay A block level element (usually a div) that the computed cues
  876. // and regions will be placed into.
  877. WebVTT.processCues = function(window, cues, overlay) {
  878. if (!window || !cues || !overlay) {
  879. return null;
  880. }
  881. // Remove all previous children.
  882. while (overlay.firstChild) {
  883. overlay.removeChild(overlay.firstChild);
  884. }
  885. var paddedOverlay = window.document.createElement("div");
  886. paddedOverlay.style.position = "absolute";
  887. paddedOverlay.style.left = "0";
  888. paddedOverlay.style.right = "0";
  889. paddedOverlay.style.top = "0";
  890. paddedOverlay.style.bottom = "0";
  891. paddedOverlay.style.margin = CUE_BACKGROUND_PADDING;
  892. overlay.appendChild(paddedOverlay);
  893. // Determine if we need to compute the display states of the cues. This could
  894. // be the case if a cue's state has been changed since the last computation or
  895. // if it has not been computed yet.
  896. function shouldCompute(cues) {
  897. for (var i = 0; i < cues.length; i++) {
  898. if (cues[i].hasBeenReset || !cues[i].displayState) {
  899. return true;
  900. }
  901. }
  902. return false;
  903. }
  904. // We don't need to recompute the cues' display states. Just reuse them.
  905. if (!shouldCompute(cues)) {
  906. for (var i = 0; i < cues.length; i++) {
  907. paddedOverlay.appendChild(cues[i].displayState);
  908. }
  909. return;
  910. }
  911. var boxPositions = [],
  912. containerBox = BoxPosition.getSimpleBoxPosition(paddedOverlay),
  913. fontSize = Math.round(containerBox.height * FONT_SIZE_PERCENT * 100) / 100;
  914. var styleOptions = {
  915. font: fontSize + "px " + FONT_STYLE
  916. };
  917. (function() {
  918. var styleBox, cue;
  919. for (var i = 0; i < cues.length; i++) {
  920. cue = cues[i];
  921. // Compute the intial position and styles of the cue div.
  922. styleBox = new CueStyleBox(window, cue, styleOptions);
  923. paddedOverlay.appendChild(styleBox.div);
  924. // Move the cue div to it's correct line position.
  925. moveBoxToLinePosition(window, styleBox, containerBox, boxPositions);
  926. // Remember the computed div so that we don't have to recompute it later
  927. // if we don't have too.
  928. cue.displayState = styleBox.div;
  929. boxPositions.push(BoxPosition.getSimpleBoxPosition(styleBox));
  930. }
  931. })();
  932. };
  933. WebVTT.Parser = function(window, vttjs, decoder) {
  934. if (!decoder) {
  935. decoder = vttjs;
  936. vttjs = {};
  937. }
  938. if (!vttjs) {
  939. vttjs = {};
  940. }
  941. this.window = window;
  942. this.vttjs = vttjs;
  943. this.state = "INITIAL";
  944. this.buffer = "";
  945. this.decoder = decoder || new TextDecoder("utf8");
  946. this.regionList = [];
  947. };
  948. WebVTT.Parser.prototype = {
  949. // If the error is a ParsingError then report it to the consumer if
  950. // possible. If it's not a ParsingError then throw it like normal.
  951. reportOrThrowError: function(e) {
  952. if (e instanceof ParsingError) {
  953. this.onparsingerror && this.onparsingerror(e);
  954. } else {
  955. throw e;
  956. }
  957. },
  958. parse: function (data) {
  959. var self = this;
  960. // If there is no data then we won't decode it, but will just try to parse
  961. // whatever is in buffer already. This may occur in circumstances, for
  962. // example when flush() is called.
  963. if (data) {
  964. // Try to decode the data that we received.
  965. self.buffer += self.decoder.decode(data, {stream: true});
  966. }
  967. function collectNextLine() {
  968. var buffer = self.buffer;
  969. var pos = 0;
  970. while (pos < buffer.length && buffer[pos] !== '\r' && buffer[pos] !== '\n') {
  971. ++pos;
  972. }
  973. var line = buffer.substr(0, pos);
  974. // Advance the buffer early in case we fail below.
  975. if (buffer[pos] === '\r') {
  976. ++pos;
  977. }
  978. if (buffer[pos] === '\n') {
  979. ++pos;
  980. }
  981. self.buffer = buffer.substr(pos);
  982. return line;
  983. }
  984. // 3.4 WebVTT region and WebVTT region settings syntax
  985. function parseRegion(input) {
  986. var settings = new Settings();
  987. parseOptions(input, function (k, v) {
  988. switch (k) {
  989. case "id":
  990. settings.set(k, v);
  991. break;
  992. case "width":
  993. settings.percent(k, v);
  994. break;
  995. case "lines":
  996. settings.integer(k, v);
  997. break;
  998. case "regionanchor":
  999. case "viewportanchor":
  1000. var xy = v.split(',');
  1001. if (xy.length !== 2) {
  1002. break;
  1003. }
  1004. // We have to make sure both x and y parse, so use a temporary
  1005. // settings object here.
  1006. var anchor = new Settings();
  1007. anchor.percent("x", xy[0]);
  1008. anchor.percent("y", xy[1]);
  1009. if (!anchor.has("x") || !anchor.has("y")) {
  1010. break;
  1011. }
  1012. settings.set(k + "X", anchor.get("x"));
  1013. settings.set(k + "Y", anchor.get("y"));
  1014. break;
  1015. case "scroll":
  1016. settings.alt(k, v, ["up"]);
  1017. break;
  1018. }
  1019. }, /=/, /\s/);
  1020. // Create the region, using default values for any values that were not
  1021. // specified.
  1022. if (settings.has("id")) {
  1023. var region = new (self.vttjs.VTTRegion || self.window.VTTRegion)();
  1024. region.width = settings.get("width", 100);
  1025. region.lines = settings.get("lines", 3);
  1026. region.regionAnchorX = settings.get("regionanchorX", 0);
  1027. region.regionAnchorY = settings.get("regionanchorY", 100);
  1028. region.viewportAnchorX = settings.get("viewportanchorX", 0);
  1029. region.viewportAnchorY = settings.get("viewportanchorY", 100);
  1030. region.scroll = settings.get("scroll", "");
  1031. // Register the region.
  1032. self.onregion && self.onregion(region);
  1033. // Remember the VTTRegion for later in case we parse any VTTCues that
  1034. // reference it.
  1035. self.regionList.push({
  1036. id: settings.get("id"),
  1037. region: region
  1038. });
  1039. }
  1040. }
  1041. // draft-pantos-http-live-streaming-20
  1042. // https://tools.ietf.org/html/draft-pantos-http-live-streaming-20#section-3.5
  1043. // 3.5 WebVTT
  1044. function parseTimestampMap(input) {
  1045. var settings = new Settings();
  1046. parseOptions(input, function(k, v) {
  1047. switch(k) {
  1048. case "MPEGT":
  1049. settings.integer(k + 'S', v);
  1050. break;
  1051. case "LOCA":
  1052. settings.set(k + 'L', parseTimeStamp(v));
  1053. break;
  1054. }
  1055. }, /[^\d]:/, /,/);
  1056. self.ontimestampmap && self.ontimestampmap({
  1057. "MPEGTS": settings.get("MPEGTS"),
  1058. "LOCAL": settings.get("LOCAL")
  1059. });
  1060. }
  1061. // 3.2 WebVTT metadata header syntax
  1062. function parseHeader(input) {
  1063. if (input.match(/X-TIMESTAMP-MAP/)) {
  1064. // This line contains HLS X-TIMESTAMP-MAP metadata
  1065. parseOptions(input, function(k, v) {
  1066. switch(k) {
  1067. case "X-TIMESTAMP-MAP":
  1068. parseTimestampMap(v);
  1069. break;
  1070. }
  1071. }, /=/);
  1072. } else {
  1073. parseOptions(input, function (k, v) {
  1074. switch (k) {
  1075. case "Region":
  1076. // 3.3 WebVTT region metadata header syntax
  1077. parseRegion(v);
  1078. break;
  1079. }
  1080. }, /:/);
  1081. }
  1082. }
  1083. // 5.1 WebVTT file parsing.
  1084. try {
  1085. var line;
  1086. if (self.state === "INITIAL") {
  1087. // We can't start parsing until we have the first line.
  1088. if (!/\r\n|\n/.test(self.buffer)) {
  1089. return this;
  1090. }
  1091. line = collectNextLine();
  1092. var m = line.match(/^WEBVTT([ \t].*)?$/);
  1093. if (!m || !m[0]) {
  1094. throw new ParsingError(ParsingError.Errors.BadSignature);
  1095. }
  1096. self.state = "HEADER";
  1097. }
  1098. var alreadyCollectedLine = false;
  1099. while (self.buffer) {
  1100. // We can't parse a line until we have the full line.
  1101. if (!/\r\n|\n/.test(self.buffer)) {
  1102. return this;
  1103. }
  1104. if (!alreadyCollectedLine) {
  1105. line = collectNextLine();
  1106. } else {
  1107. alreadyCollectedLine = false;
  1108. }
  1109. switch (self.state) {
  1110. case "HEADER":
  1111. // 13-18 - Allow a header (metadata) under the WEBVTT line.
  1112. if (/:/.test(line)) {
  1113. parseHeader(line);
  1114. } else if (!line) {
  1115. // An empty line terminates the header and starts the body (cues).
  1116. self.state = "ID";
  1117. }
  1118. continue;
  1119. case "NOTE":
  1120. // Ignore NOTE blocks.
  1121. if (!line) {
  1122. self.state = "ID";
  1123. }
  1124. continue;
  1125. case "ID":
  1126. // Check for the start of NOTE blocks.
  1127. if (/^NOTE($|[ \t])/.test(line)) {
  1128. self.state = "NOTE";
  1129. break;
  1130. }
  1131. // 19-29 - Allow any number of line terminators, then initialize new cue values.
  1132. if (!line) {
  1133. continue;
  1134. }
  1135. self.cue = new (self.vttjs.VTTCue || self.window.VTTCue)(0, 0, "");
  1136. // Safari still uses the old middle value and won't accept center
  1137. try {
  1138. self.cue.align = "center";
  1139. } catch (e) {
  1140. self.cue.align = "middle";
  1141. }
  1142. self.state = "CUE";
  1143. // 30-39 - Check if self line contains an optional identifier or timing data.
  1144. if (line.indexOf("-->") === -1) {
  1145. self.cue.id = line;
  1146. continue;
  1147. }
  1148. // Process line as start of a cue.
  1149. /*falls through*/
  1150. case "CUE":
  1151. // 40 - Collect cue timings and settings.
  1152. try {
  1153. parseCue(line, self.cue, self.regionList);
  1154. } catch (e) {
  1155. self.reportOrThrowError(e);
  1156. // In case of an error ignore rest of the cue.
  1157. self.cue = null;
  1158. self.state = "BADCUE";
  1159. continue;
  1160. }
  1161. self.state = "CUETEXT";
  1162. continue;
  1163. case "CUETEXT":
  1164. var hasSubstring = line.indexOf("-->") !== -1;
  1165. // 34 - If we have an empty line then report the cue.
  1166. // 35 - If we have the special substring '-->' then report the cue,
  1167. // but do not collect the line as we need to process the current
  1168. // one as a new cue.
  1169. if (!line || hasSubstring && (alreadyCollectedLine = true)) {
  1170. // We are done parsing self cue.
  1171. self.oncue && self.oncue(self.cue);
  1172. self.cue = null;
  1173. self.state = "ID";
  1174. continue;
  1175. }
  1176. if (self.cue.text) {
  1177. self.cue.text += "\n";
  1178. }
  1179. self.cue.text += line.replace(/\u2028/g, '\n').replace(/u2029/g, '\n');
  1180. continue;
  1181. case "BADCUE": // BADCUE
  1182. // 54-62 - Collect and discard the remaining cue.
  1183. if (!line) {
  1184. self.state = "ID";
  1185. }
  1186. continue;
  1187. }
  1188. }
  1189. } catch (e) {
  1190. self.reportOrThrowError(e);
  1191. // If we are currently parsing a cue, report what we have.
  1192. if (self.state === "CUETEXT" && self.cue && self.oncue) {
  1193. self.oncue(self.cue);
  1194. }
  1195. self.cue = null;
  1196. // Enter BADWEBVTT state if header was not parsed correctly otherwise
  1197. // another exception occurred so enter BADCUE state.
  1198. self.state = self.state === "INITIAL" ? "BADWEBVTT" : "BADCUE";
  1199. }
  1200. return this;
  1201. },
  1202. flush: function () {
  1203. var self = this;
  1204. try {
  1205. // Finish decoding the stream.
  1206. self.buffer += self.decoder.decode();
  1207. // Synthesize the end of the current cue or region.
  1208. if (self.cue || self.state === "HEADER") {
  1209. self.buffer += "\n\n";
  1210. self.parse();
  1211. }
  1212. // If we've flushed, parsed, and we're still on the INITIAL state then
  1213. // that means we don't have enough of the stream to parse the first
  1214. // line.
  1215. if (self.state === "INITIAL") {
  1216. throw new ParsingError(ParsingError.Errors.BadSignature);
  1217. }
  1218. } catch(e) {
  1219. self.reportOrThrowError(e);
  1220. }
  1221. self.onflush && self.onflush();
  1222. return this;
  1223. }
  1224. };
  1225. module.exports = WebVTT;
  1226. },{"global/document":5}],2:[function(require,module,exports){
  1227. /**
  1228. * Copyright 2013 vtt.js Contributors
  1229. *
  1230. * Licensed under the Apache License, Version 2.0 (the "License");
  1231. * you may not use this file except in compliance with the License.
  1232. * You may obtain a copy of the License at
  1233. *
  1234. * http://www.apache.org/licenses/LICENSE-2.0
  1235. *
  1236. * Unless required by applicable law or agreed to in writing, software
  1237. * distributed under the License is distributed on an "AS IS" BASIS,
  1238. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1239. * See the License for the specific language governing permissions and
  1240. * limitations under the License.
  1241. */
  1242. var autoKeyword = "auto";
  1243. var directionSetting = {
  1244. "": 1,
  1245. "lr": 1,
  1246. "rl": 1
  1247. };
  1248. var alignSetting = {
  1249. "start": 1,
  1250. "center": 1,
  1251. "end": 1,
  1252. "left": 1,
  1253. "right": 1,
  1254. "auto": 1,
  1255. "line-left": 1,
  1256. "line-right": 1
  1257. };
  1258. function findDirectionSetting(value) {
  1259. if (typeof value !== "string") {
  1260. return false;
  1261. }
  1262. var dir = directionSetting[value.toLowerCase()];
  1263. return dir ? value.toLowerCase() : false;
  1264. }
  1265. function findAlignSetting(value) {
  1266. if (typeof value !== "string") {
  1267. return false;
  1268. }
  1269. var align = alignSetting[value.toLowerCase()];
  1270. return align ? value.toLowerCase() : false;
  1271. }
  1272. function VTTCue(startTime, endTime, text) {
  1273. /**
  1274. * Shim implementation specific properties. These properties are not in
  1275. * the spec.
  1276. */
  1277. // Lets us know when the VTTCue's data has changed in such a way that we need
  1278. // to recompute its display state. This lets us compute its display state
  1279. // lazily.
  1280. this.hasBeenReset = false;
  1281. /**
  1282. * VTTCue and TextTrackCue properties
  1283. * http://dev.w3.org/html5/webvtt/#vttcue-interface
  1284. */
  1285. var _id = "";
  1286. var _pauseOnExit = false;
  1287. var _startTime = startTime;
  1288. var _endTime = endTime;
  1289. var _text = text;
  1290. var _region = null;
  1291. var _vertical = "";
  1292. var _snapToLines = true;
  1293. var _line = "auto";
  1294. var _lineAlign = "start";
  1295. var _position = "auto";
  1296. var _positionAlign = "auto";
  1297. var _size = 100;
  1298. var _align = "center";
  1299. Object.defineProperties(this, {
  1300. "id": {
  1301. enumerable: true,
  1302. get: function() {
  1303. return _id;
  1304. },
  1305. set: function(value) {
  1306. _id = "" + value;
  1307. }
  1308. },
  1309. "pauseOnExit": {
  1310. enumerable: true,
  1311. get: function() {
  1312. return _pauseOnExit;
  1313. },
  1314. set: function(value) {
  1315. _pauseOnExit = !!value;
  1316. }
  1317. },
  1318. "startTime": {
  1319. enumerable: true,
  1320. get: function() {
  1321. return _startTime;
  1322. },
  1323. set: function(value) {
  1324. if (typeof value !== "number") {
  1325. throw new TypeError("Start time must be set to a number.");
  1326. }
  1327. _startTime = value;
  1328. this.hasBeenReset = true;
  1329. }
  1330. },
  1331. "endTime": {
  1332. enumerable: true,
  1333. get: function() {
  1334. return _endTime;
  1335. },
  1336. set: function(value) {
  1337. if (typeof value !== "number") {
  1338. throw new TypeError("End time must be set to a number.");
  1339. }
  1340. _endTime = value;
  1341. this.hasBeenReset = true;
  1342. }
  1343. },
  1344. "text": {
  1345. enumerable: true,
  1346. get: function() {
  1347. return _text;
  1348. },
  1349. set: function(value) {
  1350. _text = "" + value;
  1351. this.hasBeenReset = true;
  1352. }
  1353. },
  1354. "region": {
  1355. enumerable: true,
  1356. get: function() {
  1357. return _region;
  1358. },
  1359. set: function(value) {
  1360. _region = value;
  1361. this.hasBeenReset = true;
  1362. }
  1363. },
  1364. "vertical": {
  1365. enumerable: true,
  1366. get: function() {
  1367. return _vertical;
  1368. },
  1369. set: function(value) {
  1370. var setting = findDirectionSetting(value);
  1371. // Have to check for false because the setting an be an empty string.
  1372. if (setting === false) {
  1373. throw new SyntaxError("Vertical: an invalid or illegal direction string was specified.");
  1374. }
  1375. _vertical = setting;
  1376. this.hasBeenReset = true;
  1377. }
  1378. },
  1379. "snapToLines": {
  1380. enumerable: true,
  1381. get: function() {
  1382. return _snapToLines;
  1383. },
  1384. set: function(value) {
  1385. _snapToLines = !!value;
  1386. this.hasBeenReset = true;
  1387. }
  1388. },
  1389. "line": {
  1390. enumerable: true,
  1391. get: function() {
  1392. return _line;
  1393. },
  1394. set: function(value) {
  1395. if (typeof value !== "number" && value !== autoKeyword) {
  1396. throw new SyntaxError("Line: an invalid number or illegal string was specified.");
  1397. }
  1398. _line = value;
  1399. this.hasBeenReset = true;
  1400. }
  1401. },
  1402. "lineAlign": {
  1403. enumerable: true,
  1404. get: function() {
  1405. return _lineAlign;
  1406. },
  1407. set: function(value) {
  1408. var setting = findAlignSetting(value);
  1409. if (!setting) {
  1410. console.warn("lineAlign: an invalid or illegal string was specified.");
  1411. } else {
  1412. _lineAlign = setting;
  1413. this.hasBeenReset = true;
  1414. }
  1415. }
  1416. },
  1417. "position": {
  1418. enumerable: true,
  1419. get: function() {
  1420. return _position;
  1421. },
  1422. set: function(value) {
  1423. if (value < 0 || value > 100) {
  1424. throw new Error("Position must be between 0 and 100.");
  1425. }
  1426. _position = value;
  1427. this.hasBeenReset = true;
  1428. }
  1429. },
  1430. "positionAlign": {
  1431. enumerable: true,
  1432. get: function() {
  1433. return _positionAlign;
  1434. },
  1435. set: function(value) {
  1436. var setting = findAlignSetting(value);
  1437. if (!setting) {
  1438. console.warn("positionAlign: an invalid or illegal string was specified.");
  1439. } else {
  1440. _positionAlign = setting;
  1441. this.hasBeenReset = true;
  1442. }
  1443. }
  1444. },
  1445. "size": {
  1446. enumerable: true,
  1447. get: function() {
  1448. return _size;
  1449. },
  1450. set: function(value) {
  1451. if (value < 0 || value > 100) {
  1452. throw new Error("Size must be between 0 and 100.");
  1453. }
  1454. _size = value;
  1455. this.hasBeenReset = true;
  1456. }
  1457. },
  1458. "align": {
  1459. enumerable: true,
  1460. get: function() {
  1461. return _align;
  1462. },
  1463. set: function(value) {
  1464. var setting = findAlignSetting(value);
  1465. if (!setting) {
  1466. throw new SyntaxError("align: an invalid or illegal alignment string was specified.");
  1467. }
  1468. _align = setting;
  1469. this.hasBeenReset = true;
  1470. }
  1471. }
  1472. });
  1473. /**
  1474. * Other <track> spec defined properties
  1475. */
  1476. // http://www.whatwg.org/specs/web-apps/current-work/multipage/the-video-element.html#text-track-cue-display-state
  1477. this.displayState = undefined;
  1478. }
  1479. /**
  1480. * VTTCue methods
  1481. */
  1482. VTTCue.prototype.getCueAsHTML = function() {
  1483. // Assume WebVTT.convertCueToDOMTree is on the global.
  1484. return WebVTT.convertCueToDOMTree(window, this.text);
  1485. };
  1486. module.exports = VTTCue;
  1487. },{}],3:[function(require,module,exports){
  1488. /**
  1489. * Copyright 2013 vtt.js Contributors
  1490. *
  1491. * Licensed under the Apache License, Version 2.0 (the "License");
  1492. * you may not use this file except in compliance with the License.
  1493. * You may obtain a copy of the License at
  1494. *
  1495. * http://www.apache.org/licenses/LICENSE-2.0
  1496. *
  1497. * Unless required by applicable law or agreed to in writing, software
  1498. * distributed under the License is distributed on an "AS IS" BASIS,
  1499. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1500. * See the License for the specific language governing permissions and
  1501. * limitations under the License.
  1502. */
  1503. var scrollSetting = {
  1504. "": true,
  1505. "up": true
  1506. };
  1507. function findScrollSetting(value) {
  1508. if (typeof value !== "string") {
  1509. return false;
  1510. }
  1511. var scroll = scrollSetting[value.toLowerCase()];
  1512. return scroll ? value.toLowerCase() : false;
  1513. }
  1514. function isValidPercentValue(value) {
  1515. return typeof value === "number" && (value >= 0 && value <= 100);
  1516. }
  1517. // VTTRegion shim http://dev.w3.org/html5/webvtt/#vttregion-interface
  1518. function VTTRegion() {
  1519. var _width = 100;
  1520. var _lines = 3;
  1521. var _regionAnchorX = 0;
  1522. var _regionAnchorY = 100;
  1523. var _viewportAnchorX = 0;
  1524. var _viewportAnchorY = 100;
  1525. var _scroll = "";
  1526. Object.defineProperties(this, {
  1527. "width": {
  1528. enumerable: true,
  1529. get: function() {
  1530. return _width;
  1531. },
  1532. set: function(value) {
  1533. if (!isValidPercentValue(value)) {
  1534. throw new Error("Width must be between 0 and 100.");
  1535. }
  1536. _width = value;
  1537. }
  1538. },
  1539. "lines": {
  1540. enumerable: true,
  1541. get: function() {
  1542. return _lines;
  1543. },
  1544. set: function(value) {
  1545. if (typeof value !== "number") {
  1546. throw new TypeError("Lines must be set to a number.");
  1547. }
  1548. _lines = value;
  1549. }
  1550. },
  1551. "regionAnchorY": {
  1552. enumerable: true,
  1553. get: function() {
  1554. return _regionAnchorY;
  1555. },
  1556. set: function(value) {
  1557. if (!isValidPercentValue(value)) {
  1558. throw new Error("RegionAnchorX must be between 0 and 100.");
  1559. }
  1560. _regionAnchorY = value;
  1561. }
  1562. },
  1563. "regionAnchorX": {
  1564. enumerable: true,
  1565. get: function() {
  1566. return _regionAnchorX;
  1567. },
  1568. set: function(value) {
  1569. if(!isValidPercentValue(value)) {
  1570. throw new Error("RegionAnchorY must be between 0 and 100.");
  1571. }
  1572. _regionAnchorX = value;
  1573. }
  1574. },
  1575. "viewportAnchorY": {
  1576. enumerable: true,
  1577. get: function() {
  1578. return _viewportAnchorY;
  1579. },
  1580. set: function(value) {
  1581. if (!isValidPercentValue(value)) {
  1582. throw new Error("ViewportAnchorY must be between 0 and 100.");
  1583. }
  1584. _viewportAnchorY = value;
  1585. }
  1586. },
  1587. "viewportAnchorX": {
  1588. enumerable: true,
  1589. get: function() {
  1590. return _viewportAnchorX;
  1591. },
  1592. set: function(value) {
  1593. if (!isValidPercentValue(value)) {
  1594. throw new Error("ViewportAnchorX must be between 0 and 100.");
  1595. }
  1596. _viewportAnchorX = value;
  1597. }
  1598. },
  1599. "scroll": {
  1600. enumerable: true,
  1601. get: function() {
  1602. return _scroll;
  1603. },
  1604. set: function(value) {
  1605. var setting = findScrollSetting(value);
  1606. // Have to check for false as an empty string is a legal value.
  1607. if (setting === false) {
  1608. console.warn("Scroll: an invalid or illegal string was specified.");
  1609. } else {
  1610. _scroll = setting;
  1611. }
  1612. }
  1613. }
  1614. });
  1615. }
  1616. module.exports = VTTRegion;
  1617. },{}],4:[function(require,module,exports){
  1618. },{}],5:[function(require,module,exports){
  1619. (function (global){
  1620. var topLevel = typeof global !== 'undefined' ? global :
  1621. typeof window !== 'undefined' ? window : {}
  1622. var minDoc = require('min-document');
  1623. var doccy;
  1624. if (typeof document !== 'undefined') {
  1625. doccy = document;
  1626. } else {
  1627. doccy = topLevel['__GLOBAL_DOCUMENT_CACHE@4'];
  1628. if (!doccy) {
  1629. doccy = topLevel['__GLOBAL_DOCUMENT_CACHE@4'] = minDoc;
  1630. }
  1631. }
  1632. module.exports = doccy;
  1633. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  1634. },{"min-document":4}],6:[function(require,module,exports){
  1635. (function (global){
  1636. var win;
  1637. if (typeof window !== "undefined") {
  1638. win = window;
  1639. } else if (typeof global !== "undefined") {
  1640. win = global;
  1641. } else if (typeof self !== "undefined"){
  1642. win = self;
  1643. } else {
  1644. win = {};
  1645. }
  1646. module.exports = win;
  1647. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  1648. },{}],7:[function(require,module,exports){
  1649. /**
  1650. * Copyright 2013 vtt.js Contributors
  1651. *
  1652. * Licensed under the Apache License, Version 2.0 (the "License");
  1653. * you may not use this file except in compliance with the License.
  1654. * You may obtain a copy of the License at
  1655. *
  1656. * http://www.apache.org/licenses/LICENSE-2.0
  1657. *
  1658. * Unless required by applicable law or agreed to in writing, software
  1659. * distributed under the License is distributed on an "AS IS" BASIS,
  1660. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1661. * See the License for the specific language governing permissions and
  1662. * limitations under the License.
  1663. */
  1664. // Default exports for Node. Export the extended versions of VTTCue and
  1665. // VTTRegion in Node since we likely want the capability to convert back and
  1666. // forth between JSON. If we don't then it's not that big of a deal since we're
  1667. // off browser.
  1668. var window = require('global/window');
  1669. var vttjs = module.exports = {
  1670. WebVTT: require("./vtt.js"),
  1671. VTTCue: require("./vttcue.js"),
  1672. VTTRegion: require("./vttregion.js")
  1673. };
  1674. window.vttjs = vttjs;
  1675. window.WebVTT = vttjs.WebVTT;
  1676. var cueShim = vttjs.VTTCue;
  1677. var regionShim = vttjs.VTTRegion;
  1678. var nativeVTTCue = window.VTTCue;
  1679. var nativeVTTRegion = window.VTTRegion;
  1680. vttjs.shim = function() {
  1681. window.VTTCue = cueShim;
  1682. window.VTTRegion = regionShim;
  1683. };
  1684. vttjs.restore = function() {
  1685. window.VTTCue = nativeVTTCue;
  1686. window.VTTRegion = nativeVTTRegion;
  1687. };
  1688. if (!window.VTTCue) {
  1689. vttjs.shim();
  1690. }
  1691. },{"./vtt.js":1,"./vttcue.js":2,"./vttregion.js":3,"global/window":6}]},{},[7])(7)
  1692. });