Source: lib/text/simple_text_displayer.js

  1. /*! @license
  2. * Shaka Player
  3. * Copyright 2016 Google LLC
  4. * SPDX-License-Identifier: Apache-2.0
  5. */
  6. /**
  7. * @fileoverview
  8. */
  9. goog.provide('shaka.text.SimpleTextDisplayer');
  10. goog.require('goog.asserts');
  11. goog.require('shaka.log');
  12. goog.require('shaka.text.Cue');
  13. goog.require('shaka.text.Utils');
  14. /**
  15. * A text displayer plugin using the browser's native VTTCue interface.
  16. *
  17. * @implements {shaka.extern.TextDisplayer}
  18. * @export
  19. */
  20. shaka.text.SimpleTextDisplayer = class {
  21. /**
  22. * @param {HTMLMediaElement} video
  23. * @param {string} label
  24. */
  25. constructor(video, label) {
  26. /** @private {TextTrack} */
  27. this.textTrack_ = null;
  28. // TODO: Test that in all cases, the built-in CC controls in the video
  29. // element are toggling our TextTrack.
  30. // If the video element has TextTracks, disable them. If we see one that
  31. // was created by a previous instance of Shaka Player, reuse it.
  32. for (const track of Array.from(video.textTracks)) {
  33. if (track.kind === 'metadata' || track.kind === 'chapters') {
  34. continue;
  35. }
  36. // NOTE: There is no API available to remove a TextTrack from a video
  37. // element.
  38. track.mode = 'disabled';
  39. if (track.label == label) {
  40. this.textTrack_ = track;
  41. }
  42. }
  43. if (!this.textTrack_) {
  44. // As far as I can tell, there is no observable difference between setting
  45. // kind to 'subtitles' or 'captions' when creating the TextTrack object.
  46. // The individual text tracks from the manifest will still have their own
  47. // kinds which can be displayed in the app's UI.
  48. this.textTrack_ = video.addTextTrack('subtitles', label);
  49. }
  50. this.textTrack_.mode = 'hidden';
  51. }
  52. /**
  53. * @override
  54. * @export
  55. */
  56. configure(config) {
  57. // Unused.
  58. }
  59. /**
  60. * @override
  61. * @export
  62. */
  63. remove(start, end) {
  64. // Check that the displayer hasn't been destroyed.
  65. if (!this.textTrack_) {
  66. return false;
  67. }
  68. const removeInRange = (cue) => {
  69. const inside = cue.startTime < end && cue.endTime > start;
  70. return inside;
  71. };
  72. shaka.text.SimpleTextDisplayer.removeWhere_(this.textTrack_, removeInRange);
  73. return true;
  74. }
  75. /**
  76. * @override
  77. * @export
  78. */
  79. append(cues) {
  80. const flattenedCues = shaka.text.Utils.getCuesToFlatten(cues);
  81. // Convert cues.
  82. const textTrackCues = [];
  83. const cuesInTextTrack = this.textTrack_.cues ?
  84. Array.from(this.textTrack_.cues) : [];
  85. for (const inCue of flattenedCues) {
  86. // When a VTT cue spans a segment boundary, the cue will be duplicated
  87. // into two segments.
  88. // To avoid displaying duplicate cues, if the current textTrack cues
  89. // list already contains the cue, skip it.
  90. const containsCue = cuesInTextTrack.some((cueInTextTrack) => {
  91. if (cueInTextTrack.startTime == inCue.startTime &&
  92. cueInTextTrack.endTime == inCue.endTime &&
  93. cueInTextTrack.text == inCue.payload) {
  94. return true;
  95. }
  96. return false;
  97. });
  98. if (!containsCue) {
  99. const cue =
  100. shaka.text.SimpleTextDisplayer.convertToTextTrackCue_(inCue);
  101. if (cue) {
  102. textTrackCues.push(cue);
  103. }
  104. }
  105. }
  106. // Sort the cues based on start/end times. Make a copy of the array so
  107. // we can get the index in the original ordering. Out of order cues are
  108. // rejected by Edge. See https://bit.ly/2K9VX3s
  109. const sortedCues = textTrackCues.slice().sort((a, b) => {
  110. if (a.startTime != b.startTime) {
  111. return a.startTime - b.startTime;
  112. } else if (a.endTime != b.endTime) {
  113. return a.endTime - b.startTime;
  114. } else {
  115. // The browser will display cues with identical time ranges from the
  116. // bottom up. Reversing the order of equal cues means the first one
  117. // parsed will be at the top, as you would expect.
  118. // See https://github.com/shaka-project/shaka-player/issues/848 for
  119. // more info.
  120. // However, this ordering behavior is part of VTTCue's "line" field.
  121. // Some platforms don't have a real VTTCue and use a polyfill instead.
  122. // When VTTCue is polyfilled or does not support "line", we should _not_
  123. // reverse the order. This occurs on legacy Edge.
  124. // eslint-disable-next-line no-restricted-syntax
  125. if ('line' in VTTCue.prototype) {
  126. // Native VTTCue
  127. return textTrackCues.indexOf(b) - textTrackCues.indexOf(a);
  128. } else {
  129. // Polyfilled VTTCue
  130. return textTrackCues.indexOf(a) - textTrackCues.indexOf(b);
  131. }
  132. }
  133. });
  134. for (const cue of sortedCues) {
  135. this.textTrack_.addCue(cue);
  136. }
  137. }
  138. /**
  139. * @override
  140. * @export
  141. */
  142. destroy() {
  143. if (this.textTrack_) {
  144. const removeIt = (cue) => true;
  145. shaka.text.SimpleTextDisplayer.removeWhere_(this.textTrack_, removeIt);
  146. // NOTE: There is no API available to remove a TextTrack from a video
  147. // element.
  148. this.textTrack_.mode = 'disabled';
  149. }
  150. this.textTrack_ = null;
  151. return Promise.resolve();
  152. }
  153. /**
  154. * @override
  155. * @export
  156. */
  157. isTextVisible() {
  158. return this.textTrack_.mode == 'showing';
  159. }
  160. /**
  161. * @override
  162. * @export
  163. */
  164. setTextVisibility(on) {
  165. this.textTrack_.mode = on ? 'showing' : 'hidden';
  166. }
  167. /**
  168. * @param {!shaka.text.Cue} shakaCue
  169. * @return {TextTrackCue}
  170. * @private
  171. */
  172. static convertToTextTrackCue_(shakaCue) {
  173. if (shakaCue.startTime >= shakaCue.endTime) {
  174. // Edge will throw in this case.
  175. // See issue #501
  176. shaka.log.warning('Invalid cue times: ' + shakaCue.startTime +
  177. ' - ' + shakaCue.endTime);
  178. return null;
  179. }
  180. const Cue = shaka.text.Cue;
  181. /** @type {VTTCue} */
  182. const vttCue = new VTTCue(
  183. shakaCue.startTime,
  184. shakaCue.endTime,
  185. shakaCue.payload);
  186. // NOTE: positionAlign and lineAlign settings are not supported by Chrome
  187. // at the moment, so setting them will have no effect.
  188. // The bug on chromium to implement them:
  189. // https://bugs.chromium.org/p/chromium/issues/detail?id=633690
  190. vttCue.lineAlign = shakaCue.lineAlign;
  191. vttCue.positionAlign = shakaCue.positionAlign;
  192. if (shakaCue.size) {
  193. vttCue.size = shakaCue.size;
  194. }
  195. try {
  196. // Safari 10 seems to throw on align='center'.
  197. vttCue.align = shakaCue.textAlign;
  198. } catch (exception) {}
  199. if (shakaCue.textAlign == 'center' && vttCue.align != 'center') {
  200. // We want vttCue.position = 'auto'. By default, |position| is set to
  201. // "auto". If we set it to "auto" safari will throw an exception, so we
  202. // must rely on the default value.
  203. vttCue.align = 'middle';
  204. }
  205. if (shakaCue.writingMode ==
  206. Cue.writingMode.VERTICAL_LEFT_TO_RIGHT) {
  207. vttCue.vertical = 'lr';
  208. } else if (shakaCue.writingMode ==
  209. Cue.writingMode.VERTICAL_RIGHT_TO_LEFT) {
  210. vttCue.vertical = 'rl';
  211. }
  212. // snapToLines flag is true by default
  213. if (shakaCue.lineInterpretation == Cue.lineInterpretation.PERCENTAGE) {
  214. vttCue.snapToLines = false;
  215. }
  216. if (shakaCue.line != null) {
  217. vttCue.line = shakaCue.line;
  218. }
  219. if (shakaCue.position != null) {
  220. vttCue.position = shakaCue.position;
  221. }
  222. return vttCue;
  223. }
  224. /**
  225. * Iterate over all the cues in a text track and remove all those for which
  226. * |predicate(cue)| returns true.
  227. *
  228. * @param {!TextTrack} track
  229. * @param {function(!TextTrackCue):boolean} predicate
  230. * @private
  231. */
  232. static removeWhere_(track, predicate) {
  233. // Since |track.cues| can be null if |track.mode| is "disabled", force it to
  234. // something other than "disabled".
  235. //
  236. // If the track is already showing, then we should keep it as showing. But
  237. // if it something else, we will use hidden so that we don't "flash" cues on
  238. // the screen.
  239. const oldState = track.mode;
  240. const tempState = oldState == 'showing' ? 'showing' : 'hidden';
  241. track.mode = tempState;
  242. goog.asserts.assert(
  243. track.cues,
  244. 'Cues should be accessible when mode is set to "' + tempState + '".');
  245. // Create a copy of the list to avoid errors while iterating.
  246. for (const cue of Array.from(track.cues)) {
  247. if (cue && predicate(cue)) {
  248. track.removeCue(cue);
  249. }
  250. }
  251. track.mode = oldState;
  252. }
  253. };