vtt.global.js 55 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872
  1. (function(f){var g;if(typeof window!=='undefined'){g=window}else if(typeof self!=='undefined'){g=self}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. case "line-left":
  561. textPos = cue.position;
  562. break;
  563. case "center":
  564. textPos = cue.position - (cue.size / 2);
  565. break;
  566. case "end":
  567. case "line-right":
  568. textPos = cue.position - cue.size;
  569. break;
  570. }
  571. // Horizontal box orientation; textPos is the distance from the left edge of the
  572. // area to the left edge of the box and cue.size is the distance extending to
  573. // the right from there.
  574. if (cue.vertical === "") {
  575. this.applyStyles({
  576. left: this.formatStyle(textPos, "%"),
  577. width: this.formatStyle(cue.size, "%")
  578. });
  579. // Vertical box orientation; textPos is the distance from the top edge of the
  580. // area to the top edge of the box and cue.size is the height extending
  581. // downwards from there.
  582. } else {
  583. this.applyStyles({
  584. top: this.formatStyle(textPos, "%"),
  585. height: this.formatStyle(cue.size, "%")
  586. });
  587. }
  588. this.move = function(box) {
  589. this.applyStyles({
  590. top: this.formatStyle(box.top, "px"),
  591. bottom: this.formatStyle(box.bottom, "px"),
  592. left: this.formatStyle(box.left, "px"),
  593. right: this.formatStyle(box.right, "px"),
  594. height: this.formatStyle(box.height, "px"),
  595. width: this.formatStyle(box.width, "px")
  596. });
  597. };
  598. }
  599. CueStyleBox.prototype = _objCreate(StyleBox.prototype);
  600. CueStyleBox.prototype.constructor = CueStyleBox;
  601. // Represents the co-ordinates of an Element in a way that we can easily
  602. // compute things with such as if it overlaps or intersects with another Element.
  603. // Can initialize it with either a StyleBox or another BoxPosition.
  604. function BoxPosition(obj) {
  605. // Either a BoxPosition was passed in and we need to copy it, or a StyleBox
  606. // was passed in and we need to copy the results of 'getBoundingClientRect'
  607. // as the object returned is readonly. All co-ordinate values are in reference
  608. // to the viewport origin (top left).
  609. var lh, height, width, top;
  610. if (obj.div) {
  611. height = obj.div.offsetHeight;
  612. width = obj.div.offsetWidth;
  613. top = obj.div.offsetTop;
  614. var rects = (rects = obj.div.childNodes) && (rects = rects[0]) &&
  615. rects.getClientRects && rects.getClientRects();
  616. obj = obj.div.getBoundingClientRect();
  617. // In certain cases the outter div will be slightly larger then the sum of
  618. // the inner div's lines. This could be due to bold text, etc, on some platforms.
  619. // In this case we should get the average line height and use that. This will
  620. // result in the desired behaviour.
  621. lh = rects ? Math.max((rects[0] && rects[0].height) || 0, obj.height / rects.length)
  622. : 0;
  623. }
  624. this.left = obj.left;
  625. this.right = obj.right;
  626. this.top = obj.top || top;
  627. this.height = obj.height || height;
  628. this.bottom = obj.bottom || (top + (obj.height || height));
  629. this.width = obj.width || width;
  630. this.lineHeight = lh !== undefined ? lh : obj.lineHeight;
  631. }
  632. // Move the box along a particular axis. Optionally pass in an amount to move
  633. // the box. If no amount is passed then the default is the line height of the
  634. // box.
  635. BoxPosition.prototype.move = function(axis, toMove) {
  636. toMove = toMove !== undefined ? toMove : this.lineHeight;
  637. switch (axis) {
  638. case "+x":
  639. this.left += toMove;
  640. this.right += toMove;
  641. break;
  642. case "-x":
  643. this.left -= toMove;
  644. this.right -= toMove;
  645. break;
  646. case "+y":
  647. this.top += toMove;
  648. this.bottom += toMove;
  649. break;
  650. case "-y":
  651. this.top -= toMove;
  652. this.bottom -= toMove;
  653. break;
  654. }
  655. };
  656. // Check if this box overlaps another box, b2.
  657. BoxPosition.prototype.overlaps = function(b2) {
  658. return this.left < b2.right &&
  659. this.right > b2.left &&
  660. this.top < b2.bottom &&
  661. this.bottom > b2.top;
  662. };
  663. // Check if this box overlaps any other boxes in boxes.
  664. BoxPosition.prototype.overlapsAny = function(boxes) {
  665. for (var i = 0; i < boxes.length; i++) {
  666. if (this.overlaps(boxes[i])) {
  667. return true;
  668. }
  669. }
  670. return false;
  671. };
  672. // Check if this box is within another box.
  673. BoxPosition.prototype.within = function(container) {
  674. return this.top >= container.top &&
  675. this.bottom <= container.bottom &&
  676. this.left >= container.left &&
  677. this.right <= container.right;
  678. };
  679. // Check if this box is entirely within the container or it is overlapping
  680. // on the edge opposite of the axis direction passed. For example, if "+x" is
  681. // passed and the box is overlapping on the left edge of the container, then
  682. // return true.
  683. BoxPosition.prototype.overlapsOppositeAxis = function(container, axis) {
  684. switch (axis) {
  685. case "+x":
  686. return this.left < container.left;
  687. case "-x":
  688. return this.right > container.right;
  689. case "+y":
  690. return this.top < container.top;
  691. case "-y":
  692. return this.bottom > container.bottom;
  693. }
  694. };
  695. // Find the percentage of the area that this box is overlapping with another
  696. // box.
  697. BoxPosition.prototype.intersectPercentage = function(b2) {
  698. var x = Math.max(0, Math.min(this.right, b2.right) - Math.max(this.left, b2.left)),
  699. y = Math.max(0, Math.min(this.bottom, b2.bottom) - Math.max(this.top, b2.top)),
  700. intersectArea = x * y;
  701. return intersectArea / (this.height * this.width);
  702. };
  703. // Convert the positions from this box to CSS compatible positions using
  704. // the reference container's positions. This has to be done because this
  705. // box's positions are in reference to the viewport origin, whereas, CSS
  706. // values are in referecne to their respective edges.
  707. BoxPosition.prototype.toCSSCompatValues = function(reference) {
  708. return {
  709. top: this.top - reference.top,
  710. bottom: reference.bottom - this.bottom,
  711. left: this.left - reference.left,
  712. right: reference.right - this.right,
  713. height: this.height,
  714. width: this.width
  715. };
  716. };
  717. // Get an object that represents the box's position without anything extra.
  718. // Can pass a StyleBox, HTMLElement, or another BoxPositon.
  719. BoxPosition.getSimpleBoxPosition = function(obj) {
  720. var height = obj.div ? obj.div.offsetHeight : obj.tagName ? obj.offsetHeight : 0;
  721. var width = obj.div ? obj.div.offsetWidth : obj.tagName ? obj.offsetWidth : 0;
  722. var top = obj.div ? obj.div.offsetTop : obj.tagName ? obj.offsetTop : 0;
  723. obj = obj.div ? obj.div.getBoundingClientRect() :
  724. obj.tagName ? obj.getBoundingClientRect() : obj;
  725. var ret = {
  726. left: obj.left,
  727. right: obj.right,
  728. top: obj.top || top,
  729. height: obj.height || height,
  730. bottom: obj.bottom || (top + (obj.height || height)),
  731. width: obj.width || width
  732. };
  733. return ret;
  734. };
  735. // Move a StyleBox to its specified, or next best, position. The containerBox
  736. // is the box that contains the StyleBox, such as a div. boxPositions are
  737. // a list of other boxes that the styleBox can't overlap with.
  738. function moveBoxToLinePosition(window, styleBox, containerBox, boxPositions) {
  739. // Find the best position for a cue box, b, on the video. The axis parameter
  740. // is a list of axis, the order of which, it will move the box along. For example:
  741. // Passing ["+x", "-x"] will move the box first along the x axis in the positive
  742. // direction. If it doesn't find a good position for it there it will then move
  743. // it along the x axis in the negative direction.
  744. function findBestPosition(b, axis) {
  745. var bestPosition,
  746. specifiedPosition = new BoxPosition(b),
  747. percentage = 1; // Highest possible so the first thing we get is better.
  748. for (var i = 0; i < axis.length; i++) {
  749. while (b.overlapsOppositeAxis(containerBox, axis[i]) ||
  750. (b.within(containerBox) && b.overlapsAny(boxPositions))) {
  751. b.move(axis[i]);
  752. }
  753. // We found a spot where we aren't overlapping anything. This is our
  754. // best position.
  755. if (b.within(containerBox)) {
  756. return b;
  757. }
  758. var p = b.intersectPercentage(containerBox);
  759. // If we're outside the container box less then we were on our last try
  760. // then remember this position as the best position.
  761. if (percentage > p) {
  762. bestPosition = new BoxPosition(b);
  763. percentage = p;
  764. }
  765. // Reset the box position to the specified position.
  766. b = new BoxPosition(specifiedPosition);
  767. }
  768. return bestPosition || specifiedPosition;
  769. }
  770. var boxPosition = new BoxPosition(styleBox),
  771. cue = styleBox.cue,
  772. linePos = computeLinePos(cue),
  773. axis = [];
  774. // If we have a line number to align the cue to.
  775. if (cue.snapToLines) {
  776. var size;
  777. switch (cue.vertical) {
  778. case "":
  779. axis = [ "+y", "-y" ];
  780. size = "height";
  781. break;
  782. case "rl":
  783. axis = [ "+x", "-x" ];
  784. size = "width";
  785. break;
  786. case "lr":
  787. axis = [ "-x", "+x" ];
  788. size = "width";
  789. break;
  790. }
  791. var step = boxPosition.lineHeight,
  792. position = step * Math.round(linePos),
  793. maxPosition = containerBox[size] + step,
  794. initialAxis = axis[0];
  795. // If the specified intial position is greater then the max position then
  796. // clamp the box to the amount of steps it would take for the box to
  797. // reach the max position.
  798. if (Math.abs(position) > maxPosition) {
  799. position = position < 0 ? -1 : 1;
  800. position *= Math.ceil(maxPosition / step) * step;
  801. }
  802. // If computed line position returns negative then line numbers are
  803. // relative to the bottom of the video instead of the top. Therefore, we
  804. // need to increase our initial position by the length or width of the
  805. // video, depending on the writing direction, and reverse our axis directions.
  806. if (linePos < 0) {
  807. position += cue.vertical === "" ? containerBox.height : containerBox.width;
  808. axis = axis.reverse();
  809. }
  810. // Move the box to the specified position. This may not be its best
  811. // position.
  812. boxPosition.move(initialAxis, position);
  813. } else {
  814. // If we have a percentage line value for the cue.
  815. var calculatedPercentage = (boxPosition.lineHeight / containerBox.height) * 100;
  816. switch (cue.lineAlign) {
  817. case "center":
  818. linePos -= (calculatedPercentage / 2);
  819. break;
  820. case "end":
  821. linePos -= calculatedPercentage;
  822. break;
  823. }
  824. // Apply initial line position to the cue box.
  825. switch (cue.vertical) {
  826. case "":
  827. styleBox.applyStyles({
  828. top: styleBox.formatStyle(linePos, "%")
  829. });
  830. break;
  831. case "rl":
  832. styleBox.applyStyles({
  833. left: styleBox.formatStyle(linePos, "%")
  834. });
  835. break;
  836. case "lr":
  837. styleBox.applyStyles({
  838. right: styleBox.formatStyle(linePos, "%")
  839. });
  840. break;
  841. }
  842. axis = [ "+y", "-x", "+x", "-y" ];
  843. // Get the box position again after we've applied the specified positioning
  844. // to it.
  845. boxPosition = new BoxPosition(styleBox);
  846. }
  847. var bestPosition = findBestPosition(boxPosition, axis);
  848. styleBox.move(bestPosition.toCSSCompatValues(containerBox));
  849. }
  850. function WebVTT() {
  851. // Nothing
  852. }
  853. // Helper to allow strings to be decoded instead of the default binary utf8 data.
  854. WebVTT.StringDecoder = function() {
  855. return {
  856. decode: function(data) {
  857. if (!data) {
  858. return "";
  859. }
  860. if (typeof data !== "string") {
  861. throw new Error("Error - expected string data.");
  862. }
  863. return decodeURIComponent(encodeURIComponent(data));
  864. }
  865. };
  866. };
  867. WebVTT.convertCueToDOMTree = function(window, cuetext) {
  868. if (!window || !cuetext) {
  869. return null;
  870. }
  871. return parseContent(window, cuetext);
  872. };
  873. var FONT_SIZE_PERCENT = 0.05;
  874. var FONT_STYLE = "sans-serif";
  875. var CUE_BACKGROUND_PADDING = "1.5%";
  876. // Runs the processing model over the cues and regions passed to it.
  877. // @param overlay A block level element (usually a div) that the computed cues
  878. // and regions will be placed into.
  879. WebVTT.processCues = function(window, cues, overlay) {
  880. if (!window || !cues || !overlay) {
  881. return null;
  882. }
  883. // Remove all previous children.
  884. while (overlay.firstChild) {
  885. overlay.removeChild(overlay.firstChild);
  886. }
  887. var paddedOverlay = window.document.createElement("div");
  888. paddedOverlay.style.position = "absolute";
  889. paddedOverlay.style.left = "0";
  890. paddedOverlay.style.right = "0";
  891. paddedOverlay.style.top = "0";
  892. paddedOverlay.style.bottom = "0";
  893. paddedOverlay.style.margin = CUE_BACKGROUND_PADDING;
  894. overlay.appendChild(paddedOverlay);
  895. // Determine if we need to compute the display states of the cues. This could
  896. // be the case if a cue's state has been changed since the last computation or
  897. // if it has not been computed yet.
  898. function shouldCompute(cues) {
  899. for (var i = 0; i < cues.length; i++) {
  900. if (cues[i].hasBeenReset || !cues[i].displayState) {
  901. return true;
  902. }
  903. }
  904. return false;
  905. }
  906. // We don't need to recompute the cues' display states. Just reuse them.
  907. if (!shouldCompute(cues)) {
  908. for (var i = 0; i < cues.length; i++) {
  909. paddedOverlay.appendChild(cues[i].displayState);
  910. }
  911. return;
  912. }
  913. var boxPositions = [],
  914. containerBox = BoxPosition.getSimpleBoxPosition(paddedOverlay),
  915. fontSize = Math.round(containerBox.height * FONT_SIZE_PERCENT * 100) / 100;
  916. var styleOptions = {
  917. font: fontSize + "px " + FONT_STYLE
  918. };
  919. (function() {
  920. var styleBox, cue;
  921. for (var i = 0; i < cues.length; i++) {
  922. cue = cues[i];
  923. // Compute the intial position and styles of the cue div.
  924. styleBox = new CueStyleBox(window, cue, styleOptions);
  925. paddedOverlay.appendChild(styleBox.div);
  926. // Move the cue div to it's correct line position.
  927. moveBoxToLinePosition(window, styleBox, containerBox, boxPositions);
  928. // Remember the computed div so that we don't have to recompute it later
  929. // if we don't have too.
  930. cue.displayState = styleBox.div;
  931. boxPositions.push(BoxPosition.getSimpleBoxPosition(styleBox));
  932. }
  933. })();
  934. };
  935. WebVTT.Parser = function(window, vttjs, decoder) {
  936. if (!decoder) {
  937. decoder = vttjs;
  938. vttjs = {};
  939. }
  940. if (!vttjs) {
  941. vttjs = {};
  942. }
  943. this.window = window;
  944. this.vttjs = vttjs;
  945. this.state = "INITIAL";
  946. this.buffer = "";
  947. this.decoder = decoder || new TextDecoder("utf8");
  948. this.regionList = [];
  949. };
  950. WebVTT.Parser.prototype = {
  951. // If the error is a ParsingError then report it to the consumer if
  952. // possible. If it's not a ParsingError then throw it like normal.
  953. reportOrThrowError: function(e) {
  954. if (e instanceof ParsingError) {
  955. this.onparsingerror && this.onparsingerror(e);
  956. } else {
  957. throw e;
  958. }
  959. },
  960. parse: function (data) {
  961. var self = this;
  962. // If there is no data then we won't decode it, but will just try to parse
  963. // whatever is in buffer already. This may occur in circumstances, for
  964. // example when flush() is called.
  965. if (data) {
  966. // Try to decode the data that we received.
  967. self.buffer += self.decoder.decode(data, {stream: true});
  968. }
  969. function collectNextLine() {
  970. var buffer = self.buffer;
  971. var pos = 0;
  972. while (pos < buffer.length && buffer[pos] !== '\r' && buffer[pos] !== '\n') {
  973. ++pos;
  974. }
  975. var line = buffer.substr(0, pos);
  976. // Advance the buffer early in case we fail below.
  977. if (buffer[pos] === '\r') {
  978. ++pos;
  979. }
  980. if (buffer[pos] === '\n') {
  981. ++pos;
  982. }
  983. self.buffer = buffer.substr(pos);
  984. return line;
  985. }
  986. // 3.4 WebVTT region and WebVTT region settings syntax
  987. function parseRegion(input) {
  988. var settings = new Settings();
  989. parseOptions(input, function (k, v) {
  990. switch (k) {
  991. case "id":
  992. settings.set(k, v);
  993. break;
  994. case "width":
  995. settings.percent(k, v);
  996. break;
  997. case "lines":
  998. settings.integer(k, v);
  999. break;
  1000. case "regionanchor":
  1001. case "viewportanchor":
  1002. var xy = v.split(',');
  1003. if (xy.length !== 2) {
  1004. break;
  1005. }
  1006. // We have to make sure both x and y parse, so use a temporary
  1007. // settings object here.
  1008. var anchor = new Settings();
  1009. anchor.percent("x", xy[0]);
  1010. anchor.percent("y", xy[1]);
  1011. if (!anchor.has("x") || !anchor.has("y")) {
  1012. break;
  1013. }
  1014. settings.set(k + "X", anchor.get("x"));
  1015. settings.set(k + "Y", anchor.get("y"));
  1016. break;
  1017. case "scroll":
  1018. settings.alt(k, v, ["up"]);
  1019. break;
  1020. }
  1021. }, /=/, /\s/);
  1022. // Create the region, using default values for any values that were not
  1023. // specified.
  1024. if (settings.has("id")) {
  1025. var region = new (self.vttjs.VTTRegion || self.window.VTTRegion)();
  1026. region.width = settings.get("width", 100);
  1027. region.lines = settings.get("lines", 3);
  1028. region.regionAnchorX = settings.get("regionanchorX", 0);
  1029. region.regionAnchorY = settings.get("regionanchorY", 100);
  1030. region.viewportAnchorX = settings.get("viewportanchorX", 0);
  1031. region.viewportAnchorY = settings.get("viewportanchorY", 100);
  1032. region.scroll = settings.get("scroll", "");
  1033. // Register the region.
  1034. self.onregion && self.onregion(region);
  1035. // Remember the VTTRegion for later in case we parse any VTTCues that
  1036. // reference it.
  1037. self.regionList.push({
  1038. id: settings.get("id"),
  1039. region: region
  1040. });
  1041. }
  1042. }
  1043. // draft-pantos-http-live-streaming-20
  1044. // https://tools.ietf.org/html/draft-pantos-http-live-streaming-20#section-3.5
  1045. // 3.5 WebVTT
  1046. function parseTimestampMap(input) {
  1047. var settings = new Settings();
  1048. parseOptions(input, function(k, v) {
  1049. switch(k) {
  1050. case "MPEGT":
  1051. settings.integer(k + 'S', v);
  1052. break;
  1053. case "LOCA":
  1054. settings.set(k + 'L', parseTimeStamp(v));
  1055. break;
  1056. }
  1057. }, /[^\d]:/, /,/);
  1058. self.ontimestampmap && self.ontimestampmap({
  1059. "MPEGTS": settings.get("MPEGTS"),
  1060. "LOCAL": settings.get("LOCAL")
  1061. });
  1062. }
  1063. // 3.2 WebVTT metadata header syntax
  1064. function parseHeader(input) {
  1065. if (input.match(/X-TIMESTAMP-MAP/)) {
  1066. // This line contains HLS X-TIMESTAMP-MAP metadata
  1067. parseOptions(input, function(k, v) {
  1068. switch(k) {
  1069. case "X-TIMESTAMP-MAP":
  1070. parseTimestampMap(v);
  1071. break;
  1072. }
  1073. }, /=/);
  1074. } else {
  1075. parseOptions(input, function (k, v) {
  1076. switch (k) {
  1077. case "Region":
  1078. // 3.3 WebVTT region metadata header syntax
  1079. parseRegion(v);
  1080. break;
  1081. }
  1082. }, /:/);
  1083. }
  1084. }
  1085. // 5.1 WebVTT file parsing.
  1086. try {
  1087. var line;
  1088. if (self.state === "INITIAL") {
  1089. // We can't start parsing until we have the first line.
  1090. if (!/\r\n|\n/.test(self.buffer)) {
  1091. return this;
  1092. }
  1093. line = collectNextLine();
  1094. var m = line.match(/^WEBVTT([ \t].*)?$/);
  1095. if (!m || !m[0]) {
  1096. throw new ParsingError(ParsingError.Errors.BadSignature);
  1097. }
  1098. self.state = "HEADER";
  1099. }
  1100. var alreadyCollectedLine = false;
  1101. while (self.buffer) {
  1102. // We can't parse a line until we have the full line.
  1103. if (!/\r\n|\n/.test(self.buffer)) {
  1104. return this;
  1105. }
  1106. if (!alreadyCollectedLine) {
  1107. line = collectNextLine();
  1108. } else {
  1109. alreadyCollectedLine = false;
  1110. }
  1111. switch (self.state) {
  1112. case "HEADER":
  1113. // 13-18 - Allow a header (metadata) under the WEBVTT line.
  1114. if (/:/.test(line)) {
  1115. parseHeader(line);
  1116. } else if (!line) {
  1117. // An empty line terminates the header and starts the body (cues).
  1118. self.state = "ID";
  1119. }
  1120. continue;
  1121. case "NOTE":
  1122. // Ignore NOTE blocks.
  1123. if (!line) {
  1124. self.state = "ID";
  1125. }
  1126. continue;
  1127. case "ID":
  1128. // Check for the start of NOTE blocks.
  1129. if (/^NOTE($|[ \t])/.test(line)) {
  1130. self.state = "NOTE";
  1131. break;
  1132. }
  1133. // 19-29 - Allow any number of line terminators, then initialize new cue values.
  1134. if (!line) {
  1135. continue;
  1136. }
  1137. self.cue = new (self.vttjs.VTTCue || self.window.VTTCue)(0, 0, "");
  1138. // Safari still uses the old middle value and won't accept center
  1139. try {
  1140. self.cue.align = "center";
  1141. } catch (e) {
  1142. self.cue.align = "middle";
  1143. }
  1144. self.state = "CUE";
  1145. // 30-39 - Check if self line contains an optional identifier or timing data.
  1146. if (line.indexOf("-->") === -1) {
  1147. self.cue.id = line;
  1148. continue;
  1149. }
  1150. // Process line as start of a cue.
  1151. /*falls through*/
  1152. case "CUE":
  1153. // 40 - Collect cue timings and settings.
  1154. try {
  1155. parseCue(line, self.cue, self.regionList);
  1156. } catch (e) {
  1157. self.reportOrThrowError(e);
  1158. // In case of an error ignore rest of the cue.
  1159. self.cue = null;
  1160. self.state = "BADCUE";
  1161. continue;
  1162. }
  1163. self.state = "CUETEXT";
  1164. continue;
  1165. case "CUETEXT":
  1166. var hasSubstring = line.indexOf("-->") !== -1;
  1167. // 34 - If we have an empty line then report the cue.
  1168. // 35 - If we have the special substring '-->' then report the cue,
  1169. // but do not collect the line as we need to process the current
  1170. // one as a new cue.
  1171. if (!line || hasSubstring && (alreadyCollectedLine = true)) {
  1172. // We are done parsing self cue.
  1173. self.oncue && self.oncue(self.cue);
  1174. self.cue = null;
  1175. self.state = "ID";
  1176. continue;
  1177. }
  1178. if (self.cue.text) {
  1179. self.cue.text += "\n";
  1180. }
  1181. self.cue.text += line.replace(/\u2028/g, '\n').replace(/u2029/g, '\n');
  1182. continue;
  1183. case "BADCUE": // BADCUE
  1184. // 54-62 - Collect and discard the remaining cue.
  1185. if (!line) {
  1186. self.state = "ID";
  1187. }
  1188. continue;
  1189. }
  1190. }
  1191. } catch (e) {
  1192. self.reportOrThrowError(e);
  1193. // If we are currently parsing a cue, report what we have.
  1194. if (self.state === "CUETEXT" && self.cue && self.oncue) {
  1195. self.oncue(self.cue);
  1196. }
  1197. self.cue = null;
  1198. // Enter BADWEBVTT state if header was not parsed correctly otherwise
  1199. // another exception occurred so enter BADCUE state.
  1200. self.state = self.state === "INITIAL" ? "BADWEBVTT" : "BADCUE";
  1201. }
  1202. return this;
  1203. },
  1204. flush: function () {
  1205. var self = this;
  1206. try {
  1207. // Finish decoding the stream.
  1208. self.buffer += self.decoder.decode();
  1209. // Synthesize the end of the current cue or region.
  1210. if (self.cue || self.state === "HEADER") {
  1211. self.buffer += "\n\n";
  1212. self.parse();
  1213. }
  1214. // If we've flushed, parsed, and we're still on the INITIAL state then
  1215. // that means we don't have enough of the stream to parse the first
  1216. // line.
  1217. if (self.state === "INITIAL") {
  1218. throw new ParsingError(ParsingError.Errors.BadSignature);
  1219. }
  1220. } catch(e) {
  1221. self.reportOrThrowError(e);
  1222. }
  1223. self.onflush && self.onflush();
  1224. return this;
  1225. }
  1226. };
  1227. module.exports = WebVTT;
  1228. },{"global/document":5}],2:[function(require,module,exports){
  1229. /**
  1230. * Copyright 2013 vtt.js Contributors
  1231. *
  1232. * Licensed under the Apache License, Version 2.0 (the "License");
  1233. * you may not use this file except in compliance with the License.
  1234. * You may obtain a copy of the License at
  1235. *
  1236. * http://www.apache.org/licenses/LICENSE-2.0
  1237. *
  1238. * Unless required by applicable law or agreed to in writing, software
  1239. * distributed under the License is distributed on an "AS IS" BASIS,
  1240. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1241. * See the License for the specific language governing permissions and
  1242. * limitations under the License.
  1243. */
  1244. var autoKeyword = "auto";
  1245. var directionSetting = {
  1246. "": 1,
  1247. "lr": 1,
  1248. "rl": 1
  1249. };
  1250. var alignSetting = {
  1251. "start": 1,
  1252. "center": 1,
  1253. "end": 1,
  1254. "left": 1,
  1255. "right": 1,
  1256. "auto": 1,
  1257. "line-left": 1,
  1258. "line-right": 1
  1259. };
  1260. function findDirectionSetting(value) {
  1261. if (typeof value !== "string") {
  1262. return false;
  1263. }
  1264. var dir = directionSetting[value.toLowerCase()];
  1265. return dir ? value.toLowerCase() : false;
  1266. }
  1267. function findAlignSetting(value) {
  1268. if (typeof value !== "string") {
  1269. return false;
  1270. }
  1271. var align = alignSetting[value.toLowerCase()];
  1272. return align ? value.toLowerCase() : false;
  1273. }
  1274. function VTTCue(startTime, endTime, text) {
  1275. /**
  1276. * Shim implementation specific properties. These properties are not in
  1277. * the spec.
  1278. */
  1279. // Lets us know when the VTTCue's data has changed in such a way that we need
  1280. // to recompute its display state. This lets us compute its display state
  1281. // lazily.
  1282. this.hasBeenReset = false;
  1283. /**
  1284. * VTTCue and TextTrackCue properties
  1285. * http://dev.w3.org/html5/webvtt/#vttcue-interface
  1286. */
  1287. var _id = "";
  1288. var _pauseOnExit = false;
  1289. var _startTime = startTime;
  1290. var _endTime = endTime;
  1291. var _text = text;
  1292. var _region = null;
  1293. var _vertical = "";
  1294. var _snapToLines = true;
  1295. var _line = "auto";
  1296. var _lineAlign = "start";
  1297. var _position = "auto";
  1298. var _positionAlign = "auto";
  1299. var _size = 100;
  1300. var _align = "center";
  1301. Object.defineProperties(this, {
  1302. "id": {
  1303. enumerable: true,
  1304. get: function() {
  1305. return _id;
  1306. },
  1307. set: function(value) {
  1308. _id = "" + value;
  1309. }
  1310. },
  1311. "pauseOnExit": {
  1312. enumerable: true,
  1313. get: function() {
  1314. return _pauseOnExit;
  1315. },
  1316. set: function(value) {
  1317. _pauseOnExit = !!value;
  1318. }
  1319. },
  1320. "startTime": {
  1321. enumerable: true,
  1322. get: function() {
  1323. return _startTime;
  1324. },
  1325. set: function(value) {
  1326. if (typeof value !== "number") {
  1327. throw new TypeError("Start time must be set to a number.");
  1328. }
  1329. _startTime = value;
  1330. this.hasBeenReset = true;
  1331. }
  1332. },
  1333. "endTime": {
  1334. enumerable: true,
  1335. get: function() {
  1336. return _endTime;
  1337. },
  1338. set: function(value) {
  1339. if (typeof value !== "number") {
  1340. throw new TypeError("End time must be set to a number.");
  1341. }
  1342. _endTime = value;
  1343. this.hasBeenReset = true;
  1344. }
  1345. },
  1346. "text": {
  1347. enumerable: true,
  1348. get: function() {
  1349. return _text;
  1350. },
  1351. set: function(value) {
  1352. _text = "" + value;
  1353. this.hasBeenReset = true;
  1354. }
  1355. },
  1356. "region": {
  1357. enumerable: true,
  1358. get: function() {
  1359. return _region;
  1360. },
  1361. set: function(value) {
  1362. _region = value;
  1363. this.hasBeenReset = true;
  1364. }
  1365. },
  1366. "vertical": {
  1367. enumerable: true,
  1368. get: function() {
  1369. return _vertical;
  1370. },
  1371. set: function(value) {
  1372. var setting = findDirectionSetting(value);
  1373. // Have to check for false because the setting an be an empty string.
  1374. if (setting === false) {
  1375. throw new SyntaxError("Vertical: an invalid or illegal direction string was specified.");
  1376. }
  1377. _vertical = setting;
  1378. this.hasBeenReset = true;
  1379. }
  1380. },
  1381. "snapToLines": {
  1382. enumerable: true,
  1383. get: function() {
  1384. return _snapToLines;
  1385. },
  1386. set: function(value) {
  1387. _snapToLines = !!value;
  1388. this.hasBeenReset = true;
  1389. }
  1390. },
  1391. "line": {
  1392. enumerable: true,
  1393. get: function() {
  1394. return _line;
  1395. },
  1396. set: function(value) {
  1397. if (typeof value !== "number" && value !== autoKeyword) {
  1398. throw new SyntaxError("Line: an invalid number or illegal string was specified.");
  1399. }
  1400. _line = value;
  1401. this.hasBeenReset = true;
  1402. }
  1403. },
  1404. "lineAlign": {
  1405. enumerable: true,
  1406. get: function() {
  1407. return _lineAlign;
  1408. },
  1409. set: function(value) {
  1410. var setting = findAlignSetting(value);
  1411. if (!setting) {
  1412. console.warn("lineAlign: an invalid or illegal string was specified.");
  1413. } else {
  1414. _lineAlign = setting;
  1415. this.hasBeenReset = true;
  1416. }
  1417. }
  1418. },
  1419. "position": {
  1420. enumerable: true,
  1421. get: function() {
  1422. return _position;
  1423. },
  1424. set: function(value) {
  1425. if (value < 0 || value > 100) {
  1426. throw new Error("Position must be between 0 and 100.");
  1427. }
  1428. _position = value;
  1429. this.hasBeenReset = true;
  1430. }
  1431. },
  1432. "positionAlign": {
  1433. enumerable: true,
  1434. get: function() {
  1435. return _positionAlign;
  1436. },
  1437. set: function(value) {
  1438. var setting = findAlignSetting(value);
  1439. if (!setting) {
  1440. console.warn("positionAlign: an invalid or illegal string was specified.");
  1441. } else {
  1442. _positionAlign = setting;
  1443. this.hasBeenReset = true;
  1444. }
  1445. }
  1446. },
  1447. "size": {
  1448. enumerable: true,
  1449. get: function() {
  1450. return _size;
  1451. },
  1452. set: function(value) {
  1453. if (value < 0 || value > 100) {
  1454. throw new Error("Size must be between 0 and 100.");
  1455. }
  1456. _size = value;
  1457. this.hasBeenReset = true;
  1458. }
  1459. },
  1460. "align": {
  1461. enumerable: true,
  1462. get: function() {
  1463. return _align;
  1464. },
  1465. set: function(value) {
  1466. var setting = findAlignSetting(value);
  1467. if (!setting) {
  1468. throw new SyntaxError("align: an invalid or illegal alignment string was specified.");
  1469. }
  1470. _align = setting;
  1471. this.hasBeenReset = true;
  1472. }
  1473. }
  1474. });
  1475. /**
  1476. * Other <track> spec defined properties
  1477. */
  1478. // http://www.whatwg.org/specs/web-apps/current-work/multipage/the-video-element.html#text-track-cue-display-state
  1479. this.displayState = undefined;
  1480. }
  1481. /**
  1482. * VTTCue methods
  1483. */
  1484. VTTCue.prototype.getCueAsHTML = function() {
  1485. // Assume WebVTT.convertCueToDOMTree is on the global.
  1486. return WebVTT.convertCueToDOMTree(window, this.text);
  1487. };
  1488. module.exports = VTTCue;
  1489. },{}],3:[function(require,module,exports){
  1490. /**
  1491. * Copyright 2013 vtt.js Contributors
  1492. *
  1493. * Licensed under the Apache License, Version 2.0 (the "License");
  1494. * you may not use this file except in compliance with the License.
  1495. * You may obtain a copy of the License at
  1496. *
  1497. * http://www.apache.org/licenses/LICENSE-2.0
  1498. *
  1499. * Unless required by applicable law or agreed to in writing, software
  1500. * distributed under the License is distributed on an "AS IS" BASIS,
  1501. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1502. * See the License for the specific language governing permissions and
  1503. * limitations under the License.
  1504. */
  1505. var scrollSetting = {
  1506. "": true,
  1507. "up": true
  1508. };
  1509. function findScrollSetting(value) {
  1510. if (typeof value !== "string") {
  1511. return false;
  1512. }
  1513. var scroll = scrollSetting[value.toLowerCase()];
  1514. return scroll ? value.toLowerCase() : false;
  1515. }
  1516. function isValidPercentValue(value) {
  1517. return typeof value === "number" && (value >= 0 && value <= 100);
  1518. }
  1519. // VTTRegion shim http://dev.w3.org/html5/webvtt/#vttregion-interface
  1520. function VTTRegion() {
  1521. var _width = 100;
  1522. var _lines = 3;
  1523. var _regionAnchorX = 0;
  1524. var _regionAnchorY = 100;
  1525. var _viewportAnchorX = 0;
  1526. var _viewportAnchorY = 100;
  1527. var _scroll = "";
  1528. Object.defineProperties(this, {
  1529. "width": {
  1530. enumerable: true,
  1531. get: function() {
  1532. return _width;
  1533. },
  1534. set: function(value) {
  1535. if (!isValidPercentValue(value)) {
  1536. throw new Error("Width must be between 0 and 100.");
  1537. }
  1538. _width = value;
  1539. }
  1540. },
  1541. "lines": {
  1542. enumerable: true,
  1543. get: function() {
  1544. return _lines;
  1545. },
  1546. set: function(value) {
  1547. if (typeof value !== "number") {
  1548. throw new TypeError("Lines must be set to a number.");
  1549. }
  1550. _lines = value;
  1551. }
  1552. },
  1553. "regionAnchorY": {
  1554. enumerable: true,
  1555. get: function() {
  1556. return _regionAnchorY;
  1557. },
  1558. set: function(value) {
  1559. if (!isValidPercentValue(value)) {
  1560. throw new Error("RegionAnchorX must be between 0 and 100.");
  1561. }
  1562. _regionAnchorY = value;
  1563. }
  1564. },
  1565. "regionAnchorX": {
  1566. enumerable: true,
  1567. get: function() {
  1568. return _regionAnchorX;
  1569. },
  1570. set: function(value) {
  1571. if(!isValidPercentValue(value)) {
  1572. throw new Error("RegionAnchorY must be between 0 and 100.");
  1573. }
  1574. _regionAnchorX = value;
  1575. }
  1576. },
  1577. "viewportAnchorY": {
  1578. enumerable: true,
  1579. get: function() {
  1580. return _viewportAnchorY;
  1581. },
  1582. set: function(value) {
  1583. if (!isValidPercentValue(value)) {
  1584. throw new Error("ViewportAnchorY must be between 0 and 100.");
  1585. }
  1586. _viewportAnchorY = value;
  1587. }
  1588. },
  1589. "viewportAnchorX": {
  1590. enumerable: true,
  1591. get: function() {
  1592. return _viewportAnchorX;
  1593. },
  1594. set: function(value) {
  1595. if (!isValidPercentValue(value)) {
  1596. throw new Error("ViewportAnchorX must be between 0 and 100.");
  1597. }
  1598. _viewportAnchorX = value;
  1599. }
  1600. },
  1601. "scroll": {
  1602. enumerable: true,
  1603. get: function() {
  1604. return _scroll;
  1605. },
  1606. set: function(value) {
  1607. var setting = findScrollSetting(value);
  1608. // Have to check for false as an empty string is a legal value.
  1609. if (setting === false) {
  1610. console.warn("Scroll: an invalid or illegal string was specified.");
  1611. } else {
  1612. _scroll = setting;
  1613. }
  1614. }
  1615. }
  1616. });
  1617. }
  1618. module.exports = VTTRegion;
  1619. },{}],4:[function(require,module,exports){
  1620. },{}],5:[function(require,module,exports){
  1621. (function (global){
  1622. var topLevel = typeof global !== 'undefined' ? global :
  1623. typeof window !== 'undefined' ? window : {}
  1624. var minDoc = require('min-document');
  1625. var doccy;
  1626. if (typeof document !== 'undefined') {
  1627. doccy = document;
  1628. } else {
  1629. doccy = topLevel['__GLOBAL_DOCUMENT_CACHE@4'];
  1630. if (!doccy) {
  1631. doccy = topLevel['__GLOBAL_DOCUMENT_CACHE@4'] = minDoc;
  1632. }
  1633. }
  1634. module.exports = doccy;
  1635. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  1636. },{"min-document":4}],6:[function(require,module,exports){
  1637. (function (global){
  1638. var win;
  1639. if (typeof window !== "undefined") {
  1640. win = window;
  1641. } else if (typeof global !== "undefined") {
  1642. win = global;
  1643. } else if (typeof self !== "undefined"){
  1644. win = self;
  1645. } else {
  1646. win = {};
  1647. }
  1648. module.exports = win;
  1649. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  1650. },{}],7:[function(require,module,exports){
  1651. /**
  1652. * Copyright 2013 vtt.js Contributors
  1653. *
  1654. * Licensed under the Apache License, Version 2.0 (the "License");
  1655. * you may not use this file except in compliance with the License.
  1656. * You may obtain a copy of the License at
  1657. *
  1658. * http://www.apache.org/licenses/LICENSE-2.0
  1659. *
  1660. * Unless required by applicable law or agreed to in writing, software
  1661. * distributed under the License is distributed on an "AS IS" BASIS,
  1662. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1663. * See the License for the specific language governing permissions and
  1664. * limitations under the License.
  1665. */
  1666. // Default exports for Node. Export the extended versions of VTTCue and
  1667. // VTTRegion in Node since we likely want the capability to convert back and
  1668. // forth between JSON. If we don't then it's not that big of a deal since we're
  1669. // off browser.
  1670. var window = require('global/window');
  1671. var vttjs = module.exports = {
  1672. WebVTT: require("./vtt.js"),
  1673. VTTCue: require("./vttcue.js"),
  1674. VTTRegion: require("./vttregion.js")
  1675. };
  1676. window.vttjs = vttjs;
  1677. window.WebVTT = vttjs.WebVTT;
  1678. var cueShim = vttjs.VTTCue;
  1679. var regionShim = vttjs.VTTRegion;
  1680. var nativeVTTCue = window.VTTCue;
  1681. var nativeVTTRegion = window.VTTRegion;
  1682. vttjs.shim = function() {
  1683. window.VTTCue = cueShim;
  1684. window.VTTRegion = regionShim;
  1685. };
  1686. vttjs.restore = function() {
  1687. window.VTTCue = nativeVTTCue;
  1688. window.VTTRegion = nativeVTTRegion;
  1689. };
  1690. if (!window.VTTCue) {
  1691. vttjs.shim();
  1692. }
  1693. },{"./vtt.js":1,"./vttcue.js":2,"./vttregion.js":3,"global/window":6}]},{},[7])(7)
  1694. });