Source: lib/text/vtt_text_parser.js

  1. /*! @license
  2. * Shaka Player
  3. * Copyright 2016 Google LLC
  4. * SPDX-License-Identifier: Apache-2.0
  5. */
  6. goog.provide('shaka.text.VttTextParser');
  7. goog.require('goog.asserts');
  8. goog.require('shaka.log');
  9. goog.require('shaka.media.ManifestParser');
  10. goog.require('shaka.text.Cue');
  11. goog.require('shaka.text.CueRegion');
  12. goog.require('shaka.text.TextEngine');
  13. goog.require('shaka.util.Error');
  14. goog.require('shaka.util.StringUtils');
  15. goog.require('shaka.util.TextParser');
  16. goog.require('shaka.util.TXml');
  17. /**
  18. * @implements {shaka.extern.TextParser}
  19. * @export
  20. */
  21. shaka.text.VttTextParser = class {
  22. /** Constructs a VTT parser. */
  23. constructor() {
  24. /** @private {boolean} */
  25. this.sequenceMode_ = false;
  26. /** @private {string} */
  27. this.manifestType_ = shaka.media.ManifestParser.UNKNOWN;
  28. }
  29. /**
  30. * @override
  31. * @export
  32. */
  33. parseInit(data) {
  34. goog.asserts.assert(false, 'VTT does not have init segments');
  35. }
  36. /**
  37. * @override
  38. * @export
  39. */
  40. setSequenceMode(sequenceMode) {
  41. this.sequenceMode_ = sequenceMode;
  42. }
  43. /**
  44. * @override
  45. * @export
  46. */
  47. setManifestType(manifestType) {
  48. this.manifestType_ = manifestType;
  49. }
  50. /**
  51. * @override
  52. * @export
  53. */
  54. parseMedia(data, time) {
  55. const VttTextParser = shaka.text.VttTextParser;
  56. // Get the input as a string. Normalize newlines to \n.
  57. let str = shaka.util.StringUtils.fromUTF8(data);
  58. str = str.replace(/\r\n|\r(?=[^\n]|$)/gm, '\n');
  59. const blocks = str.split(/\n{2,}/m);
  60. if (!/^WEBVTT($|[ \t\n])/m.test(blocks[0])) {
  61. throw new shaka.util.Error(
  62. shaka.util.Error.Severity.CRITICAL,
  63. shaka.util.Error.Category.TEXT,
  64. shaka.util.Error.Code.INVALID_TEXT_HEADER);
  65. }
  66. // Depending on "segmentRelativeVttTiming" configuration,
  67. // "vttOffset" will correspond to either "periodStart" (default)
  68. // or "segmentStart", for segmented VTT where timings are relative
  69. // to the beginning of each segment.
  70. // NOTE: "periodStart" is the timestamp offset applied via TextEngine.
  71. // It is no longer closely tied to periods, but the name stuck around.
  72. // NOTE: This offset and the flag choosing its meaning have no effect on
  73. // HLS content, which should use X-TIMESTAMP-MAP and periodStart instead.
  74. let offset = time.vttOffset;
  75. // Only use 'X-TIMESTAMP-MAP' with HLS. This overrides offset above.
  76. if (blocks[0].includes('X-TIMESTAMP-MAP') &&
  77. this.manifestType_ == shaka.media.ManifestParser.HLS) {
  78. if (this.sequenceMode_) {
  79. // Compute a different, rollover-based offset for sequence mode.
  80. offset = this.computeHlsSequenceModeOffset_(blocks[0], time);
  81. } else {
  82. // Calculate the offset from the segment startTime.
  83. offset = time.segmentStart;
  84. }
  85. }
  86. // Parse VTT regions.
  87. /* !Array.<!shaka.text.CueRegion> */
  88. const regions = [];
  89. for (const line of blocks[0].split('\n')) {
  90. if (/^Region:/.test(line)) {
  91. const region = VttTextParser.parseRegion_(line);
  92. regions.push(region);
  93. }
  94. }
  95. /** @type {!Map.<string, shaka.text.Cue>} */
  96. const styles = new Map();
  97. VttTextParser.addDefaultTextColor_(styles);
  98. // Parse cues.
  99. const ret = [];
  100. for (const block of blocks.slice(1)) {
  101. const lines = block.split('\n');
  102. VttTextParser.parseStyle_(lines, styles);
  103. const cue = VttTextParser.parseCue_(lines, offset, regions, styles);
  104. if (cue) {
  105. ret.push(cue);
  106. }
  107. }
  108. return ret;
  109. }
  110. /**
  111. * @param {string} headerBlock Contains X-TIMESTAMP-MAP.
  112. * @param {shaka.extern.TextParser.TimeContext} time
  113. * @return {number}
  114. * @private
  115. */
  116. computeHlsSequenceModeOffset_(headerBlock, time) {
  117. // https://bit.ly/2K92l7y
  118. // The 'X-TIMESTAMP-MAP' header is used in HLS to align text with
  119. // the rest of the media.
  120. // The header format is 'X-TIMESTAMP-MAP=MPEGTS:n,LOCAL:m'
  121. // (the attributes can go in any order)
  122. // where n is MPEG-2 time and m is cue time it maps to.
  123. // For example 'X-TIMESTAMP-MAP=LOCAL:00:00:00.000,MPEGTS:900000'
  124. // means an offset of 10 seconds
  125. // 900000/MPEG_TIMESCALE - cue time.
  126. const cueTimeMatch = headerBlock.match(
  127. /LOCAL:((?:(\d{1,}):)?(\d{2}):(\d{2})\.(\d{3}))/m);
  128. const mpegTimeMatch = headerBlock.match(/MPEGTS:(\d+)/m);
  129. if (!cueTimeMatch || !mpegTimeMatch) {
  130. throw new shaka.util.Error(
  131. shaka.util.Error.Severity.CRITICAL,
  132. shaka.util.Error.Category.TEXT,
  133. shaka.util.Error.Code.INVALID_TEXT_HEADER);
  134. }
  135. const parser = new shaka.util.TextParser(cueTimeMatch[1]);
  136. const cueTime = shaka.text.VttTextParser.parseTime_(parser);
  137. if (cueTime == null) {
  138. throw new shaka.util.Error(
  139. shaka.util.Error.Severity.CRITICAL,
  140. shaka.util.Error.Category.TEXT,
  141. shaka.util.Error.Code.INVALID_TEXT_HEADER);
  142. }
  143. const mpegTime = Number(mpegTimeMatch[1]);
  144. const mpegTimescale = shaka.text.VttTextParser.MPEG_TIMESCALE_;
  145. return time.periodStart + mpegTime / mpegTimescale - cueTime;
  146. }
  147. /**
  148. * Add default color
  149. *
  150. * @param {!Map.<string, shaka.text.Cue>} styles
  151. * @private
  152. */
  153. static addDefaultTextColor_(styles) {
  154. const textColor = shaka.text.Cue.defaultTextColor;
  155. for (const [key, value] of Object.entries(textColor)) {
  156. const cue = new shaka.text.Cue(0, 0, '');
  157. cue.color = value;
  158. styles.set('.' + key, cue);
  159. }
  160. const bgColor = shaka.text.Cue.defaultTextBackgroundColor;
  161. for (const [key, value] of Object.entries(bgColor)) {
  162. const cue = new shaka.text.Cue(0, 0, '');
  163. cue.backgroundColor = value;
  164. styles.set('.' + key, cue);
  165. }
  166. }
  167. /**
  168. * Parses a string into a Region object.
  169. *
  170. * @param {string} text
  171. * @return {!shaka.text.CueRegion}
  172. * @private
  173. */
  174. static parseRegion_(text) {
  175. const VttTextParser = shaka.text.VttTextParser;
  176. const parser = new shaka.util.TextParser(text);
  177. // The region string looks like this:
  178. // Region: id=fred width=50% lines=3 regionanchor=0%,100%
  179. // viewportanchor=10%,90% scroll=up
  180. const region = new shaka.text.CueRegion();
  181. // Skip 'Region:'
  182. parser.readWord();
  183. parser.skipWhitespace();
  184. let word = parser.readWord();
  185. while (word) {
  186. if (!VttTextParser.parseRegionSetting_(region, word)) {
  187. shaka.log.warning(
  188. 'VTT parser encountered an invalid VTTRegion setting: ', word,
  189. ' The setting will be ignored.');
  190. }
  191. parser.skipWhitespace();
  192. word = parser.readWord();
  193. }
  194. return region;
  195. }
  196. /**
  197. * Parses a style block into a Cue object.
  198. *
  199. * @param {!Array.<string>} text
  200. * @param {!Map.<string, shaka.text.Cue>} styles
  201. * @private
  202. */
  203. static parseStyle_(text, styles) {
  204. // Skip empty blocks.
  205. if (text.length == 1 && !text[0]) {
  206. return;
  207. }
  208. // Skip comment blocks.
  209. if (/^NOTE($|[ \t])/.test(text[0])) {
  210. return;
  211. }
  212. // Only style block are allowed.
  213. if (text[0] != 'STYLE') {
  214. return;
  215. }
  216. /** @type {!Array.<!Array.<string>>} */
  217. const styleBlocks = [];
  218. let lastBlockIndex = -1;
  219. for (let i = 1; i < text.length; i++) {
  220. if (text[i].includes('::cue')) {
  221. styleBlocks.push([]);
  222. lastBlockIndex = styleBlocks.length - 1;
  223. }
  224. if (lastBlockIndex == -1) {
  225. continue;
  226. }
  227. styleBlocks[lastBlockIndex].push(text[i]);
  228. if (text[i].includes('}')) {
  229. lastBlockIndex = -1;
  230. }
  231. }
  232. for (const styleBlock of styleBlocks) {
  233. let styleSelector = 'global';
  234. // Look for what is within parentheses. For example:
  235. // <code>:: cue (b) {</code>, what we are looking for is <code>b</code>
  236. const selector = styleBlock[0].match(/\((.*)\)/);
  237. if (selector) {
  238. styleSelector = selector.pop();
  239. }
  240. // We start at 1 to avoid '::cue' and end earlier to avoid '}'
  241. let propertyLines = styleBlock.slice(1, -1);
  242. if (styleBlock[0].includes('}')) {
  243. const payload = /\{(.*?)\}/.exec(styleBlock[0]);
  244. if (payload) {
  245. propertyLines = payload[1].split(';');
  246. }
  247. }
  248. // Continue styles over multiple selectors if necessary.
  249. // For example,
  250. // ::cue(b) { background: white; } ::cue(b) { color: blue; }
  251. // should set both the background and foreground of bold tags.
  252. let cue = styles.get(styleSelector);
  253. if (!cue) {
  254. cue = new shaka.text.Cue(0, 0, '');
  255. }
  256. let validStyle = false;
  257. for (let i = 0; i < propertyLines.length; i++) {
  258. // We look for CSS properties. As a general rule they are separated by
  259. // <code>:</code>. Eg: <code>color: red;</code>
  260. const lineParts = /^\s*([^:]+):\s*(.*)/.exec(propertyLines[i]);
  261. if (lineParts) {
  262. const name = lineParts[1].trim();
  263. const value = lineParts[2].trim().replace(';', '');
  264. switch (name) {
  265. case 'background-color':
  266. case 'background':
  267. validStyle = true;
  268. cue.backgroundColor = value;
  269. break;
  270. case 'color':
  271. validStyle = true;
  272. cue.color = value;
  273. break;
  274. case 'font-family':
  275. validStyle = true;
  276. cue.fontFamily = value;
  277. break;
  278. case 'font-size':
  279. validStyle = true;
  280. cue.fontSize = value;
  281. break;
  282. case 'font-weight':
  283. if (parseInt(value, 10) >= 700 || value == 'bold') {
  284. validStyle = true;
  285. cue.fontWeight = shaka.text.Cue.fontWeight.BOLD;
  286. }
  287. break;
  288. case 'font-style':
  289. switch (value) {
  290. case 'normal':
  291. validStyle = true;
  292. cue.fontStyle = shaka.text.Cue.fontStyle.NORMAL;
  293. break;
  294. case 'italic':
  295. validStyle = true;
  296. cue.fontStyle = shaka.text.Cue.fontStyle.ITALIC;
  297. break;
  298. case 'oblique':
  299. validStyle = true;
  300. cue.fontStyle = shaka.text.Cue.fontStyle.OBLIQUE;
  301. break;
  302. }
  303. break;
  304. case 'opacity':
  305. validStyle = true;
  306. cue.opacity = parseFloat(value);
  307. break;
  308. case 'text-combine-upright':
  309. validStyle = true;
  310. cue.textCombineUpright = value;
  311. break;
  312. case 'text-shadow':
  313. validStyle = true;
  314. cue.textShadow = value;
  315. break;
  316. case 'white-space':
  317. validStyle = true;
  318. cue.wrapLine = value != 'noWrap';
  319. break;
  320. default:
  321. shaka.log.warning('VTT parser encountered an unsupported style: ',
  322. lineParts);
  323. break;
  324. }
  325. }
  326. }
  327. if (validStyle) {
  328. styles.set(styleSelector, cue);
  329. }
  330. }
  331. }
  332. /**
  333. * Parses a text block into a Cue object.
  334. *
  335. * @param {!Array.<string>} text
  336. * @param {number} timeOffset
  337. * @param {!Array.<!shaka.text.CueRegion>} regions
  338. * @param {!Map.<string, shaka.text.Cue>} styles
  339. * @return {shaka.text.Cue}
  340. * @private
  341. */
  342. static parseCue_(text, timeOffset, regions, styles) {
  343. const VttTextParser = shaka.text.VttTextParser;
  344. // Skip empty blocks.
  345. if (text.length == 1 && !text[0]) {
  346. return null;
  347. }
  348. // Skip comment blocks.
  349. if (/^NOTE($|[ \t])/.test(text[0])) {
  350. return null;
  351. }
  352. // Skip style and region blocks.
  353. if (text[0] == 'STYLE' || text[0] == 'REGION') {
  354. return null;
  355. }
  356. let id = null;
  357. if (!text[0].includes('-->')) {
  358. id = text[0];
  359. text.splice(0, 1);
  360. }
  361. // Parse the times.
  362. const parser = new shaka.util.TextParser(text[0]);
  363. let start = VttTextParser.parseTime_(parser);
  364. const expect = parser.readRegex(/[ \t]+-->[ \t]+/g);
  365. let end = VttTextParser.parseTime_(parser);
  366. if (start == null || expect == null || end == null) {
  367. shaka.log.alwaysWarn(
  368. 'Failed to parse VTT time code. Cue skipped:', id, text);
  369. return null;
  370. }
  371. start += timeOffset;
  372. end += timeOffset;
  373. // Get the payload.
  374. const payload = text.slice(1).join('\n').trim();
  375. let cue = null;
  376. if (styles.has('global')) {
  377. cue = styles.get('global').clone();
  378. cue.startTime = start;
  379. cue.endTime = end;
  380. cue.payload = '';
  381. } else {
  382. cue = new shaka.text.Cue(start, end, '');
  383. }
  384. // Parse optional settings.
  385. parser.skipWhitespace();
  386. let word = parser.readWord();
  387. while (word) {
  388. if (!VttTextParser.parseCueSetting(cue, word, regions)) {
  389. shaka.log.warning('VTT parser encountered an invalid VTT setting: ',
  390. word,
  391. ' The setting will be ignored.');
  392. }
  393. parser.skipWhitespace();
  394. word = parser.readWord();
  395. }
  396. VttTextParser.parseCueStyles(payload, cue, styles);
  397. if (id != null) {
  398. cue.id = id;
  399. }
  400. return cue;
  401. }
  402. /**
  403. * Parses a WebVTT styles from the given payload.
  404. *
  405. * @param {string} payload
  406. * @param {!shaka.text.Cue} rootCue
  407. * @param {!Map.<string, shaka.text.Cue>} styles
  408. */
  409. static parseCueStyles(payload, rootCue, styles) {
  410. const VttTextParser = shaka.text.VttTextParser;
  411. const StringUtils = shaka.util.StringUtils;
  412. const TXml = shaka.util.TXml;
  413. // Optimization for unstyled payloads.
  414. if (!payload.includes('<')) {
  415. rootCue.payload = StringUtils.htmlUnescape(payload);
  416. return;
  417. }
  418. if (styles.size === 0) {
  419. VttTextParser.addDefaultTextColor_(styles);
  420. }
  421. payload = VttTextParser.replaceKaraokeStylePayload_(payload);
  422. payload = VttTextParser.replaceVoiceStylePayload_(payload);
  423. payload = VttTextParser.escapeInvalidChevrons_(payload);
  424. const xmlPayload = '<span>' + payload + '</span>';
  425. let element;
  426. try {
  427. element = TXml.parseXmlString(xmlPayload, 'span');
  428. } catch (e) {
  429. shaka.log.warning('cue parse fail: ', e);
  430. }
  431. if (element) {
  432. const childNodes = element.children;
  433. if (childNodes.length == 1) {
  434. const childNode = childNodes[0];
  435. if (!TXml.isNode(childNode)) {
  436. rootCue.payload = StringUtils.htmlUnescape(payload);
  437. return;
  438. }
  439. }
  440. for (const childNode of childNodes) {
  441. VttTextParser.generateCueFromElement_(childNode, rootCue, styles);
  442. }
  443. } else {
  444. shaka.log.warning('The cue\'s markup could not be parsed: ', payload);
  445. rootCue.payload = StringUtils.htmlUnescape(payload);
  446. }
  447. }
  448. /**
  449. * This method converts invalid > chevrons to HTML entities.
  450. * It also removes < chevrons as per spec.
  451. *
  452. * @param {!string} input
  453. * @return {string}
  454. * @private
  455. */
  456. static escapeInvalidChevrons_(input) {
  457. // Used to map HTML entities to characters.
  458. const htmlEscapes = {
  459. '< ': '',
  460. ' >': ' &gt;',
  461. };
  462. const reEscapedHtml = /(< +>|<\s|\s>)/g;
  463. const reHasEscapedHtml = RegExp(reEscapedHtml.source);
  464. // This check is an optimization, since replace always makes a copy
  465. if (input && reHasEscapedHtml.test(input)) {
  466. return input.replace(reEscapedHtml, (entity) => {
  467. return htmlEscapes[entity] || '';
  468. });
  469. }
  470. return input || '';
  471. }
  472. /**
  473. * Converts voice style tag to be valid for xml parsing
  474. * For example,
  475. * input: <v Shaka>Test
  476. * output: <v.voice-Shaka>Test</v.voice-Shaka>
  477. *
  478. * @param {string} payload
  479. * @return {string} processed payload
  480. * @private
  481. */
  482. static replaceVoiceStylePayload_(payload) {
  483. const voiceTag = 'v';
  484. const names = [];
  485. let nameStart = -1;
  486. let newPayload = '';
  487. let hasVoiceEndTag = false;
  488. for (let i = 0; i < payload.length; i++) {
  489. // This condition is used to manage tags that have end tags.
  490. if (payload[i] === '/') {
  491. const end = payload.indexOf('>', i);
  492. if (end === -1) {
  493. return payload;
  494. }
  495. const tagEnd = payload.substring(i + 1, end);
  496. if (!tagEnd || tagEnd != voiceTag) {
  497. newPayload += payload[i];
  498. continue;
  499. }
  500. hasVoiceEndTag = true;
  501. let tagStart = null;
  502. if (names.length) {
  503. tagStart = names[names.length -1];
  504. }
  505. if (!tagStart) {
  506. newPayload += payload[i];
  507. } else if (tagStart === tagEnd) {
  508. newPayload += '/' + tagEnd + '>';
  509. i += tagEnd.length + 1;
  510. } else {
  511. if (!tagStart.startsWith(voiceTag)) {
  512. newPayload += payload[i];
  513. continue;
  514. }
  515. newPayload += '/' + tagStart + '>';
  516. i += tagEnd.length + 1;
  517. }
  518. } else {
  519. // Here we only want the tag name, not any other payload.
  520. if (payload[i] === '<') {
  521. nameStart = i + 1;
  522. if (payload[nameStart] != voiceTag) {
  523. nameStart = -1;
  524. }
  525. } else if (payload[i] === '>') {
  526. if (nameStart > 0) {
  527. names.push(payload.substr(nameStart, i - nameStart));
  528. nameStart = -1;
  529. }
  530. }
  531. newPayload += payload[i];
  532. }
  533. }
  534. for (const name of names) {
  535. const newName = name.replace(' ', '.voice-');
  536. newPayload = newPayload.replace(`<${name}>`, `<${newName}>`);
  537. newPayload = newPayload.replace(`</${name}>`, `</${newName}>`);
  538. if (!hasVoiceEndTag) {
  539. newPayload += `</${newName}>`;
  540. }
  541. }
  542. return newPayload;
  543. }
  544. /**
  545. * Converts karaoke style tag to be valid for xml parsing
  546. * For example,
  547. * input: Text <00:00:00.450> time <00:00:01.450> 1
  548. * output: Text <div time="00:00:00.450"> time
  549. * <div time="00:00:01.450"> 1</div></div>
  550. *
  551. * @param {string} payload
  552. * @return {string} processed payload
  553. * @private
  554. */
  555. static replaceKaraokeStylePayload_(payload) {
  556. const names = [];
  557. let nameStart = -1;
  558. for (let i = 0; i < payload.length; i++) {
  559. if (payload[i] === '<') {
  560. nameStart = i + 1;
  561. } else if (payload[i] === '>') {
  562. if (nameStart > 0) {
  563. const name = payload.substr(nameStart, i - nameStart);
  564. if (name.match(shaka.text.VttTextParser.timeFormat_)) {
  565. names.push(name);
  566. }
  567. nameStart = -1;
  568. }
  569. }
  570. }
  571. let newPayload = payload;
  572. for (const name of names) {
  573. const replaceTag = '<' + name + '>';
  574. const startTag = '<div time="' + name + '">';
  575. const endTag = '</div>';
  576. newPayload = newPayload.replace(replaceTag, startTag);
  577. newPayload += endTag;
  578. }
  579. return newPayload;
  580. }
  581. /**
  582. * @param {string} value
  583. * @param {string} defaultValue
  584. * @private
  585. */
  586. static getOrDefault_(value, defaultValue) {
  587. if (value && value.length > 0) {
  588. return value;
  589. }
  590. return defaultValue;
  591. }
  592. /**
  593. * Merges values created in parseStyle_
  594. * @param {!shaka.text.Cue} cue
  595. * @param {shaka.text.Cue} refCue
  596. * @private
  597. */
  598. static mergeStyle_(cue, refCue) {
  599. if (!refCue) {
  600. return;
  601. }
  602. const VttTextParser = shaka.text.VttTextParser;
  603. // Overwrites if new value string length > 0
  604. cue.backgroundColor = VttTextParser.getOrDefault_(
  605. refCue.backgroundColor, cue.backgroundColor);
  606. cue.color = VttTextParser.getOrDefault_(
  607. refCue.color, cue.color);
  608. cue.fontFamily = VttTextParser.getOrDefault_(
  609. refCue.fontFamily, cue.fontFamily);
  610. cue.fontSize = VttTextParser.getOrDefault_(
  611. refCue.fontSize, cue.fontSize);
  612. cue.textShadow = VttTextParser.getOrDefault_(
  613. refCue.textShadow, cue.textShadow);
  614. // Overwrite with new values as unable to determine
  615. // if new value is set or not
  616. cue.fontWeight = refCue.fontWeight;
  617. cue.fontStyle = refCue.fontStyle;
  618. cue.opacity = refCue.opacity;
  619. cue.rubyTag = refCue.rubyTag;
  620. cue.textCombineUpright = refCue.textCombineUpright;
  621. cue.wrapLine = refCue.wrapLine;
  622. }
  623. /**
  624. * @param {!shaka.extern.xml.Node} element
  625. * @param {!shaka.text.Cue} rootCue
  626. * @param {!Map.<string, shaka.text.Cue>} styles
  627. * @private
  628. */
  629. static generateCueFromElement_(element, rootCue, styles) {
  630. const VttTextParser = shaka.text.VttTextParser;
  631. const TXml = shaka.util.TXml;
  632. const nestedCue = rootCue.clone();
  633. // We don't want propagate some properties.
  634. nestedCue.nestedCues = [];
  635. nestedCue.payload = '';
  636. nestedCue.rubyTag = '';
  637. // We don't want propagate some position settings
  638. nestedCue.line = null;
  639. nestedCue.region = new shaka.text.CueRegion();
  640. nestedCue.position = null;
  641. nestedCue.size = 0;
  642. if (shaka.util.TXml.isNode(element)) {
  643. const bold = shaka.text.Cue.fontWeight.BOLD;
  644. const italic = shaka.text.Cue.fontStyle.ITALIC;
  645. const underline = shaka.text.Cue.textDecoration.UNDERLINE;
  646. const tags = element.tagName.split(/(?=[ .])+/g);
  647. for (const tag of tags) {
  648. let styleTag = tag;
  649. // White blanks at start indicate that the style is a voice
  650. if (styleTag.startsWith('.voice-')) {
  651. const voice = styleTag.split('-').pop();
  652. styleTag = `v[voice="${voice}"]`;
  653. // The specification allows to have quotes and not, so we check to
  654. // see which one is being used.
  655. if (!styles.has(styleTag)) {
  656. styleTag = `v[voice=${voice}]`;
  657. }
  658. }
  659. if (styles.has(styleTag)) {
  660. VttTextParser.mergeStyle_(nestedCue, styles.get(styleTag));
  661. }
  662. switch (tag) {
  663. case 'br': {
  664. const lineBreakCue = shaka.text.Cue.lineBreak(
  665. nestedCue.startTime, nestedCue.endTime);
  666. rootCue.nestedCues.push(lineBreakCue);
  667. return;
  668. }
  669. case 'b':
  670. nestedCue.fontWeight = bold;
  671. break;
  672. case 'i':
  673. nestedCue.fontStyle = italic;
  674. break;
  675. case 'u':
  676. nestedCue.textDecoration.push(underline);
  677. break;
  678. case 'font': {
  679. const color = element.attributes['color'];
  680. if (color) {
  681. nestedCue.color = color;
  682. }
  683. break;
  684. }
  685. case 'div': {
  686. const time = element.attributes['time'];
  687. if (!time) {
  688. break;
  689. }
  690. const parser = new shaka.util.TextParser(time);
  691. const cueTime = shaka.text.VttTextParser.parseTime_(parser);
  692. if (cueTime) {
  693. nestedCue.startTime = cueTime;
  694. }
  695. break;
  696. }
  697. case 'ruby':
  698. case 'rp':
  699. case 'rt':
  700. nestedCue.rubyTag = tag;
  701. break;
  702. default:
  703. break;
  704. }
  705. }
  706. }
  707. const isTextNode = (item) => shaka.util.TXml.isText(item);
  708. const childNodes = element.children;
  709. if (isTextNode(element) ||
  710. (childNodes.length == 1 && isTextNode(childNodes[0]))) {
  711. // Trailing line breaks may lost when convert cue to HTML tag
  712. // Need to insert line break cue to preserve line breaks
  713. const textArr = TXml.getTextContents(element).split('\n');
  714. let isFirst = true;
  715. for (const text of textArr) {
  716. if (!isFirst) {
  717. const lineBreakCue = shaka.text.Cue.lineBreak(
  718. nestedCue.startTime, nestedCue.endTime);
  719. rootCue.nestedCues.push(lineBreakCue);
  720. }
  721. if (text.length > 0) {
  722. const textCue = nestedCue.clone();
  723. textCue.payload = shaka.util.StringUtils.htmlUnescape(text);
  724. rootCue.nestedCues.push(textCue);
  725. }
  726. isFirst = false;
  727. }
  728. } else {
  729. rootCue.nestedCues.push(nestedCue);
  730. for (const childNode of childNodes) {
  731. VttTextParser.generateCueFromElement_(childNode, nestedCue, styles);
  732. }
  733. }
  734. }
  735. /**
  736. * Parses a WebVTT setting from the given word.
  737. *
  738. * @param {!shaka.text.Cue} cue
  739. * @param {string} word
  740. * @param {!Array.<!shaka.text.CueRegion>} regions
  741. * @return {boolean} True on success.
  742. */
  743. static parseCueSetting(cue, word, regions) {
  744. const VttTextParser = shaka.text.VttTextParser;
  745. let results = null;
  746. if ((results = /^align:(start|middle|center|end|left|right)$/.exec(word))) {
  747. VttTextParser.setTextAlign_(cue, results[1]);
  748. } else if ((results = /^vertical:(lr|rl)$/.exec(word))) {
  749. VttTextParser.setVerticalWritingMode_(cue, results[1]);
  750. } else if ((results = /^size:([\d.]+)%$/.exec(word))) {
  751. cue.size = Number(results[1]);
  752. } else if ((results =
  753. // eslint-disable-next-line max-len
  754. /^position:([\d.]+)%(?:,(line-left|line-right|middle|center|start|end|auto))?$/
  755. .exec(word))) {
  756. cue.position = Number(results[1]);
  757. if (results[2]) {
  758. VttTextParser.setPositionAlign_(cue, results[2]);
  759. }
  760. } else if ((results = /^region:(.*)$/.exec(word))) {
  761. const region = VttTextParser.getRegionById_(regions, results[1]);
  762. if (region) {
  763. cue.region = region;
  764. }
  765. } else {
  766. return VttTextParser.parsedLineValueAndInterpretation_(cue, word);
  767. }
  768. return true;
  769. }
  770. /**
  771. *
  772. * @param {!Array.<!shaka.text.CueRegion>} regions
  773. * @param {string} id
  774. * @return {?shaka.text.CueRegion}
  775. * @private
  776. */
  777. static getRegionById_(regions, id) {
  778. const regionsWithId = regions.filter((region) => {
  779. return region.id == id;
  780. });
  781. if (!regionsWithId.length) {
  782. shaka.log.warning('VTT parser could not find a region with id: ',
  783. id,
  784. ' The region will be ignored.');
  785. return null;
  786. }
  787. goog.asserts.assert(regionsWithId.length == 1,
  788. 'VTTRegion ids should be unique!');
  789. return regionsWithId[0];
  790. }
  791. /**
  792. * Parses a WebVTTRegion setting from the given word.
  793. *
  794. * @param {!shaka.text.CueRegion} region
  795. * @param {string} word
  796. * @return {boolean} True on success.
  797. * @private
  798. */
  799. static parseRegionSetting_(region, word) {
  800. let results = null;
  801. if ((results = /^id=(.*)$/.exec(word))) {
  802. region.id = results[1];
  803. } else if ((results = /^width=(\d{1,2}|100)%$/.exec(word))) {
  804. region.width = Number(results[1]);
  805. } else if ((results = /^lines=(\d+)$/.exec(word))) {
  806. region.height = Number(results[1]);
  807. region.heightUnits = shaka.text.CueRegion.units.LINES;
  808. } else if ((results = /^regionanchor=(\d{1,2}|100)%,(\d{1,2}|100)%$/
  809. .exec(word))) {
  810. region.regionAnchorX = Number(results[1]);
  811. region.regionAnchorY = Number(results[2]);
  812. } else if ((results = /^viewportanchor=(\d{1,2}|100)%,(\d{1,2}|100)%$/
  813. .exec(word))) {
  814. region.viewportAnchorX = Number(results[1]);
  815. region.viewportAnchorY = Number(results[2]);
  816. } else if ((results = /^scroll=up$/.exec(word))) {
  817. region.scroll = shaka.text.CueRegion.scrollMode.UP;
  818. } else {
  819. return false;
  820. }
  821. return true;
  822. }
  823. /**
  824. * @param {!shaka.text.Cue} cue
  825. * @param {string} align
  826. * @private
  827. */
  828. static setTextAlign_(cue, align) {
  829. const Cue = shaka.text.Cue;
  830. if (align == 'middle') {
  831. cue.textAlign = Cue.textAlign.CENTER;
  832. } else {
  833. goog.asserts.assert(align.toUpperCase() in Cue.textAlign,
  834. align.toUpperCase() +
  835. ' Should be in Cue.textAlign values!');
  836. cue.textAlign = Cue.textAlign[align.toUpperCase()];
  837. }
  838. }
  839. /**
  840. * @param {!shaka.text.Cue} cue
  841. * @param {string} align
  842. * @private
  843. */
  844. static setPositionAlign_(cue, align) {
  845. const Cue = shaka.text.Cue;
  846. if (align == 'line-left' || align == 'start') {
  847. cue.positionAlign = Cue.positionAlign.LEFT;
  848. } else if (align == 'line-right' || align == 'end') {
  849. cue.positionAlign = Cue.positionAlign.RIGHT;
  850. } else if (align == 'center' || align == 'middle') {
  851. cue.positionAlign = Cue.positionAlign.CENTER;
  852. } else {
  853. cue.positionAlign = Cue.positionAlign.AUTO;
  854. }
  855. }
  856. /**
  857. * @param {!shaka.text.Cue} cue
  858. * @param {string} value
  859. * @private
  860. */
  861. static setVerticalWritingMode_(cue, value) {
  862. const Cue = shaka.text.Cue;
  863. if (value == 'lr') {
  864. cue.writingMode = Cue.writingMode.VERTICAL_LEFT_TO_RIGHT;
  865. } else {
  866. cue.writingMode = Cue.writingMode.VERTICAL_RIGHT_TO_LEFT;
  867. }
  868. }
  869. /**
  870. * @param {!shaka.text.Cue} cue
  871. * @param {string} word
  872. * @return {boolean}
  873. * @private
  874. */
  875. static parsedLineValueAndInterpretation_(cue, word) {
  876. const Cue = shaka.text.Cue;
  877. let results = null;
  878. if ((results = /^line:([\d.]+)%(?:,(start|end|center))?$/.exec(word))) {
  879. cue.lineInterpretation = Cue.lineInterpretation.PERCENTAGE;
  880. cue.line = Number(results[1]);
  881. if (results[2]) {
  882. goog.asserts.assert(
  883. results[2].toUpperCase() in Cue.lineAlign,
  884. results[2].toUpperCase() + ' Should be in Cue.lineAlign values!');
  885. cue.lineAlign = Cue.lineAlign[results[2].toUpperCase()];
  886. }
  887. } else if ((results =
  888. /^line:(-?\d+)(?:,(start|end|center))?$/.exec(word))) {
  889. cue.lineInterpretation = Cue.lineInterpretation.LINE_NUMBER;
  890. cue.line = Number(results[1]);
  891. if (results[2]) {
  892. goog.asserts.assert(
  893. results[2].toUpperCase() in Cue.lineAlign,
  894. results[2].toUpperCase() + ' Should be in Cue.lineAlign values!');
  895. cue.lineAlign = Cue.lineAlign[results[2].toUpperCase()];
  896. }
  897. } else {
  898. return false;
  899. }
  900. return true;
  901. }
  902. /**
  903. * Parses a WebVTT time from the given parser.
  904. *
  905. * @param {!shaka.util.TextParser} parser
  906. * @return {?number}
  907. * @private
  908. */
  909. static parseTime_(parser) {
  910. const results = parser.readRegex(shaka.text.VttTextParser.timeFormat_);
  911. if (results == null) {
  912. return null;
  913. }
  914. // This capture is optional, but will still be in the array as undefined,
  915. // in which case it is 0.
  916. const hours = Number(results[1]) || 0;
  917. const minutes = Number(results[2]);
  918. const seconds = Number(results[3]);
  919. const milliseconds = Number(results[4]);
  920. if (minutes > 59 || seconds > 59) {
  921. return null;
  922. }
  923. return (milliseconds / 1000) + seconds + (minutes * 60) + (hours * 3600);
  924. }
  925. };
  926. /**
  927. * @const {number}
  928. * @private
  929. */
  930. shaka.text.VttTextParser.MPEG_TIMESCALE_ = 90000;
  931. /**
  932. * @const
  933. * @private {!RegExp}
  934. * @example 00:00.000 or 00:00:00.000 or 0:00:00.000 or
  935. * 00:00.00 or 00:00:00.00 or 0:00:00.00
  936. */
  937. shaka.text.VttTextParser.timeFormat_ =
  938. /(?:(\d{1,}):)?(\d{2}):(\d{2})\.(\d{2,3})/g;
  939. shaka.text.TextEngine.registerParser(
  940. 'text/vtt', () => new shaka.text.VttTextParser());
  941. shaka.text.TextEngine.registerParser(
  942. 'text/vtt; codecs="vtt"', () => new shaka.text.VttTextParser());
  943. shaka.text.TextEngine.registerParser(
  944. 'text/vtt; codecs="wvtt"', () => new shaka.text.VttTextParser());