Source: lib/text/ui_text_displayer.js

  1. /*! @license
  2. * Shaka Player
  3. * Copyright 2016 Google LLC
  4. * SPDX-License-Identifier: Apache-2.0
  5. */
  6. goog.provide('shaka.text.UITextDisplayer');
  7. goog.require('goog.asserts');
  8. goog.require('shaka.log');
  9. goog.require('shaka.text.Cue');
  10. goog.require('shaka.text.CueRegion');
  11. goog.require('shaka.text.Utils');
  12. goog.require('shaka.util.Dom');
  13. goog.require('shaka.util.EventManager');
  14. goog.require('shaka.util.Timer');
  15. /**
  16. * The text displayer plugin for the Shaka Player UI. Can also be used directly
  17. * by providing an appropriate container element.
  18. *
  19. * @implements {shaka.extern.TextDisplayer}
  20. * @final
  21. * @export
  22. */
  23. shaka.text.UITextDisplayer = class {
  24. /**
  25. * Constructor.
  26. * @param {HTMLMediaElement} video
  27. * @param {HTMLElement} videoContainer
  28. */
  29. constructor(video, videoContainer) {
  30. goog.asserts.assert(videoContainer, 'videoContainer should be valid.');
  31. if (!document.fullscreenEnabled) {
  32. shaka.log.alwaysWarn('Using UITextDisplayer in a browser without ' +
  33. 'Fullscreen API support causes subtitles to not be rendered in ' +
  34. 'fullscreen');
  35. }
  36. /** @private {boolean} */
  37. this.isTextVisible_ = false;
  38. /** @private {!Array<!shaka.text.Cue>} */
  39. this.cues_ = [];
  40. /** @private {HTMLMediaElement} */
  41. this.video_ = video;
  42. /** @private {HTMLElement} */
  43. this.videoContainer_ = videoContainer;
  44. /** @private {?number} */
  45. this.aspectRatio_ = null;
  46. /** @private {?shaka.extern.TextDisplayerConfiguration} */
  47. this.config_ = null;
  48. /** @type {HTMLElement} */
  49. this.textContainer_ = shaka.util.Dom.createHTMLElement('div');
  50. this.textContainer_.classList.add('shaka-text-container');
  51. // Set the subtitles text-centered by default.
  52. this.textContainer_.style.textAlign = 'center';
  53. // Set the captions in the middle horizontally by default.
  54. this.textContainer_.style.display = 'flex';
  55. this.textContainer_.style.flexDirection = 'column';
  56. this.textContainer_.style.alignItems = 'center';
  57. // Set the captions at the bottom by default.
  58. this.textContainer_.style.justifyContent = 'flex-end';
  59. this.videoContainer_.appendChild(this.textContainer_);
  60. /** @private {shaka.util.Timer} */
  61. this.captionsTimer_ = new shaka.util.Timer(() => {
  62. if (!this.video_.paused) {
  63. this.updateCaptions_();
  64. }
  65. });
  66. this.configureCaptionsTimer_();
  67. /**
  68. * Maps cues to cue elements. Specifically points out the wrapper element of
  69. * the cue (e.g. the HTML element to put nested cues inside).
  70. * @private {Map<!shaka.text.Cue, !{
  71. * cueElement: !HTMLElement,
  72. * regionElement: HTMLElement,
  73. * wrapper: !HTMLElement
  74. * }>}
  75. */
  76. this.currentCuesMap_ = new Map();
  77. /** @private {shaka.util.EventManager} */
  78. this.eventManager_ = new shaka.util.EventManager();
  79. this.eventManager_.listen(document, 'fullscreenchange', () => {
  80. this.updateCaptions_(/* forceUpdate= */ true);
  81. });
  82. this.eventManager_.listen(this.video_, 'seeking', () => {
  83. this.updateCaptions_(/* forceUpdate= */ true);
  84. });
  85. this.eventManager_.listen(this.video_, 'ratechange', () => {
  86. this.configureCaptionsTimer_();
  87. });
  88. // From: https://html.spec.whatwg.org/multipage/media.html#dom-video-videowidth
  89. // Whenever the natural width or natural height of the video changes
  90. // (including, for example, because the selected video track was changed),
  91. // if the element's readyState attribute is not HAVE_NOTHING, the user
  92. // agent must queue a media element task given the media element to fire an
  93. // event named resize at the media element.
  94. this.eventManager_.listen(this.video_, 'resize', () => {
  95. const element = /** @type {!HTMLVideoElement} */ (this.video_);
  96. const width = element.videoWidth;
  97. const height = element.videoHeight;
  98. if (width && height) {
  99. this.aspectRatio_ = width / height;
  100. } else {
  101. this.aspectRatio_ = null;
  102. }
  103. });
  104. /** @private {ResizeObserver} */
  105. this.resizeObserver_ = null;
  106. if ('ResizeObserver' in window) {
  107. this.resizeObserver_ = new ResizeObserver(() => {
  108. this.updateCaptions_(/* forceUpdate= */ true);
  109. });
  110. this.resizeObserver_.observe(this.textContainer_);
  111. }
  112. /** @private {Map<string, !HTMLElement>} */
  113. this.regionElements_ = new Map();
  114. }
  115. /**
  116. * @override
  117. * @export
  118. */
  119. configure(config) {
  120. this.config_ = config;
  121. this.configureCaptionsTimer_();
  122. }
  123. /**
  124. * @override
  125. * @export
  126. */
  127. append(cues) {
  128. // Clone the cues list for performance optimization. We can avoid the cues
  129. // list growing during the comparisons for duplicate cues.
  130. // See: https://github.com/shaka-project/shaka-player/issues/3018
  131. const cuesList = [...this.cues_];
  132. for (const cue of shaka.text.Utils.removeDuplicates(cues)) {
  133. // When a VTT cue spans a segment boundary, the cue will be duplicated
  134. // into two segments.
  135. // To avoid displaying duplicate cues, if the current cue list already
  136. // contains the cue, skip it.
  137. const containsCue = cuesList.some(
  138. (cueInList) => shaka.text.Cue.equal(cueInList, cue));
  139. if (!containsCue) {
  140. this.cues_.push(cue);
  141. }
  142. }
  143. if (this.cues_.length) {
  144. this.configureCaptionsTimer_();
  145. }
  146. this.updateCaptions_();
  147. }
  148. /**
  149. * @override
  150. * @export
  151. */
  152. destroy() {
  153. // Return resolved promise if destroy() has been called.
  154. if (!this.textContainer_) {
  155. return Promise.resolve();
  156. }
  157. // Remove the text container element from the UI.
  158. this.videoContainer_.removeChild(this.textContainer_);
  159. this.textContainer_ = null;
  160. this.isTextVisible_ = false;
  161. this.cues_ = [];
  162. if (this.captionsTimer_) {
  163. this.captionsTimer_.stop();
  164. this.captionsTimer_ = null;
  165. }
  166. this.currentCuesMap_.clear();
  167. // Tear-down the event manager to ensure messages stop moving around.
  168. if (this.eventManager_) {
  169. this.eventManager_.release();
  170. this.eventManager_ = null;
  171. }
  172. if (this.resizeObserver_) {
  173. this.resizeObserver_.disconnect();
  174. this.resizeObserver_ = null;
  175. }
  176. return Promise.resolve();
  177. }
  178. /**
  179. * @override
  180. * @export
  181. */
  182. remove(start, end) {
  183. // Return false if destroy() has been called.
  184. if (!this.textContainer_) {
  185. return false;
  186. }
  187. // Remove the cues out of the time range.
  188. const oldNumCues = this.cues_.length;
  189. this.cues_ = this.cues_.filter(
  190. (cue) => cue.startTime < start || cue.endTime >= end);
  191. // If anything was actually removed in this process, force the captions to
  192. // update. This makes sure that the currently-displayed cues will stop
  193. // displaying if removed (say, due to the user changing languages).
  194. const forceUpdate = oldNumCues > this.cues_.length;
  195. this.updateCaptions_(forceUpdate);
  196. if (!this.cues_.length) {
  197. this.configureCaptionsTimer_();
  198. }
  199. return true;
  200. }
  201. /**
  202. * @override
  203. * @export
  204. */
  205. isTextVisible() {
  206. return this.isTextVisible_;
  207. }
  208. /**
  209. * @override
  210. * @export
  211. */
  212. setTextVisibility(on) {
  213. this.isTextVisible_ = on;
  214. this.updateCaptions_(/* forceUpdate= */ true);
  215. }
  216. /**
  217. * @override
  218. * @export
  219. */
  220. setTextLanguage(language) {
  221. if (language && language != 'und') {
  222. this.textContainer_.setAttribute('lang', language);
  223. } else {
  224. this.textContainer_.setAttribute('lang', '');
  225. }
  226. }
  227. /**
  228. * @override
  229. * @export
  230. */
  231. enableTextDisplayer() {
  232. }
  233. /**
  234. * @private
  235. */
  236. configureCaptionsTimer_() {
  237. if (this.captionsTimer_) {
  238. if (this.cues_.length) {
  239. const captionsUpdatePeriod = this.config_ ?
  240. this.config_.captionsUpdatePeriod : 0.25;
  241. const updateTime = captionsUpdatePeriod /
  242. Math.max(1, Math.abs(this.video_.playbackRate));
  243. this.captionsTimer_.tickEvery(updateTime);
  244. } else {
  245. this.captionsTimer_.stop();
  246. }
  247. }
  248. }
  249. /**
  250. * @private
  251. */
  252. isElementUnderTextContainer_(elemToCheck) {
  253. while (elemToCheck != null) {
  254. if (elemToCheck == this.textContainer_) {
  255. return true;
  256. }
  257. elemToCheck = elemToCheck.parentElement;
  258. }
  259. return false;
  260. }
  261. /**
  262. * @param {!Array<!shaka.text.Cue>} cues
  263. * @param {!HTMLElement} container
  264. * @param {number} currentTime
  265. * @param {!Array<!shaka.text.Cue>} parents
  266. * @private
  267. */
  268. updateCuesRecursive_(cues, container, currentTime, parents) {
  269. // Set to true if the cues have changed in some way, which will require
  270. // DOM changes. E.g. if a cue was added or removed.
  271. let updateDOM = false;
  272. /**
  273. * The elements to remove from the DOM.
  274. * Some of these elements may be added back again, if their corresponding
  275. * cue is in toPlant.
  276. * These elements are only removed if updateDOM is true.
  277. * @type {!Array<!HTMLElement>}
  278. */
  279. const toUproot = [];
  280. /**
  281. * The cues whose corresponding elements should be in the DOM.
  282. * Some of these might be new, some might have been displayed beforehand.
  283. * These will only be added if updateDOM is true.
  284. * @type {!Array<!shaka.text.Cue>}
  285. */
  286. const toPlant = [];
  287. for (const cue of cues) {
  288. parents.push(cue);
  289. let cueRegistry = this.currentCuesMap_.get(cue);
  290. const shouldBeDisplayed =
  291. cue.startTime <= currentTime && cue.endTime > currentTime;
  292. let wrapper = cueRegistry ? cueRegistry.wrapper : null;
  293. if (cueRegistry) {
  294. // If the cues are replanted, all existing cues should be uprooted,
  295. // even ones which are going to be planted again.
  296. toUproot.push(cueRegistry.cueElement);
  297. // Also uproot all displayed region elements.
  298. if (cueRegistry.regionElement) {
  299. toUproot.push(cueRegistry.regionElement);
  300. }
  301. // If the cue should not be displayed, remove it entirely.
  302. if (!shouldBeDisplayed) {
  303. // Since something has to be removed, we will need to update the DOM.
  304. updateDOM = true;
  305. this.currentCuesMap_.delete(cue);
  306. cueRegistry = null;
  307. }
  308. }
  309. if (shouldBeDisplayed) {
  310. toPlant.push(cue);
  311. if (!cueRegistry) {
  312. // The cue has to be made!
  313. this.createCue_(cue, parents);
  314. cueRegistry = this.currentCuesMap_.get(cue);
  315. wrapper = cueRegistry.wrapper;
  316. updateDOM = true;
  317. } else if (!this.isElementUnderTextContainer_(wrapper)) {
  318. // We found that the wrapper needs to be in the DOM
  319. updateDOM = true;
  320. }
  321. }
  322. // Recursively check the nested cues, to see if they need to be added or
  323. // removed.
  324. // If wrapper is null, that means that the cue is not only not being
  325. // displayed currently, it also was not removed this tick. So it's
  326. // guaranteed that the children will neither need to be added nor removed.
  327. if (cue.nestedCues.length > 0 && wrapper) {
  328. this.updateCuesRecursive_(
  329. cue.nestedCues, wrapper, currentTime, parents);
  330. }
  331. const topCue = parents.pop();
  332. goog.asserts.assert(topCue == cue, 'Parent cues should be kept in order');
  333. }
  334. if (updateDOM) {
  335. for (const element of toUproot) {
  336. // NOTE: Because we uproot shared region elements, too, we might hit an
  337. // element here that has no parent because we've already processed it.
  338. if (element.parentElement) {
  339. element.parentElement.removeChild(element);
  340. }
  341. }
  342. toPlant.sort((a, b) => {
  343. if (a.startTime != b.startTime) {
  344. return a.startTime - b.startTime;
  345. } else {
  346. return a.endTime - b.endTime;
  347. }
  348. });
  349. for (const cue of toPlant) {
  350. const cueRegistry = this.currentCuesMap_.get(cue);
  351. goog.asserts.assert(cueRegistry, 'cueRegistry should exist.');
  352. if (cueRegistry.regionElement) {
  353. if (cueRegistry.regionElement.contains(container)) {
  354. cueRegistry.regionElement.removeChild(container);
  355. }
  356. container.appendChild(cueRegistry.regionElement);
  357. cueRegistry.regionElement.appendChild(cueRegistry.cueElement);
  358. } else {
  359. container.appendChild(cueRegistry.cueElement);
  360. }
  361. }
  362. }
  363. }
  364. /**
  365. * Display the current captions.
  366. * @param {boolean=} forceUpdate
  367. * @private
  368. */
  369. updateCaptions_(forceUpdate = false) {
  370. if (!this.textContainer_) {
  371. return;
  372. }
  373. const currentTime = this.video_.currentTime;
  374. if (!this.isTextVisible_ || forceUpdate) {
  375. // Remove child elements from all regions.
  376. for (const regionElement of this.regionElements_.values()) {
  377. shaka.util.Dom.removeAllChildren(regionElement);
  378. }
  379. // Remove all top-level elements in the text container.
  380. shaka.util.Dom.removeAllChildren(this.textContainer_);
  381. // Clear the element maps.
  382. this.currentCuesMap_.clear();
  383. this.regionElements_.clear();
  384. }
  385. if (this.isTextVisible_) {
  386. // Log currently attached cue elements for verification, later.
  387. const previousCuesMap = new Map();
  388. if (goog.DEBUG) {
  389. for (const cue of this.currentCuesMap_.keys()) {
  390. previousCuesMap.set(cue, this.currentCuesMap_.get(cue));
  391. }
  392. }
  393. // Update the cues.
  394. this.updateCuesRecursive_(
  395. this.cues_, this.textContainer_, currentTime, /* parents= */ []);
  396. if (goog.DEBUG) {
  397. // Previously, we had an issue (#2076) where cues sometimes were not
  398. // properly removed from the DOM. It is not clear if this issue still
  399. // happens, so the previous fix for it has been changed to an assert.
  400. for (const cue of previousCuesMap.keys()) {
  401. if (!this.currentCuesMap_.has(cue)) {
  402. // TODO: If the problem does not appear again, then we should remove
  403. // this assert (and the previousCuesMap code) in Shaka v4.
  404. const cueElement = previousCuesMap.get(cue).cueElement;
  405. goog.asserts.assert(
  406. !cueElement.parentNode, 'Cue was not properly removed!');
  407. }
  408. }
  409. }
  410. }
  411. }
  412. /**
  413. * Compute a unique internal id:
  414. * Regions can reuse the id but have different dimensions, we need to
  415. * consider those differences
  416. * @param {shaka.text.CueRegion} region
  417. * @private
  418. */
  419. generateRegionId_(region) {
  420. const percentageUnit = shaka.text.CueRegion.units.PERCENTAGE;
  421. const heightUnit = region.heightUnits == percentageUnit ? '%' : 'px';
  422. const viewportAnchorUnit =
  423. region.viewportAnchorUnits == percentageUnit ? '%' : 'px';
  424. const uniqueRegionId = `${region.id}_${
  425. region.width}x${region.height}${heightUnit}-${
  426. region.viewportAnchorX}x${region.viewportAnchorY}${viewportAnchorUnit}`;
  427. return uniqueRegionId;
  428. }
  429. /**
  430. * Get or create a region element corresponding to the cue region. These are
  431. * cached by ID.
  432. *
  433. * @param {!shaka.text.Cue} cue
  434. * @return {!HTMLElement}
  435. * @private
  436. */
  437. getRegionElement_(cue) {
  438. const region = cue.region;
  439. // from https://dvcs.w3.org/hg/text-tracks/raw-file/default/608toVTT/608toVTT.html#caption-window-size
  440. // if aspect ratio is 4/3, use that value, otherwise, use the 16:9 value
  441. const lineWidthMultiple = this.aspectRatio_ === 4/3 ? 2.5 : 1.9;
  442. const lineHeightMultiple = 5.33;
  443. const regionId = this.generateRegionId_(region);
  444. if (this.regionElements_.has(regionId)) {
  445. return this.regionElements_.get(regionId);
  446. }
  447. const regionElement = shaka.util.Dom.createHTMLElement('span');
  448. const linesUnit = shaka.text.CueRegion.units.LINES;
  449. const percentageUnit = shaka.text.CueRegion.units.PERCENTAGE;
  450. const pixelUnit = shaka.text.CueRegion.units.PX;
  451. let heightUnit = region.heightUnits == percentageUnit ? '%' : 'px';
  452. let widthUnit = region.widthUnits == percentageUnit ? '%' : 'px';
  453. const viewportAnchorUnit =
  454. region.viewportAnchorUnits == percentageUnit ? '%' : 'px';
  455. regionElement.id = 'shaka-text-region---' + regionId;
  456. regionElement.classList.add('shaka-text-region');
  457. regionElement.style.position = 'absolute';
  458. let regionHeight = region.height;
  459. let regionWidth = region.width;
  460. if (region.heightUnits === linesUnit) {
  461. regionHeight = region.height * lineHeightMultiple;
  462. heightUnit = '%';
  463. }
  464. if (region.widthUnits === linesUnit) {
  465. regionWidth = region.width * lineWidthMultiple;
  466. widthUnit = '%';
  467. }
  468. regionElement.style.height = regionHeight + heightUnit;
  469. regionElement.style.width = regionWidth + widthUnit;
  470. if (region.viewportAnchorUnits === linesUnit) {
  471. // from https://dvcs.w3.org/hg/text-tracks/raw-file/default/608toVTT/608toVTT.html#positioning-in-cea-708
  472. let top = region.viewportAnchorY / 75 * 100;
  473. const windowWidth = this.aspectRatio_ === 4/3 ? 160 : 210;
  474. let left = region.viewportAnchorX / windowWidth * 100;
  475. // adjust top and left values based on the region anchor and window size
  476. top -= region.regionAnchorY * regionHeight / 100;
  477. left -= region.regionAnchorX * regionWidth / 100;
  478. regionElement.style.top = top + '%';
  479. regionElement.style.left = left + '%';
  480. } else {
  481. regionElement.style.top = region.viewportAnchorY -
  482. region.regionAnchorY * regionHeight / 100 + viewportAnchorUnit;
  483. regionElement.style.left = region.viewportAnchorX -
  484. region.regionAnchorX * regionWidth / 100 + viewportAnchorUnit;
  485. }
  486. if (region.heightUnits !== pixelUnit &&
  487. region.widthUnits !== pixelUnit &&
  488. region.viewportAnchorUnits !== pixelUnit) {
  489. // Clip region
  490. const top = parseInt(regionElement.style.top.slice(0, -1), 10) || 0;
  491. const left = parseInt(regionElement.style.left.slice(0, -1), 10) || 0;
  492. const height = parseInt(regionElement.style.height.slice(0, -1), 10) || 0;
  493. const width = parseInt(regionElement.style.width.slice(0, -1), 10) || 0;
  494. const realTop = Math.max(0, Math.min(100 - height, top));
  495. const realLeft = Math.max(0, Math.min(100 - width, left));
  496. regionElement.style.top = realTop + '%';
  497. regionElement.style.left = realLeft + '%';
  498. }
  499. regionElement.style.display = 'flex';
  500. regionElement.style.flexDirection = 'column';
  501. regionElement.style.alignItems = 'center';
  502. if (cue.displayAlign == shaka.text.Cue.displayAlign.BEFORE) {
  503. regionElement.style.justifyContent = 'flex-start';
  504. } else if (cue.displayAlign == shaka.text.Cue.displayAlign.CENTER) {
  505. regionElement.style.justifyContent = 'center';
  506. } else {
  507. regionElement.style.justifyContent = 'flex-end';
  508. }
  509. this.regionElements_.set(regionId, regionElement);
  510. return regionElement;
  511. }
  512. /**
  513. * Creates the object for a cue.
  514. *
  515. * @param {!shaka.text.Cue} cue
  516. * @param {!Array<!shaka.text.Cue>} parents
  517. * @private
  518. */
  519. createCue_(cue, parents) {
  520. const isNested = parents.length > 1;
  521. let type = isNested ? 'span' : 'div';
  522. if (cue.lineBreak) {
  523. type = 'br';
  524. }
  525. if (cue.rubyTag) {
  526. type = cue.rubyTag;
  527. }
  528. const needWrapper = !isNested && cue.nestedCues.length > 0;
  529. // Nested cues are inline elements. Top-level cues are block elements.
  530. const cueElement = shaka.util.Dom.createHTMLElement(type);
  531. if (type != 'br') {
  532. this.setCaptionStyles_(cueElement, cue, parents, needWrapper);
  533. }
  534. let regionElement = null;
  535. if (cue.region && cue.region.id) {
  536. regionElement = this.getRegionElement_(cue);
  537. }
  538. let wrapper = cueElement;
  539. if (needWrapper) {
  540. // Create a wrapper element which will serve to contain all children into
  541. // a single item. This ensures that nested span elements appear
  542. // horizontally and br elements occupy no vertical space.
  543. wrapper = shaka.util.Dom.createHTMLElement('span');
  544. wrapper.classList.add('shaka-text-wrapper');
  545. wrapper.style.backgroundColor = cue.backgroundColor;
  546. wrapper.style.lineHeight = 'normal';
  547. cueElement.appendChild(wrapper);
  548. }
  549. this.currentCuesMap_.set(cue, {cueElement, wrapper, regionElement});
  550. }
  551. /**
  552. * Compute cue position alignment
  553. * See https://www.w3.org/TR/webvtt1/#webvtt-cue-position-alignment
  554. *
  555. * @param {!shaka.text.Cue} cue
  556. * @private
  557. */
  558. computeCuePositionAlignment_(cue) {
  559. const Cue = shaka.text.Cue;
  560. const {direction, positionAlign, textAlign} = cue;
  561. if (positionAlign !== Cue.positionAlign.AUTO) {
  562. // Position align is not AUTO: use it
  563. return positionAlign;
  564. }
  565. // Position align is AUTO: use text align to compute its value
  566. if (textAlign === Cue.textAlign.LEFT ||
  567. (textAlign === Cue.textAlign.START &&
  568. direction === Cue.direction.HORIZONTAL_LEFT_TO_RIGHT) ||
  569. (textAlign === Cue.textAlign.END &&
  570. direction === Cue.direction.HORIZONTAL_RIGHT_TO_LEFT)) {
  571. return Cue.positionAlign.LEFT;
  572. }
  573. if (textAlign === Cue.textAlign.RIGHT ||
  574. (textAlign === Cue.textAlign.START &&
  575. direction === Cue.direction.HORIZONTAL_RIGHT_TO_LEFT) ||
  576. (textAlign === Cue.textAlign.END &&
  577. direction === Cue.direction.HORIZONTAL_LEFT_TO_RIGHT)) {
  578. return Cue.positionAlign.RIGHT;
  579. }
  580. return Cue.positionAlign.CENTER;
  581. }
  582. /**
  583. * @param {!HTMLElement} cueElement
  584. * @param {!shaka.text.Cue} cue
  585. * @param {!Array<!shaka.text.Cue>} parents
  586. * @param {boolean} hasWrapper
  587. * @private
  588. */
  589. setCaptionStyles_(cueElement, cue, parents, hasWrapper) {
  590. const Cue = shaka.text.Cue;
  591. const inherit =
  592. (cb) => shaka.text.UITextDisplayer.inheritProperty_(parents, cb);
  593. const style = cueElement.style;
  594. const isLeaf = cue.nestedCues.length == 0;
  595. const isNested = parents.length > 1;
  596. // TODO: wrapLine is not yet supported. Lines always wrap.
  597. // White space should be preserved if emitted by the text parser. It's the
  598. // job of the parser to omit any whitespace that should not be displayed.
  599. // Using 'pre-wrap' means that whitespace is preserved even at the end of
  600. // the text, but that lines which overflow can still be broken.
  601. style.whiteSpace = 'pre-wrap';
  602. // Using 'break-spaces' would be better, as it would preserve even trailing
  603. // spaces, but that only shipped in Chrome 76. As of July 2020, Safari
  604. // still has not implemented break-spaces, and the original Chromecast will
  605. // never have this feature since it no longer gets firmware updates.
  606. // So we need to replace trailing spaces with non-breaking spaces.
  607. const text = cue.payload.replace(/\s+$/g, (match) => {
  608. const nonBreakingSpace = '\xa0';
  609. return nonBreakingSpace.repeat(match.length);
  610. });
  611. style.webkitTextStrokeColor = cue.textStrokeColor;
  612. style.webkitTextStrokeWidth = cue.textStrokeWidth;
  613. style.color = cue.color;
  614. style.direction = cue.direction;
  615. style.opacity = cue.opacity;
  616. style.paddingLeft = shaka.text.UITextDisplayer.convertLengthValue_(
  617. cue.linePadding, cue, this.videoContainer_);
  618. style.paddingRight =
  619. shaka.text.UITextDisplayer.convertLengthValue_(
  620. cue.linePadding, cue, this.videoContainer_);
  621. style.textCombineUpright = cue.textCombineUpright;
  622. style.textShadow = cue.textShadow;
  623. if (cue.backgroundImage) {
  624. style.backgroundImage = 'url(\'' + cue.backgroundImage + '\')';
  625. style.backgroundRepeat = 'no-repeat';
  626. style.backgroundSize = 'contain';
  627. style.backgroundPosition = 'center';
  628. if (cue.backgroundColor) {
  629. style.backgroundColor = cue.backgroundColor;
  630. }
  631. // Quoting https://www.w3.org/TR/ttml-imsc1.2/:
  632. // "The width and height (in pixels) of the image resource referenced by
  633. // smpte:backgroundImage SHALL be equal to the width and height expressed
  634. // by the tts:extent attribute of the region in which the div element is
  635. // presented".
  636. style.width = '100%';
  637. style.height = '100%';
  638. } else {
  639. // If we have both text and nested cues, then style everything; otherwise
  640. // place the text in its own <span> so the background doesn't fill the
  641. // whole region.
  642. let elem;
  643. if (cue.nestedCues.length) {
  644. elem = cueElement;
  645. } else {
  646. elem = shaka.util.Dom.createHTMLElement('span');
  647. cueElement.appendChild(elem);
  648. }
  649. if (cue.border) {
  650. elem.style.border = cue.border;
  651. }
  652. if (!hasWrapper) {
  653. const bgColor = inherit((c) => c.backgroundColor);
  654. if (bgColor) {
  655. elem.style.backgroundColor = bgColor;
  656. } else if (text) {
  657. // If there is no background, default to a semi-transparent black.
  658. // Only do this for the text itself.
  659. elem.style.backgroundColor = 'rgba(0, 0, 0, 0.8)';
  660. }
  661. }
  662. if (text) {
  663. elem.textContent = text;
  664. }
  665. }
  666. // The displayAlign attribute specifies the vertical alignment of the
  667. // captions inside the text container. Before means at the top of the
  668. // text container, and after means at the bottom.
  669. if (isNested && !parents[parents.length - 1].isContainer) {
  670. style.display = 'inline';
  671. } else {
  672. style.display = 'flex';
  673. style.flexDirection = 'column';
  674. style.alignItems = 'center';
  675. if (cue.textAlign == Cue.textAlign.LEFT ||
  676. cue.textAlign == Cue.textAlign.START) {
  677. style.width = '100%';
  678. style.alignItems = 'start';
  679. } else if (cue.textAlign == Cue.textAlign.RIGHT ||
  680. cue.textAlign == Cue.textAlign.END) {
  681. style.width = '100%';
  682. style.alignItems = 'end';
  683. }
  684. if (cue.displayAlign == Cue.displayAlign.BEFORE) {
  685. style.justifyContent = 'flex-start';
  686. } else if (cue.displayAlign == Cue.displayAlign.CENTER) {
  687. style.justifyContent = 'center';
  688. } else {
  689. style.justifyContent = 'flex-end';
  690. }
  691. }
  692. if (!isLeaf) {
  693. style.margin = '0';
  694. }
  695. style.fontFamily = cue.fontFamily;
  696. style.fontWeight = cue.fontWeight.toString();
  697. style.fontStyle = cue.fontStyle;
  698. style.letterSpacing = cue.letterSpacing;
  699. style.fontSize = shaka.text.UITextDisplayer.convertLengthValue_(
  700. cue.fontSize, cue, this.videoContainer_);
  701. // The line attribute defines the positioning of the text container inside
  702. // the video container.
  703. // - The line offsets the text container from the top, the right or left of
  704. // the video viewport as defined by the writing direction.
  705. // - The value of the line is either as a number of lines, or a percentage
  706. // of the video viewport height or width.
  707. // The lineAlign is an alignment for the text container's line.
  708. // - The Start alignment means the text container’s top side (for horizontal
  709. // cues), left side (for vertical growing right), or right side (for
  710. // vertical growing left) is aligned at the line.
  711. // - The Center alignment means the text container is centered at the line
  712. // (to be implemented).
  713. // - The End Alignment means The text container’s bottom side (for
  714. // horizontal cues), right side (for vertical growing right), or left side
  715. // (for vertical growing left) is aligned at the line.
  716. // TODO: Implement line alignment with line number.
  717. // TODO: Implement lineAlignment of 'CENTER'.
  718. let line = cue.line;
  719. if (line != null) {
  720. let lineInterpretation = cue.lineInterpretation;
  721. // HACK: the current implementation of UITextDisplayer only handled
  722. // PERCENTAGE, so we need convert LINE_NUMBER to PERCENTAGE
  723. if (lineInterpretation == Cue.lineInterpretation.LINE_NUMBER) {
  724. lineInterpretation = Cue.lineInterpretation.PERCENTAGE;
  725. let maxLines = 16;
  726. // The maximum number of lines is different if it is a vertical video.
  727. if (this.aspectRatio_ && this.aspectRatio_ < 1) {
  728. maxLines = 32;
  729. }
  730. if (line < 0) {
  731. line = 100 + line / maxLines * 100;
  732. } else {
  733. line = line / maxLines * 100;
  734. }
  735. }
  736. if (lineInterpretation == Cue.lineInterpretation.PERCENTAGE) {
  737. style.position = 'absolute';
  738. if (cue.writingMode == Cue.writingMode.HORIZONTAL_TOP_TO_BOTTOM) {
  739. style.width = '100%';
  740. if (cue.lineAlign == Cue.lineAlign.START) {
  741. style.top = line + '%';
  742. } else if (cue.lineAlign == Cue.lineAlign.END) {
  743. style.bottom = (100 - line) + '%';
  744. }
  745. } else if (cue.writingMode == Cue.writingMode.VERTICAL_LEFT_TO_RIGHT) {
  746. style.height = '100%';
  747. if (cue.lineAlign == Cue.lineAlign.START) {
  748. style.left = line + '%';
  749. } else if (cue.lineAlign == Cue.lineAlign.END) {
  750. style.right = (100 - line) + '%';
  751. }
  752. } else {
  753. style.height = '100%';
  754. if (cue.lineAlign == Cue.lineAlign.START) {
  755. style.right = line + '%';
  756. } else if (cue.lineAlign == Cue.lineAlign.END) {
  757. style.left = (100 - line) + '%';
  758. }
  759. }
  760. }
  761. }
  762. style.lineHeight = cue.lineHeight;
  763. // The positionAlign attribute is an alignment for the text container in
  764. // the dimension of the writing direction.
  765. const computedPositionAlign = this.computeCuePositionAlignment_(cue);
  766. if (computedPositionAlign == Cue.positionAlign.LEFT) {
  767. style.cssFloat = 'left';
  768. if (cue.position !== null) {
  769. style.position = 'absolute';
  770. if (cue.writingMode == Cue.writingMode.HORIZONTAL_TOP_TO_BOTTOM) {
  771. style.left = cue.position + '%';
  772. style.width = 'auto';
  773. } else {
  774. style.top = cue.position + '%';
  775. }
  776. }
  777. } else if (computedPositionAlign == Cue.positionAlign.RIGHT) {
  778. style.cssFloat = 'right';
  779. if (cue.position !== null) {
  780. style.position = 'absolute';
  781. if (cue.writingMode == Cue.writingMode.HORIZONTAL_TOP_TO_BOTTOM) {
  782. style.right = (100 - cue.position) + '%';
  783. style.width = 'auto';
  784. } else {
  785. style.bottom = cue.position + '%';
  786. }
  787. }
  788. } else {
  789. if (cue.position !== null && cue.position != 50) {
  790. style.position = 'absolute';
  791. if (cue.writingMode == Cue.writingMode.HORIZONTAL_TOP_TO_BOTTOM) {
  792. style.left = cue.position + '%';
  793. style.width = 'auto';
  794. } else {
  795. style.top = cue.position + '%';
  796. }
  797. }
  798. }
  799. style.textAlign = cue.textAlign;
  800. style.textDecoration = cue.textDecoration.join(' ');
  801. style.writingMode = cue.writingMode;
  802. // Old versions of Chromium, which may be found in certain versions of Tizen
  803. // and WebOS, may require the prefixed version: webkitWritingMode.
  804. // https://caniuse.com/css-writing-mode
  805. // However, testing shows that Tizen 3, at least, has a 'writingMode'
  806. // property, but the setter for it does nothing. Therefore we need to
  807. // detect that and fall back to the prefixed version in this case, too.
  808. if (!('writingMode' in document.documentElement.style) ||
  809. style.writingMode != cue.writingMode) {
  810. // Note that here we do not bother to check for webkitWritingMode support
  811. // explicitly. We try the unprefixed version, then fall back to the
  812. // prefixed version unconditionally.
  813. style.webkitWritingMode = cue.writingMode;
  814. }
  815. // The size is a number giving the size of the text container, to be
  816. // interpreted as a percentage of the video, as defined by the writing
  817. // direction.
  818. if (cue.size) {
  819. if (cue.writingMode == Cue.writingMode.HORIZONTAL_TOP_TO_BOTTOM) {
  820. style.width = cue.size + '%';
  821. } else {
  822. style.height = cue.size + '%';
  823. }
  824. }
  825. }
  826. /**
  827. * Returns info about provided lengthValue
  828. * @example 100px => { value: 100, unit: 'px' }
  829. * @param {?string} lengthValue
  830. *
  831. * @return {?{ value: number, unit: string }}
  832. * @private
  833. */
  834. static getLengthValueInfo_(lengthValue) {
  835. const matches = new RegExp(/(\d*\.?\d+)([a-z]+|%+)/).exec(lengthValue);
  836. if (!matches) {
  837. return null;
  838. }
  839. return {
  840. value: Number(matches[1]),
  841. unit: matches[2],
  842. };
  843. }
  844. /**
  845. * Converts length value to an absolute value in pixels.
  846. * If lengthValue is already an absolute value it will not
  847. * be modified. Relative lengthValue will be converted to an
  848. * absolute value in pixels based on Computed Cell Size
  849. *
  850. * @param {string} lengthValue
  851. * @param {!shaka.text.Cue} cue
  852. * @param {HTMLElement} videoContainer
  853. * @return {string}
  854. * @private
  855. */
  856. static convertLengthValue_(lengthValue, cue, videoContainer) {
  857. const lengthValueInfo =
  858. shaka.text.UITextDisplayer.getLengthValueInfo_(lengthValue);
  859. if (!lengthValueInfo) {
  860. return lengthValue;
  861. }
  862. const {unit, value} = lengthValueInfo;
  863. switch (unit) {
  864. case '%':
  865. return shaka.text.UITextDisplayer.getAbsoluteLengthInPixels_(
  866. value / 100, cue, videoContainer);
  867. case 'c':
  868. return shaka.text.UITextDisplayer.getAbsoluteLengthInPixels_(
  869. value, cue, videoContainer);
  870. default:
  871. return lengthValue;
  872. }
  873. }
  874. /**
  875. * Returns computed absolute length value in pixels based on cell
  876. * and a video container size
  877. * @param {number} value
  878. * @param {!shaka.text.Cue} cue
  879. * @param {HTMLElement} videoContainer
  880. * @return {string}
  881. *
  882. * @private
  883. */
  884. static getAbsoluteLengthInPixels_(value, cue, videoContainer) {
  885. const containerHeight = videoContainer.clientHeight;
  886. return (containerHeight * value / cue.cellResolution.rows) + 'px';
  887. }
  888. /**
  889. * Inherits a property from the parent Cue elements. If the value is falsy,
  890. * it is assumed to be inherited from the parent. This returns null if the
  891. * value isn't found.
  892. *
  893. * @param {!Array<!shaka.text.Cue>} parents
  894. * @param {function(!shaka.text.Cue):?T} cb
  895. * @return {?T}
  896. * @template T
  897. * @private
  898. */
  899. static inheritProperty_(parents, cb) {
  900. for (let i = parents.length - 1; i >= 0; i--) {
  901. const val = cb(parents[i]);
  902. if (val || val === 0) {
  903. return val;
  904. }
  905. }
  906. return null;
  907. }
  908. };