vtt.js 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351
  1. /**
  2. * Copyright 2013 vtt.js Contributors
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. /* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
  17. /* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */
  18. var document = require('global/document');
  19. var _objCreate = Object.create || (function() {
  20. function F() {}
  21. return function(o) {
  22. if (arguments.length !== 1) {
  23. throw new Error('Object.create shim only accepts one parameter.');
  24. }
  25. F.prototype = o;
  26. return new F();
  27. };
  28. })();
  29. // Creates a new ParserError object from an errorData object. The errorData
  30. // object should have default code and message properties. The default message
  31. // property can be overriden by passing in a message parameter.
  32. // See ParsingError.Errors below for acceptable errors.
  33. function ParsingError(errorData, message) {
  34. this.name = "ParsingError";
  35. this.code = errorData.code;
  36. this.message = message || errorData.message;
  37. }
  38. ParsingError.prototype = _objCreate(Error.prototype);
  39. ParsingError.prototype.constructor = ParsingError;
  40. // ParsingError metadata for acceptable ParsingErrors.
  41. ParsingError.Errors = {
  42. BadSignature: {
  43. code: 0,
  44. message: "Malformed WebVTT signature."
  45. },
  46. BadTimeStamp: {
  47. code: 1,
  48. message: "Malformed time stamp."
  49. }
  50. };
  51. // Try to parse input as a time stamp.
  52. function parseTimeStamp(input) {
  53. function computeSeconds(h, m, s, f) {
  54. return (h | 0) * 3600 + (m | 0) * 60 + (s | 0) + (f | 0) / 1000;
  55. }
  56. var m = input.match(/^(\d+):(\d{1,2})(:\d{1,2})?\.(\d{3})/);
  57. if (!m) {
  58. return null;
  59. }
  60. if (m[3]) {
  61. // Timestamp takes the form of [hours]:[minutes]:[seconds].[milliseconds]
  62. return computeSeconds(m[1], m[2], m[3].replace(":", ""), m[4]);
  63. } else if (m[1] > 59) {
  64. // Timestamp takes the form of [hours]:[minutes].[milliseconds]
  65. // First position is hours as it's over 59.
  66. return computeSeconds(m[1], m[2], 0, m[4]);
  67. } else {
  68. // Timestamp takes the form of [minutes]:[seconds].[milliseconds]
  69. return computeSeconds(0, m[1], m[2], m[4]);
  70. }
  71. }
  72. // A settings object holds key/value pairs and will ignore anything but the first
  73. // assignment to a specific key.
  74. function Settings() {
  75. this.values = _objCreate(null);
  76. }
  77. Settings.prototype = {
  78. // Only accept the first assignment to any key.
  79. set: function(k, v) {
  80. if (!this.get(k) && v !== "") {
  81. this.values[k] = v;
  82. }
  83. },
  84. // Return the value for a key, or a default value.
  85. // If 'defaultKey' is passed then 'dflt' is assumed to be an object with
  86. // a number of possible default values as properties where 'defaultKey' is
  87. // the key of the property that will be chosen; otherwise it's assumed to be
  88. // a single value.
  89. get: function(k, dflt, defaultKey) {
  90. if (defaultKey) {
  91. return this.has(k) ? this.values[k] : dflt[defaultKey];
  92. }
  93. return this.has(k) ? this.values[k] : dflt;
  94. },
  95. // Check whether we have a value for a key.
  96. has: function(k) {
  97. return k in this.values;
  98. },
  99. // Accept a setting if its one of the given alternatives.
  100. alt: function(k, v, a) {
  101. for (var n = 0; n < a.length; ++n) {
  102. if (v === a[n]) {
  103. this.set(k, v);
  104. break;
  105. }
  106. }
  107. },
  108. // Accept a setting if its a valid (signed) integer.
  109. integer: function(k, v) {
  110. if (/^-?\d+$/.test(v)) { // integer
  111. this.set(k, parseInt(v, 10));
  112. }
  113. },
  114. // Accept a setting if its a valid percentage.
  115. percent: function(k, v) {
  116. var m;
  117. if ((m = v.match(/^([\d]{1,3})(\.[\d]*)?%$/))) {
  118. v = parseFloat(v);
  119. if (v >= 0 && v <= 100) {
  120. this.set(k, v);
  121. return true;
  122. }
  123. }
  124. return false;
  125. }
  126. };
  127. // Helper function to parse input into groups separated by 'groupDelim', and
  128. // interprete each group as a key/value pair separated by 'keyValueDelim'.
  129. function parseOptions(input, callback, keyValueDelim, groupDelim) {
  130. var groups = groupDelim ? input.split(groupDelim) : [input];
  131. for (var i in groups) {
  132. if (typeof groups[i] !== "string") {
  133. continue;
  134. }
  135. var kv = groups[i].split(keyValueDelim);
  136. if (kv.length !== 2) {
  137. continue;
  138. }
  139. var k = kv[0].trim();
  140. var v = kv[1].trim();
  141. callback(k, v);
  142. }
  143. }
  144. function parseCue(input, cue, regionList) {
  145. // Remember the original input if we need to throw an error.
  146. var oInput = input;
  147. // 4.1 WebVTT timestamp
  148. function consumeTimeStamp() {
  149. var ts = parseTimeStamp(input);
  150. if (ts === null) {
  151. throw new ParsingError(ParsingError.Errors.BadTimeStamp,
  152. "Malformed timestamp: " + oInput);
  153. }
  154. // Remove time stamp from input.
  155. input = input.replace(/^[^\sa-zA-Z-]+/, "");
  156. return ts;
  157. }
  158. // 4.4.2 WebVTT cue settings
  159. function consumeCueSettings(input, cue) {
  160. var settings = new Settings();
  161. parseOptions(input, function (k, v) {
  162. switch (k) {
  163. case "region":
  164. // Find the last region we parsed with the same region id.
  165. for (var i = regionList.length - 1; i >= 0; i--) {
  166. if (regionList[i].id === v) {
  167. settings.set(k, regionList[i].region);
  168. break;
  169. }
  170. }
  171. break;
  172. case "vertical":
  173. settings.alt(k, v, ["rl", "lr"]);
  174. break;
  175. case "line":
  176. var vals = v.split(","),
  177. vals0 = vals[0];
  178. settings.integer(k, vals0);
  179. settings.percent(k, vals0) ? settings.set("snapToLines", false) : null;
  180. settings.alt(k, vals0, ["auto"]);
  181. if (vals.length === 2) {
  182. settings.alt("lineAlign", vals[1], ["start", "center", "end"]);
  183. }
  184. break;
  185. case "position":
  186. vals = v.split(",");
  187. settings.percent(k, vals[0]);
  188. if (vals.length === 2) {
  189. settings.alt("positionAlign", vals[1], ["start", "center", "end"]);
  190. }
  191. break;
  192. case "size":
  193. settings.percent(k, v);
  194. break;
  195. case "align":
  196. settings.alt(k, v, ["start", "center", "end", "left", "right"]);
  197. break;
  198. }
  199. }, /:/, /\s/);
  200. // Apply default values for any missing fields.
  201. cue.region = settings.get("region", null);
  202. cue.vertical = settings.get("vertical", "");
  203. try {
  204. cue.line = settings.get("line", "auto");
  205. } catch (e) {}
  206. cue.lineAlign = settings.get("lineAlign", "start");
  207. cue.snapToLines = settings.get("snapToLines", true);
  208. cue.size = settings.get("size", 100);
  209. // Safari still uses the old middle value and won't accept center
  210. try {
  211. cue.align = settings.get("align", "center");
  212. } catch (e) {
  213. cue.align = settings.get("align", "middle");
  214. }
  215. try {
  216. cue.position = settings.get("position", "auto");
  217. } catch (e) {
  218. cue.position = settings.get("position", {
  219. start: 0,
  220. left: 0,
  221. center: 50,
  222. middle: 50,
  223. end: 100,
  224. right: 100
  225. }, cue.align);
  226. }
  227. cue.positionAlign = settings.get("positionAlign", {
  228. start: "start",
  229. left: "start",
  230. center: "center",
  231. middle: "center",
  232. end: "end",
  233. right: "end"
  234. }, cue.align);
  235. }
  236. function skipWhitespace() {
  237. input = input.replace(/^\s+/, "");
  238. }
  239. // 4.1 WebVTT cue timings.
  240. skipWhitespace();
  241. cue.startTime = consumeTimeStamp(); // (1) collect cue start time
  242. skipWhitespace();
  243. if (input.substr(0, 3) !== "-->") { // (3) next characters must match "-->"
  244. throw new ParsingError(ParsingError.Errors.BadTimeStamp,
  245. "Malformed time stamp (time stamps must be separated by '-->'): " +
  246. oInput);
  247. }
  248. input = input.substr(3);
  249. skipWhitespace();
  250. cue.endTime = consumeTimeStamp(); // (5) collect cue end time
  251. // 4.1 WebVTT cue settings list.
  252. skipWhitespace();
  253. consumeCueSettings(input, cue);
  254. }
  255. // When evaluating this file as part of a Webpack bundle for server
  256. // side rendering, `document` is an empty object.
  257. var TEXTAREA_ELEMENT = document.createElement && document.createElement("textarea");
  258. var TAG_NAME = {
  259. c: "span",
  260. i: "i",
  261. b: "b",
  262. u: "u",
  263. ruby: "ruby",
  264. rt: "rt",
  265. v: "span",
  266. lang: "span"
  267. };
  268. // 5.1 default text color
  269. // 5.2 default text background color is equivalent to text color with bg_ prefix
  270. var DEFAULT_COLOR_CLASS = {
  271. white: 'rgba(255,255,255,1)',
  272. lime: 'rgba(0,255,0,1)',
  273. cyan: 'rgba(0,255,255,1)',
  274. red: 'rgba(255,0,0,1)',
  275. yellow: 'rgba(255,255,0,1)',
  276. magenta: 'rgba(255,0,255,1)',
  277. blue: 'rgba(0,0,255,1)',
  278. black: 'rgba(0,0,0,1)'
  279. };
  280. var TAG_ANNOTATION = {
  281. v: "title",
  282. lang: "lang"
  283. };
  284. var NEEDS_PARENT = {
  285. rt: "ruby"
  286. };
  287. // Parse content into a document fragment.
  288. function parseContent(window, input) {
  289. function nextToken() {
  290. // Check for end-of-string.
  291. if (!input) {
  292. return null;
  293. }
  294. // Consume 'n' characters from the input.
  295. function consume(result) {
  296. input = input.substr(result.length);
  297. return result;
  298. }
  299. var m = input.match(/^([^<]*)(<[^>]*>?)?/);
  300. // If there is some text before the next tag, return it, otherwise return
  301. // the tag.
  302. return consume(m[1] ? m[1] : m[2]);
  303. }
  304. function unescape(s) {
  305. TEXTAREA_ELEMENT.innerHTML = s;
  306. s = TEXTAREA_ELEMENT.textContent;
  307. TEXTAREA_ELEMENT.textContent = "";
  308. return s;
  309. }
  310. function shouldAdd(current, element) {
  311. return !NEEDS_PARENT[element.localName] ||
  312. NEEDS_PARENT[element.localName] === current.localName;
  313. }
  314. // Create an element for this tag.
  315. function createElement(type, annotation) {
  316. var tagName = TAG_NAME[type];
  317. if (!tagName) {
  318. return null;
  319. }
  320. var element = window.document.createElement(tagName);
  321. var name = TAG_ANNOTATION[type];
  322. if (name && annotation) {
  323. element[name] = annotation.trim();
  324. }
  325. return element;
  326. }
  327. var rootDiv = window.document.createElement("div"),
  328. current = rootDiv,
  329. t,
  330. tagStack = [];
  331. while ((t = nextToken()) !== null) {
  332. if (t[0] === '<') {
  333. if (t[1] === "/") {
  334. // If the closing tag matches, move back up to the parent node.
  335. if (tagStack.length &&
  336. tagStack[tagStack.length - 1] === t.substr(2).replace(">", "")) {
  337. tagStack.pop();
  338. current = current.parentNode;
  339. }
  340. // Otherwise just ignore the end tag.
  341. continue;
  342. }
  343. var ts = parseTimeStamp(t.substr(1, t.length - 2));
  344. var node;
  345. if (ts) {
  346. // Timestamps are lead nodes as well.
  347. node = window.document.createProcessingInstruction("timestamp", ts);
  348. current.appendChild(node);
  349. continue;
  350. }
  351. var m = t.match(/^<([^.\s/0-9>]+)(\.[^\s\\>]+)?([^>\\]+)?(\\?)>?$/);
  352. // If we can't parse the tag, skip to the next tag.
  353. if (!m) {
  354. continue;
  355. }
  356. // Try to construct an element, and ignore the tag if we couldn't.
  357. node = createElement(m[1], m[3]);
  358. if (!node) {
  359. continue;
  360. }
  361. // Determine if the tag should be added based on the context of where it
  362. // is placed in the cuetext.
  363. if (!shouldAdd(current, node)) {
  364. continue;
  365. }
  366. // Set the class list (as a list of classes, separated by space).
  367. if (m[2]) {
  368. var classes = m[2].split('.');
  369. classes.forEach(function(cl) {
  370. var bgColor = /^bg_/.test(cl);
  371. // slice out `bg_` if it's a background color
  372. var colorName = bgColor ? cl.slice(3) : cl;
  373. if (DEFAULT_COLOR_CLASS.hasOwnProperty(colorName)) {
  374. var propName = bgColor ? 'background-color' : 'color';
  375. var propValue = DEFAULT_COLOR_CLASS[colorName];
  376. node.style[propName] = propValue;
  377. }
  378. });
  379. node.className = classes.join(' ');
  380. }
  381. // Append the node to the current node, and enter the scope of the new
  382. // node.
  383. tagStack.push(m[1]);
  384. current.appendChild(node);
  385. current = node;
  386. continue;
  387. }
  388. // Text nodes are leaf nodes.
  389. current.appendChild(window.document.createTextNode(unescape(t)));
  390. }
  391. return rootDiv;
  392. }
  393. // This is a list of all the Unicode characters that have a strong
  394. // right-to-left category. What this means is that these characters are
  395. // written right-to-left for sure. It was generated by pulling all the strong
  396. // right-to-left characters out of the Unicode data table. That table can
  397. // found at: http://www.unicode.org/Public/UNIDATA/UnicodeData.txt
  398. var strongRTLRanges = [[0x5be, 0x5be], [0x5c0, 0x5c0], [0x5c3, 0x5c3], [0x5c6, 0x5c6],
  399. [0x5d0, 0x5ea], [0x5f0, 0x5f4], [0x608, 0x608], [0x60b, 0x60b], [0x60d, 0x60d],
  400. [0x61b, 0x61b], [0x61e, 0x64a], [0x66d, 0x66f], [0x671, 0x6d5], [0x6e5, 0x6e6],
  401. [0x6ee, 0x6ef], [0x6fa, 0x70d], [0x70f, 0x710], [0x712, 0x72f], [0x74d, 0x7a5],
  402. [0x7b1, 0x7b1], [0x7c0, 0x7ea], [0x7f4, 0x7f5], [0x7fa, 0x7fa], [0x800, 0x815],
  403. [0x81a, 0x81a], [0x824, 0x824], [0x828, 0x828], [0x830, 0x83e], [0x840, 0x858],
  404. [0x85e, 0x85e], [0x8a0, 0x8a0], [0x8a2, 0x8ac], [0x200f, 0x200f],
  405. [0xfb1d, 0xfb1d], [0xfb1f, 0xfb28], [0xfb2a, 0xfb36], [0xfb38, 0xfb3c],
  406. [0xfb3e, 0xfb3e], [0xfb40, 0xfb41], [0xfb43, 0xfb44], [0xfb46, 0xfbc1],
  407. [0xfbd3, 0xfd3d], [0xfd50, 0xfd8f], [0xfd92, 0xfdc7], [0xfdf0, 0xfdfc],
  408. [0xfe70, 0xfe74], [0xfe76, 0xfefc], [0x10800, 0x10805], [0x10808, 0x10808],
  409. [0x1080a, 0x10835], [0x10837, 0x10838], [0x1083c, 0x1083c], [0x1083f, 0x10855],
  410. [0x10857, 0x1085f], [0x10900, 0x1091b], [0x10920, 0x10939], [0x1093f, 0x1093f],
  411. [0x10980, 0x109b7], [0x109be, 0x109bf], [0x10a00, 0x10a00], [0x10a10, 0x10a13],
  412. [0x10a15, 0x10a17], [0x10a19, 0x10a33], [0x10a40, 0x10a47], [0x10a50, 0x10a58],
  413. [0x10a60, 0x10a7f], [0x10b00, 0x10b35], [0x10b40, 0x10b55], [0x10b58, 0x10b72],
  414. [0x10b78, 0x10b7f], [0x10c00, 0x10c48], [0x1ee00, 0x1ee03], [0x1ee05, 0x1ee1f],
  415. [0x1ee21, 0x1ee22], [0x1ee24, 0x1ee24], [0x1ee27, 0x1ee27], [0x1ee29, 0x1ee32],
  416. [0x1ee34, 0x1ee37], [0x1ee39, 0x1ee39], [0x1ee3b, 0x1ee3b], [0x1ee42, 0x1ee42],
  417. [0x1ee47, 0x1ee47], [0x1ee49, 0x1ee49], [0x1ee4b, 0x1ee4b], [0x1ee4d, 0x1ee4f],
  418. [0x1ee51, 0x1ee52], [0x1ee54, 0x1ee54], [0x1ee57, 0x1ee57], [0x1ee59, 0x1ee59],
  419. [0x1ee5b, 0x1ee5b], [0x1ee5d, 0x1ee5d], [0x1ee5f, 0x1ee5f], [0x1ee61, 0x1ee62],
  420. [0x1ee64, 0x1ee64], [0x1ee67, 0x1ee6a], [0x1ee6c, 0x1ee72], [0x1ee74, 0x1ee77],
  421. [0x1ee79, 0x1ee7c], [0x1ee7e, 0x1ee7e], [0x1ee80, 0x1ee89], [0x1ee8b, 0x1ee9b],
  422. [0x1eea1, 0x1eea3], [0x1eea5, 0x1eea9], [0x1eeab, 0x1eebb], [0x10fffd, 0x10fffd]];
  423. function isStrongRTLChar(charCode) {
  424. for (var i = 0; i < strongRTLRanges.length; i++) {
  425. var currentRange = strongRTLRanges[i];
  426. if (charCode >= currentRange[0] && charCode <= currentRange[1]) {
  427. return true;
  428. }
  429. }
  430. return false;
  431. }
  432. function determineBidi(cueDiv) {
  433. var nodeStack = [],
  434. text = "",
  435. charCode;
  436. if (!cueDiv || !cueDiv.childNodes) {
  437. return "ltr";
  438. }
  439. function pushNodes(nodeStack, node) {
  440. for (var i = node.childNodes.length - 1; i >= 0; i--) {
  441. nodeStack.push(node.childNodes[i]);
  442. }
  443. }
  444. function nextTextNode(nodeStack) {
  445. if (!nodeStack || !nodeStack.length) {
  446. return null;
  447. }
  448. var node = nodeStack.pop(),
  449. text = node.textContent || node.innerText;
  450. if (text) {
  451. // TODO: This should match all unicode type B characters (paragraph
  452. // separator characters). See issue #115.
  453. var m = text.match(/^.*(\n|\r)/);
  454. if (m) {
  455. nodeStack.length = 0;
  456. return m[0];
  457. }
  458. return text;
  459. }
  460. if (node.tagName === "ruby") {
  461. return nextTextNode(nodeStack);
  462. }
  463. if (node.childNodes) {
  464. pushNodes(nodeStack, node);
  465. return nextTextNode(nodeStack);
  466. }
  467. }
  468. pushNodes(nodeStack, cueDiv);
  469. while ((text = nextTextNode(nodeStack))) {
  470. for (var i = 0; i < text.length; i++) {
  471. charCode = text.charCodeAt(i);
  472. if (isStrongRTLChar(charCode)) {
  473. return "rtl";
  474. }
  475. }
  476. }
  477. return "ltr";
  478. }
  479. function computeLinePos(cue) {
  480. if (typeof cue.line === "number" &&
  481. (cue.snapToLines || (cue.line >= 0 && cue.line <= 100))) {
  482. return cue.line;
  483. }
  484. if (!cue.track || !cue.track.textTrackList ||
  485. !cue.track.textTrackList.mediaElement) {
  486. return -1;
  487. }
  488. var track = cue.track,
  489. trackList = track.textTrackList,
  490. count = 0;
  491. for (var i = 0; i < trackList.length && trackList[i] !== track; i++) {
  492. if (trackList[i].mode === "showing") {
  493. count++;
  494. }
  495. }
  496. return ++count * -1;
  497. }
  498. function StyleBox() {
  499. }
  500. // Apply styles to a div. If there is no div passed then it defaults to the
  501. // div on 'this'.
  502. StyleBox.prototype.applyStyles = function(styles, div) {
  503. div = div || this.div;
  504. for (var prop in styles) {
  505. if (styles.hasOwnProperty(prop)) {
  506. div.style[prop] = styles[prop];
  507. }
  508. }
  509. };
  510. StyleBox.prototype.formatStyle = function(val, unit) {
  511. return val === 0 ? 0 : val + unit;
  512. };
  513. // Constructs the computed display state of the cue (a div). Places the div
  514. // into the overlay which should be a block level element (usually a div).
  515. function CueStyleBox(window, cue, styleOptions) {
  516. StyleBox.call(this);
  517. this.cue = cue;
  518. // Parse our cue's text into a DOM tree rooted at 'cueDiv'. This div will
  519. // have inline positioning and will function as the cue background box.
  520. this.cueDiv = parseContent(window, cue.text);
  521. var styles = {
  522. color: "rgba(255, 255, 255, 1)",
  523. backgroundColor: "rgba(0, 0, 0, 0.8)",
  524. position: "relative",
  525. left: 0,
  526. right: 0,
  527. top: 0,
  528. bottom: 0,
  529. display: "inline",
  530. writingMode: cue.vertical === "" ? "horizontal-tb"
  531. : cue.vertical === "lr" ? "vertical-lr"
  532. : "vertical-rl",
  533. unicodeBidi: "plaintext"
  534. };
  535. this.applyStyles(styles, this.cueDiv);
  536. // Create an absolutely positioned div that will be used to position the cue
  537. // div. Note, all WebVTT cue-setting alignments are equivalent to the CSS
  538. // mirrors of them except middle instead of center on Safari.
  539. this.div = window.document.createElement("div");
  540. styles = {
  541. direction: determineBidi(this.cueDiv),
  542. writingMode: cue.vertical === "" ? "horizontal-tb"
  543. : cue.vertical === "lr" ? "vertical-lr"
  544. : "vertical-rl",
  545. unicodeBidi: "plaintext",
  546. textAlign: cue.align === "middle" ? "center" : cue.align,
  547. font: styleOptions.font,
  548. whiteSpace: "pre-line",
  549. position: "absolute"
  550. };
  551. this.applyStyles(styles);
  552. this.div.appendChild(this.cueDiv);
  553. // Calculate the distance from the reference edge of the viewport to the text
  554. // position of the cue box. The reference edge will be resolved later when
  555. // the box orientation styles are applied.
  556. var textPos = 0;
  557. switch (cue.positionAlign) {
  558. case "start":
  559. case "line-left":
  560. textPos = cue.position;
  561. break;
  562. case "center":
  563. textPos = cue.position - (cue.size / 2);
  564. break;
  565. case "end":
  566. case "line-right":
  567. textPos = cue.position - cue.size;
  568. break;
  569. }
  570. // Horizontal box orientation; textPos is the distance from the left edge of the
  571. // area to the left edge of the box and cue.size is the distance extending to
  572. // the right from there.
  573. if (cue.vertical === "") {
  574. this.applyStyles({
  575. left: this.formatStyle(textPos, "%"),
  576. width: this.formatStyle(cue.size, "%")
  577. });
  578. // Vertical box orientation; textPos is the distance from the top edge of the
  579. // area to the top edge of the box and cue.size is the height extending
  580. // downwards from there.
  581. } else {
  582. this.applyStyles({
  583. top: this.formatStyle(textPos, "%"),
  584. height: this.formatStyle(cue.size, "%")
  585. });
  586. }
  587. this.move = function(box) {
  588. this.applyStyles({
  589. top: this.formatStyle(box.top, "px"),
  590. bottom: this.formatStyle(box.bottom, "px"),
  591. left: this.formatStyle(box.left, "px"),
  592. right: this.formatStyle(box.right, "px"),
  593. height: this.formatStyle(box.height, "px"),
  594. width: this.formatStyle(box.width, "px")
  595. });
  596. };
  597. }
  598. CueStyleBox.prototype = _objCreate(StyleBox.prototype);
  599. CueStyleBox.prototype.constructor = CueStyleBox;
  600. // Represents the co-ordinates of an Element in a way that we can easily
  601. // compute things with such as if it overlaps or intersects with another Element.
  602. // Can initialize it with either a StyleBox or another BoxPosition.
  603. function BoxPosition(obj) {
  604. // Either a BoxPosition was passed in and we need to copy it, or a StyleBox
  605. // was passed in and we need to copy the results of 'getBoundingClientRect'
  606. // as the object returned is readonly. All co-ordinate values are in reference
  607. // to the viewport origin (top left).
  608. var lh, height, width, top;
  609. if (obj.div) {
  610. height = obj.div.offsetHeight;
  611. width = obj.div.offsetWidth;
  612. top = obj.div.offsetTop;
  613. var rects = (rects = obj.div.childNodes) && (rects = rects[0]) &&
  614. rects.getClientRects && rects.getClientRects();
  615. obj = obj.div.getBoundingClientRect();
  616. // In certain cases the outter div will be slightly larger then the sum of
  617. // the inner div's lines. This could be due to bold text, etc, on some platforms.
  618. // In this case we should get the average line height and use that. This will
  619. // result in the desired behaviour.
  620. lh = rects ? Math.max((rects[0] && rects[0].height) || 0, obj.height / rects.length)
  621. : 0;
  622. }
  623. this.left = obj.left;
  624. this.right = obj.right;
  625. this.top = obj.top || top;
  626. this.height = obj.height || height;
  627. this.bottom = obj.bottom || (top + (obj.height || height));
  628. this.width = obj.width || width;
  629. this.lineHeight = lh !== undefined ? lh : obj.lineHeight;
  630. }
  631. // Move the box along a particular axis. Optionally pass in an amount to move
  632. // the box. If no amount is passed then the default is the line height of the
  633. // box.
  634. BoxPosition.prototype.move = function(axis, toMove) {
  635. toMove = toMove !== undefined ? toMove : this.lineHeight;
  636. switch (axis) {
  637. case "+x":
  638. this.left += toMove;
  639. this.right += toMove;
  640. break;
  641. case "-x":
  642. this.left -= toMove;
  643. this.right -= toMove;
  644. break;
  645. case "+y":
  646. this.top += toMove;
  647. this.bottom += toMove;
  648. break;
  649. case "-y":
  650. this.top -= toMove;
  651. this.bottom -= toMove;
  652. break;
  653. }
  654. };
  655. // Check if this box overlaps another box, b2.
  656. BoxPosition.prototype.overlaps = function(b2) {
  657. return this.left < b2.right &&
  658. this.right > b2.left &&
  659. this.top < b2.bottom &&
  660. this.bottom > b2.top;
  661. };
  662. // Check if this box overlaps any other boxes in boxes.
  663. BoxPosition.prototype.overlapsAny = function(boxes) {
  664. for (var i = 0; i < boxes.length; i++) {
  665. if (this.overlaps(boxes[i])) {
  666. return true;
  667. }
  668. }
  669. return false;
  670. };
  671. // Check if this box is within another box.
  672. BoxPosition.prototype.within = function(container) {
  673. return this.top >= container.top &&
  674. this.bottom <= container.bottom &&
  675. this.left >= container.left &&
  676. this.right <= container.right;
  677. };
  678. // Check if this box is entirely within the container or it is overlapping
  679. // on the edge opposite of the axis direction passed. For example, if "+x" is
  680. // passed and the box is overlapping on the left edge of the container, then
  681. // return true.
  682. BoxPosition.prototype.overlapsOppositeAxis = function(container, axis) {
  683. switch (axis) {
  684. case "+x":
  685. return this.left < container.left;
  686. case "-x":
  687. return this.right > container.right;
  688. case "+y":
  689. return this.top < container.top;
  690. case "-y":
  691. return this.bottom > container.bottom;
  692. }
  693. };
  694. // Find the percentage of the area that this box is overlapping with another
  695. // box.
  696. BoxPosition.prototype.intersectPercentage = function(b2) {
  697. var x = Math.max(0, Math.min(this.right, b2.right) - Math.max(this.left, b2.left)),
  698. y = Math.max(0, Math.min(this.bottom, b2.bottom) - Math.max(this.top, b2.top)),
  699. intersectArea = x * y;
  700. return intersectArea / (this.height * this.width);
  701. };
  702. // Convert the positions from this box to CSS compatible positions using
  703. // the reference container's positions. This has to be done because this
  704. // box's positions are in reference to the viewport origin, whereas, CSS
  705. // values are in referecne to their respective edges.
  706. BoxPosition.prototype.toCSSCompatValues = function(reference) {
  707. return {
  708. top: this.top - reference.top,
  709. bottom: reference.bottom - this.bottom,
  710. left: this.left - reference.left,
  711. right: reference.right - this.right,
  712. height: this.height,
  713. width: this.width
  714. };
  715. };
  716. // Get an object that represents the box's position without anything extra.
  717. // Can pass a StyleBox, HTMLElement, or another BoxPositon.
  718. BoxPosition.getSimpleBoxPosition = function(obj) {
  719. var height = obj.div ? obj.div.offsetHeight : obj.tagName ? obj.offsetHeight : 0;
  720. var width = obj.div ? obj.div.offsetWidth : obj.tagName ? obj.offsetWidth : 0;
  721. var top = obj.div ? obj.div.offsetTop : obj.tagName ? obj.offsetTop : 0;
  722. obj = obj.div ? obj.div.getBoundingClientRect() :
  723. obj.tagName ? obj.getBoundingClientRect() : obj;
  724. var ret = {
  725. left: obj.left,
  726. right: obj.right,
  727. top: obj.top || top,
  728. height: obj.height || height,
  729. bottom: obj.bottom || (top + (obj.height || height)),
  730. width: obj.width || width
  731. };
  732. return ret;
  733. };
  734. // Move a StyleBox to its specified, or next best, position. The containerBox
  735. // is the box that contains the StyleBox, such as a div. boxPositions are
  736. // a list of other boxes that the styleBox can't overlap with.
  737. function moveBoxToLinePosition(window, styleBox, containerBox, boxPositions) {
  738. // Find the best position for a cue box, b, on the video. The axis parameter
  739. // is a list of axis, the order of which, it will move the box along. For example:
  740. // Passing ["+x", "-x"] will move the box first along the x axis in the positive
  741. // direction. If it doesn't find a good position for it there it will then move
  742. // it along the x axis in the negative direction.
  743. function findBestPosition(b, axis) {
  744. var bestPosition,
  745. specifiedPosition = new BoxPosition(b),
  746. percentage = 1; // Highest possible so the first thing we get is better.
  747. for (var i = 0; i < axis.length; i++) {
  748. while (b.overlapsOppositeAxis(containerBox, axis[i]) ||
  749. (b.within(containerBox) && b.overlapsAny(boxPositions))) {
  750. b.move(axis[i]);
  751. }
  752. // We found a spot where we aren't overlapping anything. This is our
  753. // best position.
  754. if (b.within(containerBox)) {
  755. return b;
  756. }
  757. var p = b.intersectPercentage(containerBox);
  758. // If we're outside the container box less then we were on our last try
  759. // then remember this position as the best position.
  760. if (percentage > p) {
  761. bestPosition = new BoxPosition(b);
  762. percentage = p;
  763. }
  764. // Reset the box position to the specified position.
  765. b = new BoxPosition(specifiedPosition);
  766. }
  767. return bestPosition || specifiedPosition;
  768. }
  769. var boxPosition = new BoxPosition(styleBox),
  770. cue = styleBox.cue,
  771. linePos = computeLinePos(cue),
  772. axis = [];
  773. // If we have a line number to align the cue to.
  774. if (cue.snapToLines) {
  775. var size;
  776. switch (cue.vertical) {
  777. case "":
  778. axis = [ "+y", "-y" ];
  779. size = "height";
  780. break;
  781. case "rl":
  782. axis = [ "+x", "-x" ];
  783. size = "width";
  784. break;
  785. case "lr":
  786. axis = [ "-x", "+x" ];
  787. size = "width";
  788. break;
  789. }
  790. var step = boxPosition.lineHeight,
  791. position = step * Math.round(linePos),
  792. maxPosition = containerBox[size] + step,
  793. initialAxis = axis[0];
  794. // If the specified intial position is greater then the max position then
  795. // clamp the box to the amount of steps it would take for the box to
  796. // reach the max position.
  797. if (Math.abs(position) > maxPosition) {
  798. position = position < 0 ? -1 : 1;
  799. position *= Math.ceil(maxPosition / step) * step;
  800. }
  801. // If computed line position returns negative then line numbers are
  802. // relative to the bottom of the video instead of the top. Therefore, we
  803. // need to increase our initial position by the length or width of the
  804. // video, depending on the writing direction, and reverse our axis directions.
  805. if (linePos < 0) {
  806. position += cue.vertical === "" ? containerBox.height : containerBox.width;
  807. axis = axis.reverse();
  808. }
  809. // Move the box to the specified position. This may not be its best
  810. // position.
  811. boxPosition.move(initialAxis, position);
  812. } else {
  813. // If we have a percentage line value for the cue.
  814. var calculatedPercentage = (boxPosition.lineHeight / containerBox.height) * 100;
  815. switch (cue.lineAlign) {
  816. case "center":
  817. linePos -= (calculatedPercentage / 2);
  818. break;
  819. case "end":
  820. linePos -= calculatedPercentage;
  821. break;
  822. }
  823. // Apply initial line position to the cue box.
  824. switch (cue.vertical) {
  825. case "":
  826. styleBox.applyStyles({
  827. top: styleBox.formatStyle(linePos, "%")
  828. });
  829. break;
  830. case "rl":
  831. styleBox.applyStyles({
  832. left: styleBox.formatStyle(linePos, "%")
  833. });
  834. break;
  835. case "lr":
  836. styleBox.applyStyles({
  837. right: styleBox.formatStyle(linePos, "%")
  838. });
  839. break;
  840. }
  841. axis = [ "+y", "-x", "+x", "-y" ];
  842. // Get the box position again after we've applied the specified positioning
  843. // to it.
  844. boxPosition = new BoxPosition(styleBox);
  845. }
  846. var bestPosition = findBestPosition(boxPosition, axis);
  847. styleBox.move(bestPosition.toCSSCompatValues(containerBox));
  848. }
  849. function WebVTT() {
  850. // Nothing
  851. }
  852. // Helper to allow strings to be decoded instead of the default binary utf8 data.
  853. WebVTT.StringDecoder = function() {
  854. return {
  855. decode: function(data) {
  856. if (!data) {
  857. return "";
  858. }
  859. if (typeof data !== "string") {
  860. throw new Error("Error - expected string data.");
  861. }
  862. return decodeURIComponent(encodeURIComponent(data));
  863. }
  864. };
  865. };
  866. WebVTT.convertCueToDOMTree = function(window, cuetext) {
  867. if (!window || !cuetext) {
  868. return null;
  869. }
  870. return parseContent(window, cuetext);
  871. };
  872. var FONT_SIZE_PERCENT = 0.05;
  873. var FONT_STYLE = "sans-serif";
  874. var CUE_BACKGROUND_PADDING = "1.5%";
  875. // Runs the processing model over the cues and regions passed to it.
  876. // @param overlay A block level element (usually a div) that the computed cues
  877. // and regions will be placed into.
  878. WebVTT.processCues = function(window, cues, overlay) {
  879. if (!window || !cues || !overlay) {
  880. return null;
  881. }
  882. // Remove all previous children.
  883. while (overlay.firstChild) {
  884. overlay.removeChild(overlay.firstChild);
  885. }
  886. var paddedOverlay = window.document.createElement("div");
  887. paddedOverlay.style.position = "absolute";
  888. paddedOverlay.style.left = "0";
  889. paddedOverlay.style.right = "0";
  890. paddedOverlay.style.top = "0";
  891. paddedOverlay.style.bottom = "0";
  892. paddedOverlay.style.margin = CUE_BACKGROUND_PADDING;
  893. overlay.appendChild(paddedOverlay);
  894. // Determine if we need to compute the display states of the cues. This could
  895. // be the case if a cue's state has been changed since the last computation or
  896. // if it has not been computed yet.
  897. function shouldCompute(cues) {
  898. for (var i = 0; i < cues.length; i++) {
  899. if (cues[i].hasBeenReset || !cues[i].displayState) {
  900. return true;
  901. }
  902. }
  903. return false;
  904. }
  905. // We don't need to recompute the cues' display states. Just reuse them.
  906. if (!shouldCompute(cues)) {
  907. for (var i = 0; i < cues.length; i++) {
  908. paddedOverlay.appendChild(cues[i].displayState);
  909. }
  910. return;
  911. }
  912. var boxPositions = [],
  913. containerBox = BoxPosition.getSimpleBoxPosition(paddedOverlay),
  914. fontSize = Math.round(containerBox.height * FONT_SIZE_PERCENT * 100) / 100;
  915. var styleOptions = {
  916. font: fontSize + "px " + FONT_STYLE
  917. };
  918. (function() {
  919. var styleBox, cue;
  920. for (var i = 0; i < cues.length; i++) {
  921. cue = cues[i];
  922. // Compute the intial position and styles of the cue div.
  923. styleBox = new CueStyleBox(window, cue, styleOptions);
  924. paddedOverlay.appendChild(styleBox.div);
  925. // Move the cue div to it's correct line position.
  926. moveBoxToLinePosition(window, styleBox, containerBox, boxPositions);
  927. // Remember the computed div so that we don't have to recompute it later
  928. // if we don't have too.
  929. cue.displayState = styleBox.div;
  930. boxPositions.push(BoxPosition.getSimpleBoxPosition(styleBox));
  931. }
  932. })();
  933. };
  934. WebVTT.Parser = function(window, vttjs, decoder) {
  935. if (!decoder) {
  936. decoder = vttjs;
  937. vttjs = {};
  938. }
  939. if (!vttjs) {
  940. vttjs = {};
  941. }
  942. this.window = window;
  943. this.vttjs = vttjs;
  944. this.state = "INITIAL";
  945. this.buffer = "";
  946. this.decoder = decoder || new TextDecoder("utf8");
  947. this.regionList = [];
  948. };
  949. WebVTT.Parser.prototype = {
  950. // If the error is a ParsingError then report it to the consumer if
  951. // possible. If it's not a ParsingError then throw it like normal.
  952. reportOrThrowError: function(e) {
  953. if (e instanceof ParsingError) {
  954. this.onparsingerror && this.onparsingerror(e);
  955. } else {
  956. throw e;
  957. }
  958. },
  959. parse: function (data) {
  960. var self = this;
  961. // If there is no data then we won't decode it, but will just try to parse
  962. // whatever is in buffer already. This may occur in circumstances, for
  963. // example when flush() is called.
  964. if (data) {
  965. // Try to decode the data that we received.
  966. self.buffer += self.decoder.decode(data, {stream: true});
  967. }
  968. function collectNextLine() {
  969. var buffer = self.buffer;
  970. var pos = 0;
  971. while (pos < buffer.length && buffer[pos] !== '\r' && buffer[pos] !== '\n') {
  972. ++pos;
  973. }
  974. var line = buffer.substr(0, pos);
  975. // Advance the buffer early in case we fail below.
  976. if (buffer[pos] === '\r') {
  977. ++pos;
  978. }
  979. if (buffer[pos] === '\n') {
  980. ++pos;
  981. }
  982. self.buffer = buffer.substr(pos);
  983. return line;
  984. }
  985. // 3.4 WebVTT region and WebVTT region settings syntax
  986. function parseRegion(input) {
  987. var settings = new Settings();
  988. parseOptions(input, function (k, v) {
  989. switch (k) {
  990. case "id":
  991. settings.set(k, v);
  992. break;
  993. case "width":
  994. settings.percent(k, v);
  995. break;
  996. case "lines":
  997. settings.integer(k, v);
  998. break;
  999. case "regionanchor":
  1000. case "viewportanchor":
  1001. var xy = v.split(',');
  1002. if (xy.length !== 2) {
  1003. break;
  1004. }
  1005. // We have to make sure both x and y parse, so use a temporary
  1006. // settings object here.
  1007. var anchor = new Settings();
  1008. anchor.percent("x", xy[0]);
  1009. anchor.percent("y", xy[1]);
  1010. if (!anchor.has("x") || !anchor.has("y")) {
  1011. break;
  1012. }
  1013. settings.set(k + "X", anchor.get("x"));
  1014. settings.set(k + "Y", anchor.get("y"));
  1015. break;
  1016. case "scroll":
  1017. settings.alt(k, v, ["up"]);
  1018. break;
  1019. }
  1020. }, /=/, /\s/);
  1021. // Create the region, using default values for any values that were not
  1022. // specified.
  1023. if (settings.has("id")) {
  1024. var region = new (self.vttjs.VTTRegion || self.window.VTTRegion)();
  1025. region.width = settings.get("width", 100);
  1026. region.lines = settings.get("lines", 3);
  1027. region.regionAnchorX = settings.get("regionanchorX", 0);
  1028. region.regionAnchorY = settings.get("regionanchorY", 100);
  1029. region.viewportAnchorX = settings.get("viewportanchorX", 0);
  1030. region.viewportAnchorY = settings.get("viewportanchorY", 100);
  1031. region.scroll = settings.get("scroll", "");
  1032. // Register the region.
  1033. self.onregion && self.onregion(region);
  1034. // Remember the VTTRegion for later in case we parse any VTTCues that
  1035. // reference it.
  1036. self.regionList.push({
  1037. id: settings.get("id"),
  1038. region: region
  1039. });
  1040. }
  1041. }
  1042. // draft-pantos-http-live-streaming-20
  1043. // https://tools.ietf.org/html/draft-pantos-http-live-streaming-20#section-3.5
  1044. // 3.5 WebVTT
  1045. function parseTimestampMap(input) {
  1046. var settings = new Settings();
  1047. parseOptions(input, function(k, v) {
  1048. switch(k) {
  1049. case "MPEGT":
  1050. settings.integer(k + 'S', v);
  1051. break;
  1052. case "LOCA":
  1053. settings.set(k + 'L', parseTimeStamp(v));
  1054. break;
  1055. }
  1056. }, /[^\d]:/, /,/);
  1057. self.ontimestampmap && self.ontimestampmap({
  1058. "MPEGTS": settings.get("MPEGTS"),
  1059. "LOCAL": settings.get("LOCAL")
  1060. });
  1061. }
  1062. // 3.2 WebVTT metadata header syntax
  1063. function parseHeader(input) {
  1064. if (input.match(/X-TIMESTAMP-MAP/)) {
  1065. // This line contains HLS X-TIMESTAMP-MAP metadata
  1066. parseOptions(input, function(k, v) {
  1067. switch(k) {
  1068. case "X-TIMESTAMP-MAP":
  1069. parseTimestampMap(v);
  1070. break;
  1071. }
  1072. }, /=/);
  1073. } else {
  1074. parseOptions(input, function (k, v) {
  1075. switch (k) {
  1076. case "Region":
  1077. // 3.3 WebVTT region metadata header syntax
  1078. parseRegion(v);
  1079. break;
  1080. }
  1081. }, /:/);
  1082. }
  1083. }
  1084. // 5.1 WebVTT file parsing.
  1085. try {
  1086. var line;
  1087. if (self.state === "INITIAL") {
  1088. // We can't start parsing until we have the first line.
  1089. if (!/\r\n|\n/.test(self.buffer)) {
  1090. return this;
  1091. }
  1092. line = collectNextLine();
  1093. var m = line.match(/^WEBVTT([ \t].*)?$/);
  1094. if (!m || !m[0]) {
  1095. throw new ParsingError(ParsingError.Errors.BadSignature);
  1096. }
  1097. self.state = "HEADER";
  1098. }
  1099. var alreadyCollectedLine = false;
  1100. while (self.buffer) {
  1101. // We can't parse a line until we have the full line.
  1102. if (!/\r\n|\n/.test(self.buffer)) {
  1103. return this;
  1104. }
  1105. if (!alreadyCollectedLine) {
  1106. line = collectNextLine();
  1107. } else {
  1108. alreadyCollectedLine = false;
  1109. }
  1110. switch (self.state) {
  1111. case "HEADER":
  1112. // 13-18 - Allow a header (metadata) under the WEBVTT line.
  1113. if (/:/.test(line)) {
  1114. parseHeader(line);
  1115. } else if (!line) {
  1116. // An empty line terminates the header and starts the body (cues).
  1117. self.state = "ID";
  1118. }
  1119. continue;
  1120. case "NOTE":
  1121. // Ignore NOTE blocks.
  1122. if (!line) {
  1123. self.state = "ID";
  1124. }
  1125. continue;
  1126. case "ID":
  1127. // Check for the start of NOTE blocks.
  1128. if (/^NOTE($|[ \t])/.test(line)) {
  1129. self.state = "NOTE";
  1130. break;
  1131. }
  1132. // 19-29 - Allow any number of line terminators, then initialize new cue values.
  1133. if (!line) {
  1134. continue;
  1135. }
  1136. self.cue = new (self.vttjs.VTTCue || self.window.VTTCue)(0, 0, "");
  1137. // Safari still uses the old middle value and won't accept center
  1138. try {
  1139. self.cue.align = "center";
  1140. } catch (e) {
  1141. self.cue.align = "middle";
  1142. }
  1143. self.state = "CUE";
  1144. // 30-39 - Check if self line contains an optional identifier or timing data.
  1145. if (line.indexOf("-->") === -1) {
  1146. self.cue.id = line;
  1147. continue;
  1148. }
  1149. // Process line as start of a cue.
  1150. /*falls through*/
  1151. case "CUE":
  1152. // 40 - Collect cue timings and settings.
  1153. try {
  1154. parseCue(line, self.cue, self.regionList);
  1155. } catch (e) {
  1156. self.reportOrThrowError(e);
  1157. // In case of an error ignore rest of the cue.
  1158. self.cue = null;
  1159. self.state = "BADCUE";
  1160. continue;
  1161. }
  1162. self.state = "CUETEXT";
  1163. continue;
  1164. case "CUETEXT":
  1165. var hasSubstring = line.indexOf("-->") !== -1;
  1166. // 34 - If we have an empty line then report the cue.
  1167. // 35 - If we have the special substring '-->' then report the cue,
  1168. // but do not collect the line as we need to process the current
  1169. // one as a new cue.
  1170. if (!line || hasSubstring && (alreadyCollectedLine = true)) {
  1171. // We are done parsing self cue.
  1172. self.oncue && self.oncue(self.cue);
  1173. self.cue = null;
  1174. self.state = "ID";
  1175. continue;
  1176. }
  1177. if (self.cue.text) {
  1178. self.cue.text += "\n";
  1179. }
  1180. self.cue.text += line.replace(/\u2028/g, '\n').replace(/u2029/g, '\n');
  1181. continue;
  1182. case "BADCUE": // BADCUE
  1183. // 54-62 - Collect and discard the remaining cue.
  1184. if (!line) {
  1185. self.state = "ID";
  1186. }
  1187. continue;
  1188. }
  1189. }
  1190. } catch (e) {
  1191. self.reportOrThrowError(e);
  1192. // If we are currently parsing a cue, report what we have.
  1193. if (self.state === "CUETEXT" && self.cue && self.oncue) {
  1194. self.oncue(self.cue);
  1195. }
  1196. self.cue = null;
  1197. // Enter BADWEBVTT state if header was not parsed correctly otherwise
  1198. // another exception occurred so enter BADCUE state.
  1199. self.state = self.state === "INITIAL" ? "BADWEBVTT" : "BADCUE";
  1200. }
  1201. return this;
  1202. },
  1203. flush: function () {
  1204. var self = this;
  1205. try {
  1206. // Finish decoding the stream.
  1207. self.buffer += self.decoder.decode();
  1208. // Synthesize the end of the current cue or region.
  1209. if (self.cue || self.state === "HEADER") {
  1210. self.buffer += "\n\n";
  1211. self.parse();
  1212. }
  1213. // If we've flushed, parsed, and we're still on the INITIAL state then
  1214. // that means we don't have enough of the stream to parse the first
  1215. // line.
  1216. if (self.state === "INITIAL") {
  1217. throw new ParsingError(ParsingError.Errors.BadSignature);
  1218. }
  1219. } catch(e) {
  1220. self.reportOrThrowError(e);
  1221. }
  1222. self.onflush && self.onflush();
  1223. return this;
  1224. }
  1225. };
  1226. module.exports = WebVTT;