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