vtt.js 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349
  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. textPos = cue.position;
  560. break;
  561. case "center":
  562. textPos = cue.position - (cue.size / 2);
  563. break;
  564. case "end":
  565. textPos = cue.position - cue.size;
  566. break;
  567. }
  568. // Horizontal box orientation; textPos is the distance from the left edge of the
  569. // area to the left edge of the box and cue.size is the distance extending to
  570. // the right from there.
  571. if (cue.vertical === "") {
  572. this.applyStyles({
  573. left: this.formatStyle(textPos, "%"),
  574. width: this.formatStyle(cue.size, "%")
  575. });
  576. // Vertical box orientation; textPos is the distance from the top edge of the
  577. // area to the top edge of the box and cue.size is the height extending
  578. // downwards from there.
  579. } else {
  580. this.applyStyles({
  581. top: this.formatStyle(textPos, "%"),
  582. height: this.formatStyle(cue.size, "%")
  583. });
  584. }
  585. this.move = function(box) {
  586. this.applyStyles({
  587. top: this.formatStyle(box.top, "px"),
  588. bottom: this.formatStyle(box.bottom, "px"),
  589. left: this.formatStyle(box.left, "px"),
  590. right: this.formatStyle(box.right, "px"),
  591. height: this.formatStyle(box.height, "px"),
  592. width: this.formatStyle(box.width, "px")
  593. });
  594. };
  595. }
  596. CueStyleBox.prototype = _objCreate(StyleBox.prototype);
  597. CueStyleBox.prototype.constructor = CueStyleBox;
  598. // Represents the co-ordinates of an Element in a way that we can easily
  599. // compute things with such as if it overlaps or intersects with another Element.
  600. // Can initialize it with either a StyleBox or another BoxPosition.
  601. function BoxPosition(obj) {
  602. // Either a BoxPosition was passed in and we need to copy it, or a StyleBox
  603. // was passed in and we need to copy the results of 'getBoundingClientRect'
  604. // as the object returned is readonly. All co-ordinate values are in reference
  605. // to the viewport origin (top left).
  606. var lh, height, width, top;
  607. if (obj.div) {
  608. height = obj.div.offsetHeight;
  609. width = obj.div.offsetWidth;
  610. top = obj.div.offsetTop;
  611. var rects = (rects = obj.div.childNodes) && (rects = rects[0]) &&
  612. rects.getClientRects && rects.getClientRects();
  613. obj = obj.div.getBoundingClientRect();
  614. // In certain cases the outter div will be slightly larger then the sum of
  615. // the inner div's lines. This could be due to bold text, etc, on some platforms.
  616. // In this case we should get the average line height and use that. This will
  617. // result in the desired behaviour.
  618. lh = rects ? Math.max((rects[0] && rects[0].height) || 0, obj.height / rects.length)
  619. : 0;
  620. }
  621. this.left = obj.left;
  622. this.right = obj.right;
  623. this.top = obj.top || top;
  624. this.height = obj.height || height;
  625. this.bottom = obj.bottom || (top + (obj.height || height));
  626. this.width = obj.width || width;
  627. this.lineHeight = lh !== undefined ? lh : obj.lineHeight;
  628. }
  629. // Move the box along a particular axis. Optionally pass in an amount to move
  630. // the box. If no amount is passed then the default is the line height of the
  631. // box.
  632. BoxPosition.prototype.move = function(axis, toMove) {
  633. toMove = toMove !== undefined ? toMove : this.lineHeight;
  634. switch (axis) {
  635. case "+x":
  636. this.left += toMove;
  637. this.right += toMove;
  638. break;
  639. case "-x":
  640. this.left -= toMove;
  641. this.right -= toMove;
  642. break;
  643. case "+y":
  644. this.top += toMove;
  645. this.bottom += toMove;
  646. break;
  647. case "-y":
  648. this.top -= toMove;
  649. this.bottom -= toMove;
  650. break;
  651. }
  652. };
  653. // Check if this box overlaps another box, b2.
  654. BoxPosition.prototype.overlaps = function(b2) {
  655. return this.left < b2.right &&
  656. this.right > b2.left &&
  657. this.top < b2.bottom &&
  658. this.bottom > b2.top;
  659. };
  660. // Check if this box overlaps any other boxes in boxes.
  661. BoxPosition.prototype.overlapsAny = function(boxes) {
  662. for (var i = 0; i < boxes.length; i++) {
  663. if (this.overlaps(boxes[i])) {
  664. return true;
  665. }
  666. }
  667. return false;
  668. };
  669. // Check if this box is within another box.
  670. BoxPosition.prototype.within = function(container) {
  671. return this.top >= container.top &&
  672. this.bottom <= container.bottom &&
  673. this.left >= container.left &&
  674. this.right <= container.right;
  675. };
  676. // Check if this box is entirely within the container or it is overlapping
  677. // on the edge opposite of the axis direction passed. For example, if "+x" is
  678. // passed and the box is overlapping on the left edge of the container, then
  679. // return true.
  680. BoxPosition.prototype.overlapsOppositeAxis = function(container, axis) {
  681. switch (axis) {
  682. case "+x":
  683. return this.left < container.left;
  684. case "-x":
  685. return this.right > container.right;
  686. case "+y":
  687. return this.top < container.top;
  688. case "-y":
  689. return this.bottom > container.bottom;
  690. }
  691. };
  692. // Find the percentage of the area that this box is overlapping with another
  693. // box.
  694. BoxPosition.prototype.intersectPercentage = function(b2) {
  695. var x = Math.max(0, Math.min(this.right, b2.right) - Math.max(this.left, b2.left)),
  696. y = Math.max(0, Math.min(this.bottom, b2.bottom) - Math.max(this.top, b2.top)),
  697. intersectArea = x * y;
  698. return intersectArea / (this.height * this.width);
  699. };
  700. // Convert the positions from this box to CSS compatible positions using
  701. // the reference container's positions. This has to be done because this
  702. // box's positions are in reference to the viewport origin, whereas, CSS
  703. // values are in referecne to their respective edges.
  704. BoxPosition.prototype.toCSSCompatValues = function(reference) {
  705. return {
  706. top: this.top - reference.top,
  707. bottom: reference.bottom - this.bottom,
  708. left: this.left - reference.left,
  709. right: reference.right - this.right,
  710. height: this.height,
  711. width: this.width
  712. };
  713. };
  714. // Get an object that represents the box's position without anything extra.
  715. // Can pass a StyleBox, HTMLElement, or another BoxPositon.
  716. BoxPosition.getSimpleBoxPosition = function(obj) {
  717. var height = obj.div ? obj.div.offsetHeight : obj.tagName ? obj.offsetHeight : 0;
  718. var width = obj.div ? obj.div.offsetWidth : obj.tagName ? obj.offsetWidth : 0;
  719. var top = obj.div ? obj.div.offsetTop : obj.tagName ? obj.offsetTop : 0;
  720. obj = obj.div ? obj.div.getBoundingClientRect() :
  721. obj.tagName ? obj.getBoundingClientRect() : obj;
  722. var ret = {
  723. left: obj.left,
  724. right: obj.right,
  725. top: obj.top || top,
  726. height: obj.height || height,
  727. bottom: obj.bottom || (top + (obj.height || height)),
  728. width: obj.width || width
  729. };
  730. return ret;
  731. };
  732. // Move a StyleBox to its specified, or next best, position. The containerBox
  733. // is the box that contains the StyleBox, such as a div. boxPositions are
  734. // a list of other boxes that the styleBox can't overlap with.
  735. function moveBoxToLinePosition(window, styleBox, containerBox, boxPositions) {
  736. // Find the best position for a cue box, b, on the video. The axis parameter
  737. // is a list of axis, the order of which, it will move the box along. For example:
  738. // Passing ["+x", "-x"] will move the box first along the x axis in the positive
  739. // direction. If it doesn't find a good position for it there it will then move
  740. // it along the x axis in the negative direction.
  741. function findBestPosition(b, axis) {
  742. var bestPosition,
  743. specifiedPosition = new BoxPosition(b),
  744. percentage = 1; // Highest possible so the first thing we get is better.
  745. for (var i = 0; i < axis.length; i++) {
  746. while (b.overlapsOppositeAxis(containerBox, axis[i]) ||
  747. (b.within(containerBox) && b.overlapsAny(boxPositions))) {
  748. b.move(axis[i]);
  749. }
  750. // We found a spot where we aren't overlapping anything. This is our
  751. // best position.
  752. if (b.within(containerBox)) {
  753. return b;
  754. }
  755. var p = b.intersectPercentage(containerBox);
  756. // If we're outside the container box less then we were on our last try
  757. // then remember this position as the best position.
  758. if (percentage > p) {
  759. bestPosition = new BoxPosition(b);
  760. percentage = p;
  761. }
  762. // Reset the box position to the specified position.
  763. b = new BoxPosition(specifiedPosition);
  764. }
  765. return bestPosition || specifiedPosition;
  766. }
  767. var boxPosition = new BoxPosition(styleBox),
  768. cue = styleBox.cue,
  769. linePos = computeLinePos(cue),
  770. axis = [];
  771. // If we have a line number to align the cue to.
  772. if (cue.snapToLines) {
  773. var size;
  774. switch (cue.vertical) {
  775. case "":
  776. axis = [ "+y", "-y" ];
  777. size = "height";
  778. break;
  779. case "rl":
  780. axis = [ "+x", "-x" ];
  781. size = "width";
  782. break;
  783. case "lr":
  784. axis = [ "-x", "+x" ];
  785. size = "width";
  786. break;
  787. }
  788. var step = boxPosition.lineHeight,
  789. position = step * Math.round(linePos),
  790. maxPosition = containerBox[size] + step,
  791. initialAxis = axis[0];
  792. // If the specified intial position is greater then the max position then
  793. // clamp the box to the amount of steps it would take for the box to
  794. // reach the max position.
  795. if (Math.abs(position) > maxPosition) {
  796. position = position < 0 ? -1 : 1;
  797. position *= Math.ceil(maxPosition / step) * step;
  798. }
  799. // If computed line position returns negative then line numbers are
  800. // relative to the bottom of the video instead of the top. Therefore, we
  801. // need to increase our initial position by the length or width of the
  802. // video, depending on the writing direction, and reverse our axis directions.
  803. if (linePos < 0) {
  804. position += cue.vertical === "" ? containerBox.height : containerBox.width;
  805. axis = axis.reverse();
  806. }
  807. // Move the box to the specified position. This may not be its best
  808. // position.
  809. boxPosition.move(initialAxis, position);
  810. } else {
  811. // If we have a percentage line value for the cue.
  812. var calculatedPercentage = (boxPosition.lineHeight / containerBox.height) * 100;
  813. switch (cue.lineAlign) {
  814. case "center":
  815. linePos -= (calculatedPercentage / 2);
  816. break;
  817. case "end":
  818. linePos -= calculatedPercentage;
  819. break;
  820. }
  821. // Apply initial line position to the cue box.
  822. switch (cue.vertical) {
  823. case "":
  824. styleBox.applyStyles({
  825. top: styleBox.formatStyle(linePos, "%")
  826. });
  827. break;
  828. case "rl":
  829. styleBox.applyStyles({
  830. left: styleBox.formatStyle(linePos, "%")
  831. });
  832. break;
  833. case "lr":
  834. styleBox.applyStyles({
  835. right: styleBox.formatStyle(linePos, "%")
  836. });
  837. break;
  838. }
  839. axis = [ "+y", "-x", "+x", "-y" ];
  840. // Get the box position again after we've applied the specified positioning
  841. // to it.
  842. boxPosition = new BoxPosition(styleBox);
  843. }
  844. var bestPosition = findBestPosition(boxPosition, axis);
  845. styleBox.move(bestPosition.toCSSCompatValues(containerBox));
  846. }
  847. function WebVTT() {
  848. // Nothing
  849. }
  850. // Helper to allow strings to be decoded instead of the default binary utf8 data.
  851. WebVTT.StringDecoder = function() {
  852. return {
  853. decode: function(data) {
  854. if (!data) {
  855. return "";
  856. }
  857. if (typeof data !== "string") {
  858. throw new Error("Error - expected string data.");
  859. }
  860. return decodeURIComponent(encodeURIComponent(data));
  861. }
  862. };
  863. };
  864. WebVTT.convertCueToDOMTree = function(window, cuetext) {
  865. if (!window || !cuetext) {
  866. return null;
  867. }
  868. return parseContent(window, cuetext);
  869. };
  870. var FONT_SIZE_PERCENT = 0.05;
  871. var FONT_STYLE = "sans-serif";
  872. var CUE_BACKGROUND_PADDING = "1.5%";
  873. // Runs the processing model over the cues and regions passed to it.
  874. // @param overlay A block level element (usually a div) that the computed cues
  875. // and regions will be placed into.
  876. WebVTT.processCues = function(window, cues, overlay) {
  877. if (!window || !cues || !overlay) {
  878. return null;
  879. }
  880. // Remove all previous children.
  881. while (overlay.firstChild) {
  882. overlay.removeChild(overlay.firstChild);
  883. }
  884. var paddedOverlay = window.document.createElement("div");
  885. paddedOverlay.style.position = "absolute";
  886. paddedOverlay.style.left = "0";
  887. paddedOverlay.style.right = "0";
  888. paddedOverlay.style.top = "0";
  889. paddedOverlay.style.bottom = "0";
  890. paddedOverlay.style.margin = CUE_BACKGROUND_PADDING;
  891. overlay.appendChild(paddedOverlay);
  892. // Determine if we need to compute the display states of the cues. This could
  893. // be the case if a cue's state has been changed since the last computation or
  894. // if it has not been computed yet.
  895. function shouldCompute(cues) {
  896. for (var i = 0; i < cues.length; i++) {
  897. if (cues[i].hasBeenReset || !cues[i].displayState) {
  898. return true;
  899. }
  900. }
  901. return false;
  902. }
  903. // We don't need to recompute the cues' display states. Just reuse them.
  904. if (!shouldCompute(cues)) {
  905. for (var i = 0; i < cues.length; i++) {
  906. paddedOverlay.appendChild(cues[i].displayState);
  907. }
  908. return;
  909. }
  910. var boxPositions = [],
  911. containerBox = BoxPosition.getSimpleBoxPosition(paddedOverlay),
  912. fontSize = Math.round(containerBox.height * FONT_SIZE_PERCENT * 100) / 100;
  913. var styleOptions = {
  914. font: fontSize + "px " + FONT_STYLE
  915. };
  916. (function() {
  917. var styleBox, cue;
  918. for (var i = 0; i < cues.length; i++) {
  919. cue = cues[i];
  920. // Compute the intial position and styles of the cue div.
  921. styleBox = new CueStyleBox(window, cue, styleOptions);
  922. paddedOverlay.appendChild(styleBox.div);
  923. // Move the cue div to it's correct line position.
  924. moveBoxToLinePosition(window, styleBox, containerBox, boxPositions);
  925. // Remember the computed div so that we don't have to recompute it later
  926. // if we don't have too.
  927. cue.displayState = styleBox.div;
  928. boxPositions.push(BoxPosition.getSimpleBoxPosition(styleBox));
  929. }
  930. })();
  931. };
  932. WebVTT.Parser = function(window, vttjs, decoder) {
  933. if (!decoder) {
  934. decoder = vttjs;
  935. vttjs = {};
  936. }
  937. if (!vttjs) {
  938. vttjs = {};
  939. }
  940. this.window = window;
  941. this.vttjs = vttjs;
  942. this.state = "INITIAL";
  943. this.buffer = "";
  944. this.decoder = decoder || new TextDecoder("utf8");
  945. this.regionList = [];
  946. };
  947. WebVTT.Parser.prototype = {
  948. // If the error is a ParsingError then report it to the consumer if
  949. // possible. If it's not a ParsingError then throw it like normal.
  950. reportOrThrowError: function(e) {
  951. if (e instanceof ParsingError) {
  952. this.onparsingerror && this.onparsingerror(e);
  953. } else {
  954. throw e;
  955. }
  956. },
  957. parse: function (data) {
  958. var self = this;
  959. // If there is no data then we won't decode it, but will just try to parse
  960. // whatever is in buffer already. This may occur in circumstances, for
  961. // example when flush() is called.
  962. if (data) {
  963. // Try to decode the data that we received.
  964. self.buffer += self.decoder.decode(data, {stream: true});
  965. }
  966. function collectNextLine() {
  967. var buffer = self.buffer;
  968. var pos = 0;
  969. while (pos < buffer.length && buffer[pos] !== '\r' && buffer[pos] !== '\n') {
  970. ++pos;
  971. }
  972. var line = buffer.substr(0, pos);
  973. // Advance the buffer early in case we fail below.
  974. if (buffer[pos] === '\r') {
  975. ++pos;
  976. }
  977. if (buffer[pos] === '\n') {
  978. ++pos;
  979. }
  980. self.buffer = buffer.substr(pos);
  981. return line;
  982. }
  983. // 3.4 WebVTT region and WebVTT region settings syntax
  984. function parseRegion(input) {
  985. var settings = new Settings();
  986. parseOptions(input, function (k, v) {
  987. switch (k) {
  988. case "id":
  989. settings.set(k, v);
  990. break;
  991. case "width":
  992. settings.percent(k, v);
  993. break;
  994. case "lines":
  995. settings.integer(k, v);
  996. break;
  997. case "regionanchor":
  998. case "viewportanchor":
  999. var xy = v.split(',');
  1000. if (xy.length !== 2) {
  1001. break;
  1002. }
  1003. // We have to make sure both x and y parse, so use a temporary
  1004. // settings object here.
  1005. var anchor = new Settings();
  1006. anchor.percent("x", xy[0]);
  1007. anchor.percent("y", xy[1]);
  1008. if (!anchor.has("x") || !anchor.has("y")) {
  1009. break;
  1010. }
  1011. settings.set(k + "X", anchor.get("x"));
  1012. settings.set(k + "Y", anchor.get("y"));
  1013. break;
  1014. case "scroll":
  1015. settings.alt(k, v, ["up"]);
  1016. break;
  1017. }
  1018. }, /=/, /\s/);
  1019. // Create the region, using default values for any values that were not
  1020. // specified.
  1021. if (settings.has("id")) {
  1022. var region = new (self.vttjs.VTTRegion || self.window.VTTRegion)();
  1023. region.width = settings.get("width", 100);
  1024. region.lines = settings.get("lines", 3);
  1025. region.regionAnchorX = settings.get("regionanchorX", 0);
  1026. region.regionAnchorY = settings.get("regionanchorY", 100);
  1027. region.viewportAnchorX = settings.get("viewportanchorX", 0);
  1028. region.viewportAnchorY = settings.get("viewportanchorY", 100);
  1029. region.scroll = settings.get("scroll", "");
  1030. // Register the region.
  1031. self.onregion && self.onregion(region);
  1032. // Remember the VTTRegion for later in case we parse any VTTCues that
  1033. // reference it.
  1034. self.regionList.push({
  1035. id: settings.get("id"),
  1036. region: region
  1037. });
  1038. }
  1039. }
  1040. // draft-pantos-http-live-streaming-20
  1041. // https://tools.ietf.org/html/draft-pantos-http-live-streaming-20#section-3.5
  1042. // 3.5 WebVTT
  1043. function parseTimestampMap(input) {
  1044. var settings = new Settings();
  1045. parseOptions(input, function(k, v) {
  1046. switch(k) {
  1047. case "MPEGT":
  1048. settings.integer(k + 'S', v);
  1049. break;
  1050. case "LOCA":
  1051. settings.set(k + 'L', parseTimeStamp(v));
  1052. break;
  1053. }
  1054. }, /[^\d]:/, /,/);
  1055. self.ontimestampmap && self.ontimestampmap({
  1056. "MPEGTS": settings.get("MPEGTS"),
  1057. "LOCAL": settings.get("LOCAL")
  1058. });
  1059. }
  1060. // 3.2 WebVTT metadata header syntax
  1061. function parseHeader(input) {
  1062. if (input.match(/X-TIMESTAMP-MAP/)) {
  1063. // This line contains HLS X-TIMESTAMP-MAP metadata
  1064. parseOptions(input, function(k, v) {
  1065. switch(k) {
  1066. case "X-TIMESTAMP-MAP":
  1067. parseTimestampMap(v);
  1068. break;
  1069. }
  1070. }, /=/);
  1071. } else {
  1072. parseOptions(input, function (k, v) {
  1073. switch (k) {
  1074. case "Region":
  1075. // 3.3 WebVTT region metadata header syntax
  1076. parseRegion(v);
  1077. break;
  1078. }
  1079. }, /:/);
  1080. }
  1081. }
  1082. // 5.1 WebVTT file parsing.
  1083. try {
  1084. var line;
  1085. if (self.state === "INITIAL") {
  1086. // We can't start parsing until we have the first line.
  1087. if (!/\r\n|\n/.test(self.buffer)) {
  1088. return this;
  1089. }
  1090. line = collectNextLine();
  1091. var m = line.match(/^WEBVTT([ \t].*)?$/);
  1092. if (!m || !m[0]) {
  1093. throw new ParsingError(ParsingError.Errors.BadSignature);
  1094. }
  1095. self.state = "HEADER";
  1096. }
  1097. var alreadyCollectedLine = false;
  1098. while (self.buffer) {
  1099. // We can't parse a line until we have the full line.
  1100. if (!/\r\n|\n/.test(self.buffer)) {
  1101. return this;
  1102. }
  1103. if (!alreadyCollectedLine) {
  1104. line = collectNextLine();
  1105. } else {
  1106. alreadyCollectedLine = false;
  1107. }
  1108. switch (self.state) {
  1109. case "HEADER":
  1110. // 13-18 - Allow a header (metadata) under the WEBVTT line.
  1111. if (/:/.test(line)) {
  1112. parseHeader(line);
  1113. } else if (!line) {
  1114. // An empty line terminates the header and starts the body (cues).
  1115. self.state = "ID";
  1116. }
  1117. continue;
  1118. case "NOTE":
  1119. // Ignore NOTE blocks.
  1120. if (!line) {
  1121. self.state = "ID";
  1122. }
  1123. continue;
  1124. case "ID":
  1125. // Check for the start of NOTE blocks.
  1126. if (/^NOTE($|[ \t])/.test(line)) {
  1127. self.state = "NOTE";
  1128. break;
  1129. }
  1130. // 19-29 - Allow any number of line terminators, then initialize new cue values.
  1131. if (!line) {
  1132. continue;
  1133. }
  1134. self.cue = new (self.vttjs.VTTCue || self.window.VTTCue)(0, 0, "");
  1135. // Safari still uses the old middle value and won't accept center
  1136. try {
  1137. self.cue.align = "center";
  1138. } catch (e) {
  1139. self.cue.align = "middle";
  1140. }
  1141. self.state = "CUE";
  1142. // 30-39 - Check if self line contains an optional identifier or timing data.
  1143. if (line.indexOf("-->") === -1) {
  1144. self.cue.id = line;
  1145. continue;
  1146. }
  1147. // Process line as start of a cue.
  1148. /*falls through*/
  1149. case "CUE":
  1150. // 40 - Collect cue timings and settings.
  1151. try {
  1152. parseCue(line, self.cue, self.regionList);
  1153. } catch (e) {
  1154. self.reportOrThrowError(e);
  1155. // In case of an error ignore rest of the cue.
  1156. self.cue = null;
  1157. self.state = "BADCUE";
  1158. continue;
  1159. }
  1160. self.state = "CUETEXT";
  1161. continue;
  1162. case "CUETEXT":
  1163. var hasSubstring = line.indexOf("-->") !== -1;
  1164. // 34 - If we have an empty line then report the cue.
  1165. // 35 - If we have the special substring '-->' then report the cue,
  1166. // but do not collect the line as we need to process the current
  1167. // one as a new cue.
  1168. if (!line || hasSubstring && (alreadyCollectedLine = true)) {
  1169. // We are done parsing self cue.
  1170. self.oncue && self.oncue(self.cue);
  1171. self.cue = null;
  1172. self.state = "ID";
  1173. continue;
  1174. }
  1175. if (self.cue.text) {
  1176. self.cue.text += "\n";
  1177. }
  1178. self.cue.text += line.replace(/\u2028/g, '\n').replace(/u2029/g, '\n');
  1179. continue;
  1180. case "BADCUE": // BADCUE
  1181. // 54-62 - Collect and discard the remaining cue.
  1182. if (!line) {
  1183. self.state = "ID";
  1184. }
  1185. continue;
  1186. }
  1187. }
  1188. } catch (e) {
  1189. self.reportOrThrowError(e);
  1190. // If we are currently parsing a cue, report what we have.
  1191. if (self.state === "CUETEXT" && self.cue && self.oncue) {
  1192. self.oncue(self.cue);
  1193. }
  1194. self.cue = null;
  1195. // Enter BADWEBVTT state if header was not parsed correctly otherwise
  1196. // another exception occurred so enter BADCUE state.
  1197. self.state = self.state === "INITIAL" ? "BADWEBVTT" : "BADCUE";
  1198. }
  1199. return this;
  1200. },
  1201. flush: function () {
  1202. var self = this;
  1203. try {
  1204. // Finish decoding the stream.
  1205. self.buffer += self.decoder.decode();
  1206. // Synthesize the end of the current cue or region.
  1207. if (self.cue || self.state === "HEADER") {
  1208. self.buffer += "\n\n";
  1209. self.parse();
  1210. }
  1211. // If we've flushed, parsed, and we're still on the INITIAL state then
  1212. // that means we don't have enough of the stream to parse the first
  1213. // line.
  1214. if (self.state === "INITIAL") {
  1215. throw new ParsingError(ParsingError.Errors.BadSignature);
  1216. }
  1217. } catch(e) {
  1218. self.reportOrThrowError(e);
  1219. }
  1220. self.onflush && self.onflush();
  1221. return this;
  1222. }
  1223. };
  1224. module.exports = WebVTT;