vtt.js 43 KB

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