Source: lib/text/ttml_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.TtmlTextParser');
  7. goog.require('goog.asserts');
  8. goog.require('goog.Uri');
  9. goog.require('shaka.log');
  10. goog.require('shaka.text.Cue');
  11. goog.require('shaka.text.CueRegion');
  12. goog.require('shaka.text.TextEngine');
  13. goog.require('shaka.util.ArrayUtils');
  14. goog.require('shaka.util.Error');
  15. goog.require('shaka.util.StringUtils');
  16. goog.require('shaka.util.TXml');
  17. /**
  18. * @implements {shaka.extern.TextParser}
  19. * @export
  20. */
  21. shaka.text.TtmlTextParser = class {
  22. /**
  23. * @override
  24. * @export
  25. */
  26. parseInit(data) {
  27. goog.asserts.assert(false, 'TTML does not have init segments');
  28. }
  29. /**
  30. * @override
  31. * @export
  32. */
  33. setSequenceMode(sequenceMode) {
  34. // Unused.
  35. }
  36. /**
  37. * @override
  38. * @export
  39. */
  40. setManifestType(manifestType) {
  41. // Unused.
  42. }
  43. /**
  44. * @override
  45. * @export
  46. */
  47. parseMedia(data, time, uri, images) {
  48. const TtmlTextParser = shaka.text.TtmlTextParser;
  49. const TXml = shaka.util.TXml;
  50. const ttpNs = TtmlTextParser.parameterNs_;
  51. const ttsNs = TtmlTextParser.styleNs_;
  52. const str = shaka.util.StringUtils.fromUTF8(data);
  53. const cues = [];
  54. // dont try to parse empty string as
  55. // DOMParser will not throw error but return an errored xml
  56. if (str == '') {
  57. return cues;
  58. }
  59. const tt = TXml.parseXmlString(str, 'tt', /* includeParent= */ true);
  60. if (!tt) {
  61. throw new shaka.util.Error(
  62. shaka.util.Error.Severity.CRITICAL,
  63. shaka.util.Error.Category.TEXT,
  64. shaka.util.Error.Code.INVALID_XML,
  65. 'Failed to parse TTML.');
  66. }
  67. const body = TXml.getElementsByTagName(tt, 'body')[0];
  68. if (!body) {
  69. return [];
  70. }
  71. // Get the framerate, subFrameRate and frameRateMultiplier if applicable.
  72. const frameRate = TXml.getAttributeNSList(tt, ttpNs, 'frameRate');
  73. const subFrameRate = TXml.getAttributeNSList(
  74. tt, ttpNs, 'subFrameRate');
  75. const frameRateMultiplier =
  76. TXml.getAttributeNSList(tt, ttpNs, 'frameRateMultiplier');
  77. const tickRate = TXml.getAttributeNSList(tt, ttpNs, 'tickRate');
  78. const cellResolution = TXml.getAttributeNSList(
  79. tt, ttpNs, 'cellResolution');
  80. const spaceStyle = tt.attributes['xml:space'] || 'default';
  81. const extent = TXml.getAttributeNSList(tt, ttsNs, 'extent');
  82. if (spaceStyle != 'default' && spaceStyle != 'preserve') {
  83. throw new shaka.util.Error(
  84. shaka.util.Error.Severity.CRITICAL,
  85. shaka.util.Error.Category.TEXT,
  86. shaka.util.Error.Code.INVALID_XML,
  87. 'Invalid xml:space value: ' + spaceStyle);
  88. }
  89. const collapseMultipleSpaces = spaceStyle == 'default';
  90. const rateInfo = new TtmlTextParser.RateInfo_(
  91. frameRate, subFrameRate, frameRateMultiplier, tickRate);
  92. const cellResolutionInfo =
  93. TtmlTextParser.getCellResolution_(cellResolution);
  94. const metadata = TXml.getElementsByTagName(tt, 'metadata')[0];
  95. const metadataElements =
  96. (metadata ? metadata.children : []).filter((c) => c != '\n');
  97. const styles = TXml.getElementsByTagName(tt, 'style');
  98. const regionElements = TXml.getElementsByTagName(tt, 'region');
  99. const cueRegions = [];
  100. for (const region of regionElements) {
  101. const cueRegion =
  102. TtmlTextParser.parseCueRegion_(region, styles, extent);
  103. if (cueRegion) {
  104. cueRegions.push(cueRegion);
  105. }
  106. }
  107. // A <body> element should only contain <div> elements, not <p> or <span>
  108. // elements. We used to allow this, but it is non-compliant, and the
  109. // loose nature of our previous parser made it difficult to implement TTML
  110. // nesting more fully.
  111. if (TXml.findChildren(body, 'p').length) {
  112. throw new shaka.util.Error(
  113. shaka.util.Error.Severity.CRITICAL,
  114. shaka.util.Error.Category.TEXT,
  115. shaka.util.Error.Code.INVALID_TEXT_CUE,
  116. '<p> can only be inside <div> in TTML');
  117. }
  118. for (const div of TXml.findChildren(body, 'div')) {
  119. // A <div> element should only contain <p>, not <span>.
  120. if (TXml.findChildren(div, 'span').length) {
  121. throw new shaka.util.Error(
  122. shaka.util.Error.Severity.CRITICAL,
  123. shaka.util.Error.Category.TEXT,
  124. shaka.util.Error.Code.INVALID_TEXT_CUE,
  125. '<span> can only be inside <p> in TTML');
  126. }
  127. }
  128. const cue = TtmlTextParser.parseCue_(
  129. body, time, rateInfo, metadataElements, styles,
  130. regionElements, cueRegions, collapseMultipleSpaces,
  131. cellResolutionInfo, /* parentCueElement= */ null,
  132. /* isContent= */ false, uri, images);
  133. if (cue) {
  134. // According to the TTML spec, backgrounds default to transparent.
  135. // So default the background of the top-level element to transparent.
  136. // Nested elements may override that background color already.
  137. if (!cue.backgroundColor) {
  138. cue.backgroundColor = 'transparent';
  139. }
  140. cues.push(cue);
  141. }
  142. return cues;
  143. }
  144. /**
  145. * Parses a TTML node into a Cue.
  146. *
  147. * @param {!shaka.extern.xml.Node} cueNode
  148. * @param {shaka.extern.TextParser.TimeContext} timeContext
  149. * @param {!shaka.text.TtmlTextParser.RateInfo_} rateInfo
  150. * @param {!Array.<!shaka.extern.xml.Node>} metadataElements
  151. * @param {!Array.<!shaka.extern.xml.Node>} styles
  152. * @param {!Array.<!shaka.extern.xml.Node>} regionElements
  153. * @param {!Array.<!shaka.text.CueRegion>} cueRegions
  154. * @param {boolean} collapseMultipleSpaces
  155. * @param {?{columns: number, rows: number}} cellResolution
  156. * @param {?shaka.extern.xml.Node} parentCueElement
  157. * @param {boolean} isContent
  158. * @param {?(string|undefined)} uri
  159. * @param {!Array.<string>} images
  160. * @return {shaka.text.Cue}
  161. * @private
  162. */
  163. static parseCue_(
  164. cueNode, timeContext, rateInfo, metadataElements, styles, regionElements,
  165. cueRegions, collapseMultipleSpaces, cellResolution, parentCueElement,
  166. isContent, uri, images) {
  167. const TXml = shaka.util.TXml;
  168. const StringUtils = shaka.util.StringUtils;
  169. /** @type {shaka.extern.xml.Node} */
  170. let cueElement;
  171. /** @type {?shaka.extern.xml.Node} */
  172. let parentElement = parentCueElement;
  173. if (TXml.isText(cueNode)) {
  174. if (!isContent) {
  175. // Ignore text elements outside the content. For example, whitespace
  176. // on the same lexical level as the <p> elements, in a document with
  177. // xml:space="preserve", should not be renderer.
  178. return null;
  179. }
  180. // This should generate an "anonymous span" according to the TTML spec.
  181. // So pretend the element was a <span>. parentElement was set above, so
  182. // we should still be able to correctly traverse up for timing
  183. // information later.
  184. /** @type {shaka.extern.xml.Node} */
  185. const span = {
  186. tagName: 'span',
  187. children: [TXml.getTextContents(cueNode)],
  188. attributes: {},
  189. parent: null,
  190. };
  191. cueElement = span;
  192. } else {
  193. cueElement = cueNode;
  194. }
  195. goog.asserts.assert(cueElement, 'cueElement should be non-null!');
  196. let imageElement = null;
  197. for (const nameSpace of shaka.text.TtmlTextParser.smpteNsList_) {
  198. imageElement = shaka.text.TtmlTextParser.getElementsFromCollection_(
  199. cueElement, 'backgroundImage', metadataElements, '#',
  200. nameSpace)[0];
  201. if (imageElement) {
  202. break;
  203. }
  204. }
  205. let imageUri = null;
  206. const backgroundImage = TXml.getAttributeNSList(
  207. cueElement,
  208. shaka.text.TtmlTextParser.smpteNsList_,
  209. 'backgroundImage');
  210. const imsc1ImgUrnTester =
  211. /^(urn:)(mpeg:[a-z0-9][a-z0-9-]{0,31}:)(subs:)([0-9]+)$/;
  212. if (backgroundImage && imsc1ImgUrnTester.test(backgroundImage)) {
  213. const index = parseInt(backgroundImage.split(':').pop(), 10) -1;
  214. if (index >= images.length) {
  215. return null;
  216. }
  217. imageUri = images[index];
  218. } else if (uri && backgroundImage && !backgroundImage.startsWith('#')) {
  219. const baseUri = new goog.Uri(uri);
  220. const relativeUri = new goog.Uri(backgroundImage);
  221. const newUri = baseUri.resolve(relativeUri).toString();
  222. if (newUri) {
  223. imageUri = newUri;
  224. }
  225. }
  226. if (cueNode.tagName == 'p' || imageElement || imageUri) {
  227. isContent = true;
  228. }
  229. const parentIsContent = isContent;
  230. const spaceStyle = cueElement.attributes['xml:space'] ||
  231. (collapseMultipleSpaces ? 'default' : 'preserve');
  232. const localCollapseMultipleSpaces = spaceStyle == 'default';
  233. // Parse any nested cues first.
  234. const isLeafNode = cueElement.children.every(TXml.isText);
  235. const nestedCues = [];
  236. if (!isLeafNode) {
  237. // Otherwise, recurse into the children. Text nodes will convert into
  238. // anonymous spans, which will then be leaf nodes.
  239. for (const childNode of cueElement.children) {
  240. const nestedCue = shaka.text.TtmlTextParser.parseCue_(
  241. childNode,
  242. timeContext,
  243. rateInfo,
  244. metadataElements,
  245. styles,
  246. regionElements,
  247. cueRegions,
  248. localCollapseMultipleSpaces,
  249. cellResolution,
  250. cueElement,
  251. isContent,
  252. uri,
  253. images,
  254. );
  255. // This node may or may not generate a nested cue.
  256. if (nestedCue) {
  257. nestedCues.push(nestedCue);
  258. }
  259. }
  260. }
  261. const isNested = /** @type {boolean} */ (parentCueElement != null);
  262. const textContent = TXml.getTextContents(cueElement);
  263. // In this regex, "\S" means "non-whitespace character".
  264. const hasTextContent = cueElement.children.length &&
  265. textContent &&
  266. /\S/.test(textContent);
  267. const hasTimeAttributes =
  268. cueElement.attributes['begin'] ||
  269. cueElement.attributes['end'] ||
  270. cueElement.attributes['dur'];
  271. if (!hasTimeAttributes && !hasTextContent && cueElement.tagName != 'br' &&
  272. nestedCues.length == 0) {
  273. if (!isNested) {
  274. // Disregards empty <p> elements without time attributes nor content.
  275. // <p begin="..." smpte:backgroundImage="..." /> will go through,
  276. // as some information could be held by its attributes.
  277. // <p /> won't, as it would not be displayed.
  278. return null;
  279. } else if (localCollapseMultipleSpaces) {
  280. // Disregards empty anonymous spans when (local) trim is true.
  281. return null;
  282. }
  283. }
  284. // Get local time attributes.
  285. let {start, end} = shaka.text.TtmlTextParser.parseTime_(
  286. cueElement, rateInfo);
  287. // Resolve local time relative to parent elements. Time elements can appear
  288. // all the way up to 'body', but not 'tt'.
  289. while (parentElement && TXml.isNode(parentElement) &&
  290. parentElement.tagName != 'tt') {
  291. ({start, end} = shaka.text.TtmlTextParser.resolveTime_(
  292. parentElement, rateInfo, start, end));
  293. parentElement =
  294. /** @type {shaka.extern.xml.Node} */ (parentElement.parent);
  295. }
  296. if (start == null) {
  297. start = 0;
  298. }
  299. start += timeContext.periodStart;
  300. // If end is null, that means the duration is effectively infinite.
  301. if (end == null) {
  302. end = Infinity;
  303. } else {
  304. end += timeContext.periodStart;
  305. }
  306. // Clip times to segment boundaries.
  307. // https://github.com/shaka-project/shaka-player/issues/4631
  308. start = Math.max(start, timeContext.segmentStart);
  309. end = Math.min(end, timeContext.segmentEnd);
  310. if (!hasTimeAttributes && nestedCues.length > 0) {
  311. // If no time is defined for this cue, base the timing information on
  312. // the time of the nested cues. In the case of multiple nested cues with
  313. // different start times, it is the text displayer's responsibility to
  314. // make sure that only the appropriate nested cue is drawn at any given
  315. // time.
  316. start = Infinity;
  317. end = 0;
  318. for (const cue of nestedCues) {
  319. start = Math.min(start, cue.startTime);
  320. end = Math.max(end, cue.endTime);
  321. }
  322. }
  323. if (cueElement.tagName == 'br') {
  324. const cue = new shaka.text.Cue(start, end, '');
  325. cue.lineBreak = true;
  326. return cue;
  327. }
  328. let payload = '';
  329. if (isLeafNode) {
  330. // If the childNodes are all text, this is a leaf node. Get the payload.
  331. payload = StringUtils.htmlUnescape(
  332. shaka.util.TXml.getTextContents(cueElement) || '');
  333. if (localCollapseMultipleSpaces) {
  334. // Collapse multiple spaces into one.
  335. payload = payload.replace(/\s+/g, ' ');
  336. }
  337. }
  338. const cue = new shaka.text.Cue(start, end, payload);
  339. cue.nestedCues = nestedCues;
  340. if (!isContent) {
  341. // If this is not a <p> element or a <div> with images, and it has no
  342. // parent that was a <p> element, then it's part of the outer containers
  343. // (e.g. the <body> or a normal <div> element within it).
  344. cue.isContainer = true;
  345. }
  346. if (cellResolution) {
  347. cue.cellResolution = cellResolution;
  348. }
  349. // Get other properties if available.
  350. const regionElement = shaka.text.TtmlTextParser.getElementsFromCollection_(
  351. cueElement, 'region', regionElements, /* prefix= */ '')[0];
  352. // Do not actually apply that region unless it is non-inherited, though.
  353. // This makes it so that, if a parent element has a region, the children
  354. // don't also all independently apply the positioning of that region.
  355. if (cueElement.attributes['region']) {
  356. if (regionElement && regionElement.attributes['xml:id']) {
  357. const regionId = regionElement.attributes['xml:id'];
  358. cue.region = cueRegions.filter((region) => region.id == regionId)[0];
  359. }
  360. }
  361. let regionElementForStyle = regionElement;
  362. if (parentCueElement && isNested && !cueElement.attributes['region'] &&
  363. !cueElement.attributes['style']) {
  364. regionElementForStyle =
  365. shaka.text.TtmlTextParser.getElementsFromCollection_(
  366. parentCueElement, 'region', regionElements, /* prefix= */ '')[0];
  367. }
  368. shaka.text.TtmlTextParser.addStyle_(
  369. cue,
  370. cueElement,
  371. regionElementForStyle,
  372. /** @type {!shaka.extern.xml.Node} */(imageElement),
  373. imageUri,
  374. styles,
  375. /** isNested= */ parentIsContent, // "nested in a <div>" doesn't count.
  376. /** isLeaf= */ (nestedCues.length == 0));
  377. return cue;
  378. }
  379. /**
  380. * Parses an Element into a TextTrackCue or VTTCue.
  381. *
  382. * @param {!shaka.extern.xml.Node} regionElement
  383. * @param {!Array.<!shaka.extern.xml.Node>} styles
  384. * Defined in the top of tt element and used principally for images.
  385. * @param {?string} globalExtent
  386. * @return {shaka.text.CueRegion}
  387. * @private
  388. */
  389. static parseCueRegion_(regionElement, styles, globalExtent) {
  390. const TtmlTextParser = shaka.text.TtmlTextParser;
  391. const region = new shaka.text.CueRegion();
  392. const id = regionElement.attributes['xml:id'];
  393. if (!id) {
  394. shaka.log.warning('TtmlTextParser parser encountered a region with ' +
  395. 'no id. Region will be ignored.');
  396. return null;
  397. }
  398. region.id = id;
  399. let globalResults = null;
  400. if (globalExtent) {
  401. globalResults = TtmlTextParser.percentValues_.exec(globalExtent) ||
  402. TtmlTextParser.pixelValues_.exec(globalExtent);
  403. }
  404. const globalWidth = globalResults ? Number(globalResults[1]) : null;
  405. const globalHeight = globalResults ? Number(globalResults[2]) : null;
  406. let results = null;
  407. let percentage = null;
  408. const extent = TtmlTextParser.getStyleAttributeFromRegion_(
  409. regionElement, styles, 'extent');
  410. if (extent) {
  411. percentage = TtmlTextParser.percentValues_.exec(extent);
  412. results = percentage || TtmlTextParser.pixelValues_.exec(extent);
  413. if (results != null) {
  414. region.width = Number(results[1]);
  415. region.height = Number(results[2]);
  416. if (!percentage) {
  417. if (globalWidth != null) {
  418. region.width = region.width * 100 / globalWidth;
  419. }
  420. if (globalHeight != null) {
  421. region.height = region.height * 100 / globalHeight;
  422. }
  423. }
  424. region.widthUnits = percentage || globalWidth != null ?
  425. shaka.text.CueRegion.units.PERCENTAGE :
  426. shaka.text.CueRegion.units.PX;
  427. region.heightUnits = percentage || globalHeight != null ?
  428. shaka.text.CueRegion.units.PERCENTAGE :
  429. shaka.text.CueRegion.units.PX;
  430. }
  431. }
  432. const origin = TtmlTextParser.getStyleAttributeFromRegion_(
  433. regionElement, styles, 'origin');
  434. if (origin) {
  435. percentage = TtmlTextParser.percentValues_.exec(origin);
  436. results = percentage || TtmlTextParser.pixelValues_.exec(origin);
  437. if (results != null) {
  438. region.viewportAnchorX = Number(results[1]);
  439. region.viewportAnchorY = Number(results[2]);
  440. if (!percentage) {
  441. if (globalHeight != null) {
  442. region.viewportAnchorY = region.viewportAnchorY * 100 /
  443. globalHeight;
  444. }
  445. if (globalWidth != null) {
  446. region.viewportAnchorX = region.viewportAnchorX * 100 /
  447. globalWidth;
  448. }
  449. } else if (!extent) {
  450. region.width = 100 - region.viewportAnchorX;
  451. region.widthUnits = shaka.text.CueRegion.units.PERCENTAGE;
  452. region.height = 100 - region.viewportAnchorY;
  453. region.heightUnits = shaka.text.CueRegion.units.PERCENTAGE;
  454. }
  455. region.viewportAnchorUnits = percentage || globalWidth != null ?
  456. shaka.text.CueRegion.units.PERCENTAGE :
  457. shaka.text.CueRegion.units.PX;
  458. }
  459. }
  460. return region;
  461. }
  462. /**
  463. * Ensures any TTML RGBA's alpha range of 0-255 is converted to 0-1.
  464. * @param {string} color
  465. * @return {string}
  466. * @private
  467. */
  468. static convertTTMLrgbaToHTMLrgba_(color) {
  469. const rgba = color.match(/rgba\(([^)]+)\)/);
  470. if (rgba) {
  471. const values = rgba[1].split(',');
  472. if (values.length == 4) {
  473. values[3] = String(Number(values[3]) / 255);
  474. return 'rgba(' + values.join(',') + ')';
  475. }
  476. }
  477. return color;
  478. }
  479. /**
  480. * Adds applicable style properties to a cue.
  481. *
  482. * @param {!shaka.text.Cue} cue
  483. * @param {!shaka.extern.xml.Node} cueElement
  484. * @param {shaka.extern.xml.Node} region
  485. * @param {shaka.extern.xml.Node} imageElement
  486. * @param {?string} imageUri
  487. * @param {!Array.<!shaka.extern.xml.Node>} styles
  488. * @param {boolean} isNested
  489. * @param {boolean} isLeaf
  490. * @private
  491. */
  492. static addStyle_(
  493. cue, cueElement, region, imageElement, imageUri, styles,
  494. isNested, isLeaf) {
  495. const TtmlTextParser = shaka.text.TtmlTextParser;
  496. const TXml = shaka.util.TXml;
  497. const Cue = shaka.text.Cue;
  498. // Styles should be inherited from regions, if a style property is not
  499. // associated with a Content element (or an anonymous span).
  500. const shouldInheritRegionStyles = isNested || isLeaf;
  501. const direction = TtmlTextParser.getStyleAttribute_(
  502. cueElement, region, styles, 'direction', shouldInheritRegionStyles);
  503. if (direction == 'rtl') {
  504. cue.direction = Cue.direction.HORIZONTAL_RIGHT_TO_LEFT;
  505. }
  506. // Direction attribute specifies one-dimentional writing direction
  507. // (left to right or right to left). Writing mode specifies that
  508. // plus whether text is vertical or horizontal.
  509. // They should not contradict each other. If they do, we give
  510. // preference to writing mode.
  511. const writingMode = TtmlTextParser.getStyleAttribute_(
  512. cueElement, region, styles, 'writingMode', shouldInheritRegionStyles);
  513. // Set cue's direction if the text is horizontal, and cue's writingMode if
  514. // it's vertical.
  515. if (writingMode == 'tb' || writingMode == 'tblr') {
  516. cue.writingMode = Cue.writingMode.VERTICAL_LEFT_TO_RIGHT;
  517. } else if (writingMode == 'tbrl') {
  518. cue.writingMode = Cue.writingMode.VERTICAL_RIGHT_TO_LEFT;
  519. } else if (writingMode == 'rltb' || writingMode == 'rl') {
  520. cue.direction = Cue.direction.HORIZONTAL_RIGHT_TO_LEFT;
  521. } else if (writingMode) {
  522. cue.direction = Cue.direction.HORIZONTAL_LEFT_TO_RIGHT;
  523. }
  524. const align = TtmlTextParser.getStyleAttribute_(
  525. cueElement, region, styles, 'textAlign', true);
  526. if (align) {
  527. cue.positionAlign = TtmlTextParser.textAlignToPositionAlign_[align];
  528. cue.lineAlign = TtmlTextParser.textAlignToLineAlign_[align];
  529. goog.asserts.assert(align.toUpperCase() in Cue.textAlign,
  530. align.toUpperCase() + ' Should be in Cue.textAlign values!');
  531. cue.textAlign = Cue.textAlign[align.toUpperCase()];
  532. } else {
  533. // Default value is START in the TTML spec: https://bit.ly/32OGmvo
  534. // But to make the subtitle render consitent with other players and the
  535. // shaka.text.Cue we use CENTER
  536. cue.textAlign = Cue.textAlign.CENTER;
  537. }
  538. const displayAlign = TtmlTextParser.getStyleAttribute_(
  539. cueElement, region, styles, 'displayAlign', true);
  540. if (displayAlign) {
  541. goog.asserts.assert(displayAlign.toUpperCase() in Cue.displayAlign,
  542. displayAlign.toUpperCase() +
  543. ' Should be in Cue.displayAlign values!');
  544. cue.displayAlign = Cue.displayAlign[displayAlign.toUpperCase()];
  545. }
  546. const color = TtmlTextParser.getStyleAttribute_(
  547. cueElement, region, styles, 'color', shouldInheritRegionStyles);
  548. if (color) {
  549. cue.color = TtmlTextParser.convertTTMLrgbaToHTMLrgba_(color);
  550. }
  551. // Background color should not be set on a container. If this is a nested
  552. // cue, you can set the background. If it's a top-level that happens to
  553. // also be a leaf, you can set the background.
  554. // See https://github.com/shaka-project/shaka-player/issues/2623
  555. // This used to be handled in the displayer, but that is confusing. The Cue
  556. // structure should reflect what you want to happen in the displayer, and
  557. // the displayer shouldn't have to know about TTML.
  558. const backgroundColor = TtmlTextParser.getStyleAttribute_(
  559. cueElement, region, styles, 'backgroundColor',
  560. shouldInheritRegionStyles);
  561. if (backgroundColor) {
  562. cue.backgroundColor =
  563. TtmlTextParser.convertTTMLrgbaToHTMLrgba_(backgroundColor);
  564. }
  565. const border = TtmlTextParser.getStyleAttribute_(
  566. cueElement, region, styles, 'border', shouldInheritRegionStyles);
  567. if (border) {
  568. cue.border = border;
  569. }
  570. const fontFamily = TtmlTextParser.getStyleAttribute_(
  571. cueElement, region, styles, 'fontFamily', shouldInheritRegionStyles);
  572. // See https://github.com/sandflow/imscJS/blob/1.1.3/src/main/js/html.js#L1384
  573. if (fontFamily) {
  574. switch (fontFamily) {
  575. case 'monospaceSerif':
  576. cue.fontFamily = 'Courier New,Liberation Mono,Courier,monospace';
  577. break;
  578. case 'proportionalSansSerif':
  579. cue.fontFamily = 'Arial,Helvetica,Liberation Sans,sans-serif';
  580. break;
  581. case 'sansSerif':
  582. cue.fontFamily = 'sans-serif';
  583. break;
  584. case 'monospaceSansSerif':
  585. cue.fontFamily = 'Consolas,monospace';
  586. break;
  587. case 'proportionalSerif':
  588. cue.fontFamily = 'serif';
  589. break;
  590. default:
  591. cue.fontFamily = fontFamily.split(',').filter((font) => {
  592. return font != 'default';
  593. }).join(',');
  594. break;
  595. }
  596. }
  597. const fontWeight = TtmlTextParser.getStyleAttribute_(
  598. cueElement, region, styles, 'fontWeight', shouldInheritRegionStyles);
  599. if (fontWeight && fontWeight == 'bold') {
  600. cue.fontWeight = Cue.fontWeight.BOLD;
  601. }
  602. const wrapOption = TtmlTextParser.getStyleAttribute_(
  603. cueElement, region, styles, 'wrapOption', shouldInheritRegionStyles);
  604. if (wrapOption && wrapOption == 'noWrap') {
  605. cue.wrapLine = false;
  606. } else {
  607. cue.wrapLine = true;
  608. }
  609. const lineHeight = TtmlTextParser.getStyleAttribute_(
  610. cueElement, region, styles, 'lineHeight', shouldInheritRegionStyles);
  611. if (lineHeight && lineHeight.match(TtmlTextParser.unitValues_)) {
  612. cue.lineHeight = lineHeight;
  613. }
  614. const fontSize = TtmlTextParser.getStyleAttribute_(
  615. cueElement, region, styles, 'fontSize', shouldInheritRegionStyles);
  616. if (fontSize) {
  617. const isValidFontSizeUnit =
  618. fontSize.match(TtmlTextParser.unitValues_) ||
  619. fontSize.match(TtmlTextParser.percentValue_);
  620. if (isValidFontSizeUnit) {
  621. cue.fontSize = fontSize;
  622. }
  623. }
  624. const fontStyle = TtmlTextParser.getStyleAttribute_(
  625. cueElement, region, styles, 'fontStyle', shouldInheritRegionStyles);
  626. if (fontStyle) {
  627. goog.asserts.assert(fontStyle.toUpperCase() in Cue.fontStyle,
  628. fontStyle.toUpperCase() +
  629. ' Should be in Cue.fontStyle values!');
  630. cue.fontStyle = Cue.fontStyle[fontStyle.toUpperCase()];
  631. }
  632. if (imageElement) {
  633. // According to the spec, we should use imageType (camelCase), but
  634. // historically we have checked for imagetype (lowercase).
  635. // This was the case since background image support was first introduced
  636. // in PR #1859, in April 2019, and first released in v2.5.0.
  637. // Now we check for both, although only imageType (camelCase) is to spec.
  638. const backgroundImageType =
  639. imageElement.attributes['imageType'] ||
  640. imageElement.attributes['imagetype'];
  641. const backgroundImageEncoding = imageElement.attributes['encoding'];
  642. const backgroundImageData = (TXml.getTextContents(imageElement)).trim();
  643. if (backgroundImageType == 'PNG' &&
  644. backgroundImageEncoding == 'Base64' &&
  645. backgroundImageData) {
  646. cue.backgroundImage = 'data:image/png;base64,' + backgroundImageData;
  647. }
  648. } else if (imageUri) {
  649. cue.backgroundImage = imageUri;
  650. }
  651. const textOutline = TtmlTextParser.getStyleAttribute_(
  652. cueElement, region, styles, 'textOutline', shouldInheritRegionStyles);
  653. if (textOutline) {
  654. // tts:textOutline isn't natively supported by browsers, but it can be
  655. // mostly replicated using the non-standard -webkit-text-stroke-width and
  656. // -webkit-text-stroke-color properties.
  657. const split = textOutline.split(' ');
  658. if (split[0].match(TtmlTextParser.unitValues_)) {
  659. // There is no defined color, so default to the text color.
  660. cue.textStrokeColor = cue.color;
  661. } else {
  662. cue.textStrokeColor =
  663. TtmlTextParser.convertTTMLrgbaToHTMLrgba_(split[0]);
  664. split.shift();
  665. }
  666. if (split[0] && split[0].match(TtmlTextParser.unitValues_)) {
  667. cue.textStrokeWidth = split[0];
  668. } else {
  669. // If there is no width, or the width is not a number, don't draw a
  670. // border.
  671. cue.textStrokeColor = '';
  672. }
  673. // There is an optional blur radius also, but we have no way of
  674. // replicating that, so ignore it.
  675. }
  676. const letterSpacing = TtmlTextParser.getStyleAttribute_(
  677. cueElement, region, styles, 'letterSpacing', shouldInheritRegionStyles);
  678. if (letterSpacing && letterSpacing.match(TtmlTextParser.unitValues_)) {
  679. cue.letterSpacing = letterSpacing;
  680. }
  681. const linePadding = TtmlTextParser.getStyleAttribute_(
  682. cueElement, region, styles, 'linePadding', shouldInheritRegionStyles);
  683. if (linePadding && linePadding.match(TtmlTextParser.unitValues_)) {
  684. cue.linePadding = linePadding;
  685. }
  686. const opacity = TtmlTextParser.getStyleAttribute_(
  687. cueElement, region, styles, 'opacity', shouldInheritRegionStyles);
  688. if (opacity) {
  689. cue.opacity = parseFloat(opacity);
  690. }
  691. // Text decoration is an array of values which can come both from the
  692. // element's style or be inherited from elements' parent nodes. All of those
  693. // values should be applied as long as they don't contradict each other. If
  694. // they do, elements' own style gets preference.
  695. const textDecorationRegion = TtmlTextParser.getStyleAttributeFromRegion_(
  696. region, styles, 'textDecoration');
  697. if (textDecorationRegion) {
  698. TtmlTextParser.addTextDecoration_(cue, textDecorationRegion);
  699. }
  700. const textDecorationElement = TtmlTextParser.getStyleAttributeFromElement_(
  701. cueElement, styles, 'textDecoration');
  702. if (textDecorationElement) {
  703. TtmlTextParser.addTextDecoration_(cue, textDecorationElement);
  704. }
  705. const textCombine = TtmlTextParser.getStyleAttribute_(
  706. cueElement, region, styles, 'textCombine', shouldInheritRegionStyles);
  707. if (textCombine) {
  708. cue.textCombineUpright = textCombine;
  709. }
  710. const ruby = TtmlTextParser.getStyleAttribute_(
  711. cueElement, region, styles, 'ruby', shouldInheritRegionStyles);
  712. switch (ruby) {
  713. case 'container':
  714. cue.rubyTag = 'ruby';
  715. break;
  716. case 'text':
  717. cue.rubyTag = 'rt';
  718. break;
  719. }
  720. }
  721. /**
  722. * Parses text decoration values and adds/removes them to/from the cue.
  723. *
  724. * @param {!shaka.text.Cue} cue
  725. * @param {string} decoration
  726. * @private
  727. */
  728. static addTextDecoration_(cue, decoration) {
  729. const Cue = shaka.text.Cue;
  730. for (const value of decoration.split(' ')) {
  731. switch (value) {
  732. case 'underline':
  733. if (!cue.textDecoration.includes(Cue.textDecoration.UNDERLINE)) {
  734. cue.textDecoration.push(Cue.textDecoration.UNDERLINE);
  735. }
  736. break;
  737. case 'noUnderline':
  738. if (cue.textDecoration.includes(Cue.textDecoration.UNDERLINE)) {
  739. shaka.util.ArrayUtils.remove(cue.textDecoration,
  740. Cue.textDecoration.UNDERLINE);
  741. }
  742. break;
  743. case 'lineThrough':
  744. if (!cue.textDecoration.includes(Cue.textDecoration.LINE_THROUGH)) {
  745. cue.textDecoration.push(Cue.textDecoration.LINE_THROUGH);
  746. }
  747. break;
  748. case 'noLineThrough':
  749. if (cue.textDecoration.includes(Cue.textDecoration.LINE_THROUGH)) {
  750. shaka.util.ArrayUtils.remove(cue.textDecoration,
  751. Cue.textDecoration.LINE_THROUGH);
  752. }
  753. break;
  754. case 'overline':
  755. if (!cue.textDecoration.includes(Cue.textDecoration.OVERLINE)) {
  756. cue.textDecoration.push(Cue.textDecoration.OVERLINE);
  757. }
  758. break;
  759. case 'noOverline':
  760. if (cue.textDecoration.includes(Cue.textDecoration.OVERLINE)) {
  761. shaka.util.ArrayUtils.remove(cue.textDecoration,
  762. Cue.textDecoration.OVERLINE);
  763. }
  764. break;
  765. }
  766. }
  767. }
  768. /**
  769. * Finds a specified attribute on either the original cue element or its
  770. * associated region and returns the value if the attribute was found.
  771. *
  772. * @param {!shaka.extern.xml.Node} cueElement
  773. * @param {shaka.extern.xml.Node} region
  774. * @param {!Array.<!shaka.extern.xml.Node>} styles
  775. * @param {string} attribute
  776. * @param {boolean=} shouldInheritRegionStyles
  777. * @return {?string}
  778. * @private
  779. */
  780. static getStyleAttribute_(cueElement, region, styles, attribute,
  781. shouldInheritRegionStyles=true) {
  782. // An attribute can be specified on region level or in a styling block
  783. // associated with the region or original element.
  784. const TtmlTextParser = shaka.text.TtmlTextParser;
  785. const attr = TtmlTextParser.getStyleAttributeFromElement_(
  786. cueElement, styles, attribute);
  787. if (attr) {
  788. return attr;
  789. }
  790. if (shouldInheritRegionStyles) {
  791. return TtmlTextParser.getStyleAttributeFromRegion_(
  792. region, styles, attribute);
  793. }
  794. return null;
  795. }
  796. /**
  797. * Finds a specified attribute on the element's associated region
  798. * and returns the value if the attribute was found.
  799. *
  800. * @param {shaka.extern.xml.Node} region
  801. * @param {!Array.<!shaka.extern.xml.Node>} styles
  802. * @param {string} attribute
  803. * @return {?string}
  804. * @private
  805. */
  806. static getStyleAttributeFromRegion_(region, styles, attribute) {
  807. const TXml = shaka.util.TXml;
  808. const ttsNs = shaka.text.TtmlTextParser.styleNs_;
  809. if (!region) {
  810. return null;
  811. }
  812. const attr = TXml.getAttributeNSList(region, ttsNs, attribute);
  813. if (attr) {
  814. return attr;
  815. }
  816. return shaka.text.TtmlTextParser.getInheritedStyleAttribute_(
  817. region, styles, attribute);
  818. }
  819. /**
  820. * Finds a specified attribute on the cue element and returns the value
  821. * if the attribute was found.
  822. *
  823. * @param {!shaka.extern.xml.Node} cueElement
  824. * @param {!Array.<!shaka.extern.xml.Node>} styles
  825. * @param {string} attribute
  826. * @return {?string}
  827. * @private
  828. */
  829. static getStyleAttributeFromElement_(cueElement, styles, attribute) {
  830. const TXml = shaka.util.TXml;
  831. const ttsNs = shaka.text.TtmlTextParser.styleNs_;
  832. // Styling on elements should take precedence
  833. // over the main styling attributes
  834. const elementAttribute = TXml.getAttributeNSList(
  835. cueElement,
  836. ttsNs,
  837. attribute);
  838. if (elementAttribute) {
  839. return elementAttribute;
  840. }
  841. return shaka.text.TtmlTextParser.getInheritedStyleAttribute_(
  842. cueElement, styles, attribute);
  843. }
  844. /**
  845. * Finds a specified attribute on an element's styles and the styles those
  846. * styles inherit from.
  847. *
  848. * @param {!shaka.extern.xml.Node} element
  849. * @param {!Array.<!shaka.extern.xml.Node>} styles
  850. * @param {string} attribute
  851. * @return {?string}
  852. * @private
  853. */
  854. static getInheritedStyleAttribute_(element, styles, attribute) {
  855. const TXml = shaka.util.TXml;
  856. const ttsNs = shaka.text.TtmlTextParser.styleNs_;
  857. const ebuttsNs = shaka.text.TtmlTextParser.styleEbuttsNs_;
  858. const inheritedStyles =
  859. shaka.text.TtmlTextParser.getElementsFromCollection_(
  860. element, 'style', styles, /* prefix= */ '');
  861. let styleValue = null;
  862. // The last value in our styles stack takes the precedence over the others
  863. for (let i = 0; i < inheritedStyles.length; i++) {
  864. // Check ebu namespace first.
  865. let styleAttributeValue = TXml.getAttributeNS(
  866. inheritedStyles[i],
  867. ebuttsNs,
  868. attribute);
  869. if (!styleAttributeValue) {
  870. // Fall back to tts namespace.
  871. styleAttributeValue = TXml.getAttributeNSList(
  872. inheritedStyles[i],
  873. ttsNs,
  874. attribute);
  875. }
  876. if (!styleAttributeValue) {
  877. // Next, check inheritance.
  878. // Styles can inherit from other styles, so traverse up that chain.
  879. styleAttributeValue =
  880. shaka.text.TtmlTextParser.getStyleAttributeFromElement_(
  881. inheritedStyles[i], styles, attribute);
  882. }
  883. if (styleAttributeValue) {
  884. styleValue = styleAttributeValue;
  885. }
  886. }
  887. return styleValue;
  888. }
  889. /**
  890. * Selects items from |collection| whose id matches |attributeName|
  891. * from |element|.
  892. *
  893. * @param {shaka.extern.xml.Node} element
  894. * @param {string} attributeName
  895. * @param {!Array.<shaka.extern.xml.Node>} collection
  896. * @param {string} prefixName
  897. * @param {string=} nsName
  898. * @return {!Array.<!shaka.extern.xml.Node>}
  899. * @private
  900. */
  901. static getElementsFromCollection_(
  902. element, attributeName, collection, prefixName, nsName) {
  903. const items = [];
  904. if (!element || collection.length < 1) {
  905. return items;
  906. }
  907. const attributeValue = shaka.text.TtmlTextParser.getInheritedAttribute_(
  908. element, attributeName, nsName);
  909. if (attributeValue) {
  910. // There could be multiple items in one attribute
  911. // <span style="style1 style2">A cue</span>
  912. const itemNames = attributeValue.split(' ');
  913. for (const name of itemNames) {
  914. for (const item of collection) {
  915. if ((prefixName + item.attributes['xml:id']) == name) {
  916. items.push(item);
  917. break;
  918. }
  919. }
  920. }
  921. }
  922. return items;
  923. }
  924. /**
  925. * Traverses upwards from a given node until a given attribute is found.
  926. *
  927. * @param {!shaka.extern.xml.Node} element
  928. * @param {string} attributeName
  929. * @param {string=} nsName
  930. * @return {?string}
  931. * @private
  932. */
  933. static getInheritedAttribute_(element, attributeName, nsName) {
  934. let ret = null;
  935. const TXml = shaka.util.TXml;
  936. while (!ret) {
  937. ret = nsName ?
  938. TXml.getAttributeNS(element, nsName, attributeName) :
  939. element.attributes[attributeName];
  940. if (ret) {
  941. break;
  942. }
  943. // Element.parentNode can lead to XMLDocument, which is not an Element and
  944. // has no getAttribute().
  945. const parentNode = element.parent;
  946. if (parentNode) {
  947. element = parentNode;
  948. } else {
  949. break;
  950. }
  951. }
  952. return ret;
  953. }
  954. /**
  955. * Factor parent/ancestor time attributes into the parsed time of a
  956. * child/descendent.
  957. *
  958. * @param {!shaka.extern.xml.Node} parentElement
  959. * @param {!shaka.text.TtmlTextParser.RateInfo_} rateInfo
  960. * @param {?number} start The child's start time
  961. * @param {?number} end The child's end time
  962. * @return {{start: ?number, end: ?number}}
  963. * @private
  964. */
  965. static resolveTime_(parentElement, rateInfo, start, end) {
  966. const parentTime = shaka.text.TtmlTextParser.parseTime_(
  967. parentElement, rateInfo);
  968. if (start == null) {
  969. // No start time of your own? Inherit from the parent.
  970. start = parentTime.start;
  971. } else {
  972. // Otherwise, the start time is relative to the parent's start time.
  973. if (parentTime.start != null) {
  974. start += parentTime.start;
  975. }
  976. }
  977. if (end == null) {
  978. // No end time of your own? Inherit from the parent.
  979. end = parentTime.end;
  980. } else {
  981. // Otherwise, the end time is relative to the parent's _start_ time.
  982. // This is not a typo. Both times are relative to the parent's _start_.
  983. if (parentTime.start != null) {
  984. end += parentTime.start;
  985. }
  986. }
  987. return {start, end};
  988. }
  989. /**
  990. * Parse TTML time attributes from the given element.
  991. *
  992. * @param {!shaka.extern.xml.Node} element
  993. * @param {!shaka.text.TtmlTextParser.RateInfo_} rateInfo
  994. * @return {{start: ?number, end: ?number}}
  995. * @private
  996. */
  997. static parseTime_(element, rateInfo) {
  998. const start = shaka.text.TtmlTextParser.parseTimeAttribute_(
  999. element.attributes['begin'], rateInfo);
  1000. let end = shaka.text.TtmlTextParser.parseTimeAttribute_(
  1001. element.attributes['end'], rateInfo);
  1002. const duration = shaka.text.TtmlTextParser.parseTimeAttribute_(
  1003. element.attributes['dur'], rateInfo);
  1004. if (end == null && duration != null) {
  1005. end = start + duration;
  1006. }
  1007. return {start, end};
  1008. }
  1009. /**
  1010. * Parses a TTML time from the given attribute text.
  1011. *
  1012. * @param {string} text
  1013. * @param {!shaka.text.TtmlTextParser.RateInfo_} rateInfo
  1014. * @return {?number}
  1015. * @private
  1016. */
  1017. static parseTimeAttribute_(text, rateInfo) {
  1018. let ret = null;
  1019. const TtmlTextParser = shaka.text.TtmlTextParser;
  1020. if (TtmlTextParser.timeColonFormatFrames_.test(text)) {
  1021. ret = TtmlTextParser.parseColonTimeWithFrames_(rateInfo, text);
  1022. } else if (TtmlTextParser.timeColonFormat_.test(text)) {
  1023. ret = TtmlTextParser.parseTimeFromRegex_(
  1024. TtmlTextParser.timeColonFormat_, text);
  1025. } else if (TtmlTextParser.timeColonFormatMilliseconds_.test(text)) {
  1026. ret = TtmlTextParser.parseTimeFromRegex_(
  1027. TtmlTextParser.timeColonFormatMilliseconds_, text);
  1028. } else if (TtmlTextParser.timeFramesFormat_.test(text)) {
  1029. ret = TtmlTextParser.parseFramesTime_(rateInfo, text);
  1030. } else if (TtmlTextParser.timeTickFormat_.test(text)) {
  1031. ret = TtmlTextParser.parseTickTime_(rateInfo, text);
  1032. } else if (TtmlTextParser.timeHMSFormat_.test(text)) {
  1033. ret = TtmlTextParser.parseTimeFromRegex_(
  1034. TtmlTextParser.timeHMSFormat_, text);
  1035. } else if (text) {
  1036. // It's not empty or null, but it doesn't match a known format.
  1037. throw new shaka.util.Error(
  1038. shaka.util.Error.Severity.CRITICAL,
  1039. shaka.util.Error.Category.TEXT,
  1040. shaka.util.Error.Code.INVALID_TEXT_CUE,
  1041. 'Could not parse cue time range in TTML');
  1042. }
  1043. return ret;
  1044. }
  1045. /**
  1046. * Parses a TTML time in frame format.
  1047. *
  1048. * @param {!shaka.text.TtmlTextParser.RateInfo_} rateInfo
  1049. * @param {string} text
  1050. * @return {?number}
  1051. * @private
  1052. */
  1053. static parseFramesTime_(rateInfo, text) {
  1054. // 75f or 75.5f
  1055. const results = shaka.text.TtmlTextParser.timeFramesFormat_.exec(text);
  1056. const frames = Number(results[1]);
  1057. return frames / rateInfo.frameRate;
  1058. }
  1059. /**
  1060. * Parses a TTML time in tick format.
  1061. *
  1062. * @param {!shaka.text.TtmlTextParser.RateInfo_} rateInfo
  1063. * @param {string} text
  1064. * @return {?number}
  1065. * @private
  1066. */
  1067. static parseTickTime_(rateInfo, text) {
  1068. // 50t or 50.5t
  1069. const results = shaka.text.TtmlTextParser.timeTickFormat_.exec(text);
  1070. const ticks = Number(results[1]);
  1071. return ticks / rateInfo.tickRate;
  1072. }
  1073. /**
  1074. * Parses a TTML colon formatted time containing frames.
  1075. *
  1076. * @param {!shaka.text.TtmlTextParser.RateInfo_} rateInfo
  1077. * @param {string} text
  1078. * @return {?number}
  1079. * @private
  1080. */
  1081. static parseColonTimeWithFrames_(rateInfo, text) {
  1082. // 01:02:43:07 ('07' is frames) or 01:02:43:07.1 (subframes)
  1083. const results = shaka.text.TtmlTextParser.timeColonFormatFrames_.exec(text);
  1084. const hours = Number(results[1]);
  1085. const minutes = Number(results[2]);
  1086. let seconds = Number(results[3]);
  1087. let frames = Number(results[4]);
  1088. const subframes = Number(results[5]) || 0;
  1089. frames += subframes / rateInfo.subFrameRate;
  1090. seconds += frames / rateInfo.frameRate;
  1091. return seconds + (minutes * 60) + (hours * 3600);
  1092. }
  1093. /**
  1094. * Parses a TTML time with a given regex. Expects regex to be some
  1095. * sort of a time-matcher to match hours, minutes, seconds and milliseconds
  1096. *
  1097. * @param {!RegExp} regex
  1098. * @param {string} text
  1099. * @return {?number}
  1100. * @private
  1101. */
  1102. static parseTimeFromRegex_(regex, text) {
  1103. const results = regex.exec(text);
  1104. if (results == null || results[0] == '') {
  1105. return null;
  1106. }
  1107. // This capture is optional, but will still be in the array as undefined,
  1108. // in which case it is 0.
  1109. const hours = Number(results[1]) || 0;
  1110. const minutes = Number(results[2]) || 0;
  1111. const seconds = Number(results[3]) || 0;
  1112. const milliseconds = Number(results[4]) || 0;
  1113. return (milliseconds / 1000) + seconds + (minutes * 60) + (hours * 3600);
  1114. }
  1115. /**
  1116. * If ttp:cellResolution provided returns cell resolution info
  1117. * with number of columns and rows into which the Root Container
  1118. * Region area is divided
  1119. *
  1120. * @param {?string} cellResolution
  1121. * @return {?{columns: number, rows: number}}
  1122. * @private
  1123. */
  1124. static getCellResolution_(cellResolution) {
  1125. if (!cellResolution) {
  1126. return null;
  1127. }
  1128. const matches = /^(\d+) (\d+)$/.exec(cellResolution);
  1129. if (!matches) {
  1130. return null;
  1131. }
  1132. const columns = parseInt(matches[1], 10);
  1133. const rows = parseInt(matches[2], 10);
  1134. return {columns, rows};
  1135. }
  1136. };
  1137. /**
  1138. * @summary
  1139. * Contains information about frame/subframe rate
  1140. * and frame rate multiplier for time in frame format.
  1141. *
  1142. * @example 01:02:03:04(4 frames) or 01:02:03:04.1(4 frames, 1 subframe)
  1143. * @private
  1144. */
  1145. shaka.text.TtmlTextParser.RateInfo_ = class {
  1146. /**
  1147. * @param {?string} frameRate
  1148. * @param {?string} subFrameRate
  1149. * @param {?string} frameRateMultiplier
  1150. * @param {?string} tickRate
  1151. */
  1152. constructor(frameRate, subFrameRate, frameRateMultiplier, tickRate) {
  1153. /**
  1154. * @type {number}
  1155. */
  1156. this.frameRate = Number(frameRate) || 30;
  1157. /**
  1158. * @type {number}
  1159. */
  1160. this.subFrameRate = Number(subFrameRate) || 1;
  1161. /**
  1162. * @type {number}
  1163. */
  1164. this.tickRate = Number(tickRate);
  1165. if (this.tickRate == 0) {
  1166. if (frameRate) {
  1167. this.tickRate = this.frameRate * this.subFrameRate;
  1168. } else {
  1169. this.tickRate = 1;
  1170. }
  1171. }
  1172. if (frameRateMultiplier) {
  1173. const multiplierResults = /^(\d+) (\d+)$/g.exec(frameRateMultiplier);
  1174. if (multiplierResults) {
  1175. const numerator = Number(multiplierResults[1]);
  1176. const denominator = Number(multiplierResults[2]);
  1177. const multiplierNum = numerator / denominator;
  1178. this.frameRate *= multiplierNum;
  1179. }
  1180. }
  1181. }
  1182. };
  1183. /**
  1184. * @const
  1185. * @private {!RegExp}
  1186. * @example 50.17% 10%
  1187. */
  1188. shaka.text.TtmlTextParser.percentValues_ =
  1189. /^(\d{1,2}(?:\.\d+)?|100(?:\.0+)?)% (\d{1,2}(?:\.\d+)?|100(?:\.0+)?)%$/;
  1190. /**
  1191. * @const
  1192. * @private {!RegExp}
  1193. * @example 0.6% 90% 300% 1000%
  1194. */
  1195. shaka.text.TtmlTextParser.percentValue_ = /^(\d{1,4}(?:\.\d+)?|100)%$/;
  1196. /**
  1197. * @const
  1198. * @private {!RegExp}
  1199. * @example 100px, 8em, 0.80c
  1200. */
  1201. shaka.text.TtmlTextParser.unitValues_ = /^(\d+px|\d+em|\d*\.?\d+c)$/;
  1202. /**
  1203. * @const
  1204. * @private {!RegExp}
  1205. * @example 100px
  1206. */
  1207. shaka.text.TtmlTextParser.pixelValues_ = /^(\d+)px (\d+)px$/;
  1208. /**
  1209. * @const
  1210. * @private {!RegExp}
  1211. * @example 00:00:40:07 (7 frames) or 00:00:40:07.1 (7 frames, 1 subframe)
  1212. */
  1213. shaka.text.TtmlTextParser.timeColonFormatFrames_ =
  1214. /^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/;
  1215. /**
  1216. * @const
  1217. * @private {!RegExp}
  1218. * @example 00:00:40 or 00:40
  1219. */
  1220. shaka.text.TtmlTextParser.timeColonFormat_ = /^(?:(\d{2,}):)?(\d{2}):(\d{2})$/;
  1221. /**
  1222. * @const
  1223. * @private {!RegExp}
  1224. * @example 01:02:43.0345555 or 02:43.03 or 02:45.5
  1225. */
  1226. shaka.text.TtmlTextParser.timeColonFormatMilliseconds_ =
  1227. /^(?:(\d{2,}):)?(\d{2}):(\d{2}\.\d+)$/;
  1228. /**
  1229. * @const
  1230. * @private {!RegExp}
  1231. * @example 75f or 75.5f
  1232. */
  1233. shaka.text.TtmlTextParser.timeFramesFormat_ = /^(\d*(?:\.\d*)?)f$/;
  1234. /**
  1235. * @const
  1236. * @private {!RegExp}
  1237. * @example 50t or 50.5t
  1238. */
  1239. shaka.text.TtmlTextParser.timeTickFormat_ = /^(\d*(?:\.\d*)?)t$/;
  1240. /**
  1241. * @const
  1242. * @private {!RegExp}
  1243. * @example 3.45h, 3m or 4.20s
  1244. */
  1245. shaka.text.TtmlTextParser.timeHMSFormat_ =
  1246. new RegExp(['^(?:(\\d*(?:\\.\\d*)?)h)?',
  1247. '(?:(\\d*(?:\\.\\d*)?)m)?',
  1248. '(?:(\\d*(?:\\.\\d*)?)s)?',
  1249. '(?:(\\d*(?:\\.\\d*)?)ms)?$'].join(''));
  1250. /**
  1251. * @const
  1252. * @private {!Object.<string, shaka.text.Cue.lineAlign>}
  1253. */
  1254. shaka.text.TtmlTextParser.textAlignToLineAlign_ = {
  1255. 'left': shaka.text.Cue.lineAlign.START,
  1256. 'center': shaka.text.Cue.lineAlign.CENTER,
  1257. 'right': shaka.text.Cue.lineAlign.END,
  1258. 'start': shaka.text.Cue.lineAlign.START,
  1259. 'end': shaka.text.Cue.lineAlign.END,
  1260. };
  1261. /**
  1262. * @const
  1263. * @private {!Object.<string, shaka.text.Cue.positionAlign>}
  1264. */
  1265. shaka.text.TtmlTextParser.textAlignToPositionAlign_ = {
  1266. 'left': shaka.text.Cue.positionAlign.LEFT,
  1267. 'center': shaka.text.Cue.positionAlign.CENTER,
  1268. 'right': shaka.text.Cue.positionAlign.RIGHT,
  1269. };
  1270. /**
  1271. * The namespace URL for TTML parameters. Can be assigned any name in the TTML
  1272. * document, not just "ttp:", so we use this with getAttributeNS() to ensure
  1273. * that we support arbitrary namespace names.
  1274. *
  1275. * @const {!Array.<string>}
  1276. * @private
  1277. */
  1278. shaka.text.TtmlTextParser.parameterNs_ = [
  1279. 'http://www.w3.org/ns/ttml#parameter',
  1280. 'http://www.w3.org/2006/10/ttaf1#parameter',
  1281. ];
  1282. /**
  1283. * The namespace URL for TTML styles. Can be assigned any name in the TTML
  1284. * document, not just "tts:", so we use this with getAttributeNS() to ensure
  1285. * that we support arbitrary namespace names.
  1286. *
  1287. * @const {!Array.<string>}
  1288. * @private
  1289. */
  1290. shaka.text.TtmlTextParser.styleNs_ = [
  1291. 'http://www.w3.org/ns/ttml#styling',
  1292. 'http://www.w3.org/2006/10/ttaf1#styling',
  1293. ];
  1294. /**
  1295. * The namespace URL for EBU TTML styles. Can be assigned any name in the TTML
  1296. * document, not just "ebutts:", so we use this with getAttributeNS() to ensure
  1297. * that we support arbitrary namespace names.
  1298. *
  1299. * @const {string}
  1300. * @private
  1301. */
  1302. shaka.text.TtmlTextParser.styleEbuttsNs_ = 'urn:ebu:tt:style';
  1303. /**
  1304. * The supported namespace URLs for SMPTE fields.
  1305. * @const {!Array.<string>}
  1306. * @private
  1307. */
  1308. shaka.text.TtmlTextParser.smpteNsList_ = [
  1309. 'http://www.smpte-ra.org/schemas/2052-1/2010/smpte-tt',
  1310. 'http://www.smpte-ra.org/schemas/2052-1/2013/smpte-tt',
  1311. ];
  1312. shaka.text.TextEngine.registerParser(
  1313. 'application/ttml+xml', () => new shaka.text.TtmlTextParser());