Source: lib/media/playhead.js

  1. /*! @license
  2. * Shaka Player
  3. * Copyright 2016 Google LLC
  4. * SPDX-License-Identifier: Apache-2.0
  5. */
  6. goog.provide('shaka.media.MediaSourcePlayhead');
  7. goog.provide('shaka.media.Playhead');
  8. goog.provide('shaka.media.SrcEqualsPlayhead');
  9. goog.require('goog.asserts');
  10. goog.require('shaka.log');
  11. goog.require('shaka.media.GapJumpingController');
  12. goog.require('shaka.media.TimeRangesUtils');
  13. goog.require('shaka.media.VideoWrapper');
  14. goog.require('shaka.util.EventManager');
  15. goog.require('shaka.util.IReleasable');
  16. goog.require('shaka.util.MediaReadyState');
  17. goog.require('shaka.util.Platform');
  18. goog.require('shaka.util.Timer');
  19. goog.requireType('shaka.media.PresentationTimeline');
  20. /**
  21. * Creates a Playhead, which manages the video's current time.
  22. *
  23. * The Playhead provides mechanisms for setting the presentation's start time,
  24. * restricting seeking to valid time ranges, and stopping playback for startup
  25. * and re-buffering.
  26. *
  27. * @extends {shaka.util.IReleasable}
  28. * @interface
  29. */
  30. shaka.media.Playhead = class {
  31. /**
  32. * Called when the Player is ready to begin playback. Anything that depends
  33. * on setStartTime() should be done here, not in the constructor.
  34. *
  35. * @see https://github.com/shaka-project/shaka-player/issues/4244
  36. */
  37. ready() {}
  38. /**
  39. * Set the start time. If the content has already started playback, this will
  40. * be ignored.
  41. *
  42. * @param {number} startTime
  43. */
  44. setStartTime(startTime) {}
  45. /**
  46. * Get the number of playback stalls detected by the StallDetector.
  47. *
  48. * @return {number}
  49. */
  50. getStallsDetected() {}
  51. /**
  52. * Get the number of playback gaps jumped by the GapJumpingController.
  53. *
  54. * @return {number}
  55. */
  56. getGapsJumped() {}
  57. /**
  58. * Get the current playhead position. The position will be restricted to valid
  59. * time ranges.
  60. *
  61. * @return {number}
  62. */
  63. getTime() {}
  64. /**
  65. * Notify the playhead that the buffered ranges have changed.
  66. */
  67. notifyOfBufferingChange() {}
  68. };
  69. /**
  70. * A playhead implementation that only relies on the media element.
  71. *
  72. * @implements {shaka.media.Playhead}
  73. * @final
  74. */
  75. shaka.media.SrcEqualsPlayhead = class {
  76. /**
  77. * @param {!HTMLMediaElement} mediaElement
  78. */
  79. constructor(mediaElement) {
  80. /** @private {HTMLMediaElement} */
  81. this.mediaElement_ = mediaElement;
  82. /** @private {boolean} */
  83. this.started_ = false;
  84. /** @private {?number} */
  85. this.startTime_ = null;
  86. /** @private {shaka.util.EventManager} */
  87. this.eventManager_ = new shaka.util.EventManager();
  88. }
  89. /** @override */
  90. ready() {
  91. goog.asserts.assert(
  92. this.mediaElement_ != null,
  93. 'Playhead should not be released before calling ready()',
  94. );
  95. // We listen for the loaded-data-event so that we know when we can
  96. // interact with |currentTime|.
  97. const onLoaded = () => {
  98. if (this.startTime_ == null ||
  99. (this.startTime_ == 0 && this.mediaElement_.duration != Infinity)) {
  100. this.started_ = true;
  101. } else {
  102. const currentTime = this.mediaElement_.currentTime;
  103. let newTime = this.startTime_;
  104. // Using the currentTime allows using a negative number in Live HLS
  105. if (this.startTime_ < 0) {
  106. newTime = Math.max(0, currentTime + this.startTime_);
  107. }
  108. if (currentTime != newTime) {
  109. // Startup is complete only when the video element acknowledges the
  110. // seek.
  111. this.eventManager_.listenOnce(this.mediaElement_, 'seeking', () => {
  112. this.started_ = true;
  113. });
  114. this.mediaElement_.currentTime = newTime;
  115. } else {
  116. this.started_ = true;
  117. }
  118. }
  119. };
  120. shaka.util.MediaReadyState.waitForReadyState(this.mediaElement_,
  121. HTMLMediaElement.HAVE_CURRENT_DATA,
  122. this.eventManager_, () => {
  123. onLoaded();
  124. });
  125. }
  126. /** @override */
  127. release() {
  128. if (this.eventManager_) {
  129. this.eventManager_.release();
  130. this.eventManager_ = null;
  131. }
  132. this.mediaElement_ = null;
  133. }
  134. /** @override */
  135. setStartTime(startTime) {
  136. // If we have already started playback, ignore updates to the start time.
  137. // This is just to make things consistent.
  138. this.startTime_ = this.started_ ? this.startTime_ : startTime;
  139. }
  140. /** @override */
  141. getTime() {
  142. // If we have not started playback yet, return the start time. However once
  143. // we start playback we assume that we can always return the current time.
  144. const time = this.started_ ?
  145. this.mediaElement_.currentTime :
  146. this.startTime_;
  147. // In the case that we have not started playback, but the start time was
  148. // never set, we don't know what the start time should be. To ensure we
  149. // always return a number, we will default back to 0.
  150. return time || 0;
  151. }
  152. /** @override */
  153. getStallsDetected() {
  154. return 0;
  155. }
  156. /** @override */
  157. getGapsJumped() {
  158. return 0;
  159. }
  160. /** @override */
  161. notifyOfBufferingChange() {}
  162. };
  163. /**
  164. * A playhead implementation that relies on the media element and a manifest.
  165. * When provided with a manifest, we can provide more accurate control than
  166. * the SrcEqualsPlayhead.
  167. *
  168. * TODO: Clean up and simplify Playhead. There are too many layers of, methods
  169. * for, and conditions on timestamp adjustment.
  170. *
  171. * @implements {shaka.media.Playhead}
  172. * @final
  173. */
  174. shaka.media.MediaSourcePlayhead = class {
  175. /**
  176. * @param {!HTMLMediaElement} mediaElement
  177. * @param {shaka.extern.Manifest} manifest
  178. * @param {shaka.extern.StreamingConfiguration} config
  179. * @param {?number} startTime
  180. * The playhead's initial position in seconds. If null, defaults to the
  181. * start of the presentation for VOD and the live-edge for live.
  182. * @param {function()} onSeek
  183. * Called when the user agent seeks to a time within the presentation
  184. * timeline.
  185. * @param {function(!Event)} onEvent
  186. * Called when an event is raised to be sent to the application.
  187. */
  188. constructor(mediaElement, manifest, config, startTime, onSeek, onEvent) {
  189. /**
  190. * The seek range must be at least this number of seconds long. If it is
  191. * smaller than this, change it to be this big so we don't repeatedly seek
  192. * to keep within a zero-width window.
  193. *
  194. * This is 3s long, to account for the weaker hardware on platforms like
  195. * Chromecast.
  196. *
  197. * @private {number}
  198. */
  199. this.minSeekRange_ = 3.0;
  200. /** @private {HTMLMediaElement} */
  201. this.mediaElement_ = mediaElement;
  202. /** @private {shaka.media.PresentationTimeline} */
  203. this.timeline_ = manifest.presentationTimeline;
  204. /** @private {?shaka.extern.StreamingConfiguration} */
  205. this.config_ = config;
  206. /** @private {function()} */
  207. this.onSeek_ = onSeek;
  208. /** @private {?number} */
  209. this.lastCorrectiveSeek_ = null;
  210. /** @private {shaka.media.GapJumpingController} */
  211. this.gapController_ = new shaka.media.GapJumpingController(
  212. mediaElement,
  213. manifest.presentationTimeline,
  214. config,
  215. onEvent);
  216. /** @private {shaka.media.VideoWrapper} */
  217. this.videoWrapper_ = new shaka.media.VideoWrapper(
  218. mediaElement,
  219. () => this.onSeeking_(),
  220. (realStartTime) => this.onStarted_(realStartTime),
  221. () => this.getStartTime_(startTime));
  222. /** @type {shaka.util.Timer} */
  223. this.checkWindowTimer_ = new shaka.util.Timer(() => {
  224. this.onPollWindow_();
  225. });
  226. }
  227. /** @override */
  228. ready() {
  229. this.checkWindowTimer_.tickEvery(/* seconds= */ 0.25);
  230. }
  231. /** @override */
  232. release() {
  233. if (this.videoWrapper_) {
  234. this.videoWrapper_.release();
  235. this.videoWrapper_ = null;
  236. }
  237. if (this.gapController_) {
  238. this.gapController_.release();
  239. this.gapController_= null;
  240. }
  241. if (this.checkWindowTimer_) {
  242. this.checkWindowTimer_.stop();
  243. this.checkWindowTimer_ = null;
  244. }
  245. this.config_ = null;
  246. this.timeline_ = null;
  247. this.videoWrapper_ = null;
  248. this.mediaElement_ = null;
  249. this.onSeek_ = () => {};
  250. }
  251. /** @override */
  252. setStartTime(startTime) {
  253. this.videoWrapper_.setTime(startTime);
  254. }
  255. /** @override */
  256. getTime() {
  257. const time = this.videoWrapper_.getTime();
  258. // Although we restrict the video's currentTime elsewhere, clamp it here to
  259. // ensure timing issues don't cause us to return a time outside the segment
  260. // availability window. E.g., the user agent seeks and calls this function
  261. // before we receive the 'seeking' event.
  262. //
  263. // We don't buffer when the livestream video is paused and the playhead time
  264. // is out of the seek range; thus, we do not clamp the current time when the
  265. // video is paused.
  266. // https://github.com/shaka-project/shaka-player/issues/1121
  267. if (this.mediaElement_.readyState > 0 && !this.mediaElement_.paused) {
  268. return this.clampTime_(time);
  269. }
  270. return time;
  271. }
  272. /** @override */
  273. getStallsDetected() {
  274. return this.gapController_.getStallsDetected();
  275. }
  276. /** @override */
  277. getGapsJumped() {
  278. return this.gapController_.getGapsJumped();
  279. }
  280. /**
  281. * Gets the playhead's initial position in seconds.
  282. *
  283. * @param {?number} startTime
  284. * @return {number}
  285. * @private
  286. */
  287. getStartTime_(startTime) {
  288. if (startTime == null) {
  289. if (this.timeline_.getDuration() < Infinity) {
  290. // If the presentation is VOD, or if the presentation is live but has
  291. // finished broadcasting, then start from the beginning.
  292. startTime = this.timeline_.getSeekRangeStart();
  293. } else {
  294. // Otherwise, start near the live-edge.
  295. startTime = this.timeline_.getSeekRangeEnd();
  296. }
  297. } else if (startTime < 0) {
  298. // For live streams, if the startTime is negative, start from a certain
  299. // offset time from the live edge. If the offset from the live edge is
  300. // not available, start from the current available segment start point
  301. // instead, handled by clampTime_().
  302. startTime = this.timeline_.getSeekRangeEnd() + startTime;
  303. }
  304. return this.clampSeekToDuration_(this.clampTime_(startTime));
  305. }
  306. /** @override */
  307. notifyOfBufferingChange() {
  308. this.gapController_.onSegmentAppended();
  309. }
  310. /**
  311. * Called on a recurring timer to keep the playhead from falling outside the
  312. * availability window.
  313. *
  314. * @private
  315. */
  316. onPollWindow_() {
  317. // Don't catch up to the seek range when we are paused or empty.
  318. // The definition of "seeking" says that we are seeking until the buffered
  319. // data intersects with the playhead. If we fall outside of the seek range,
  320. // it doesn't matter if we are in a "seeking" state. We can and should go
  321. // ahead and catch up while seeking.
  322. if (this.mediaElement_.readyState == 0 || this.mediaElement_.paused) {
  323. return;
  324. }
  325. const currentTime = this.videoWrapper_.getTime();
  326. let seekStart = this.timeline_.getSeekRangeStart();
  327. const seekEnd = this.timeline_.getSeekRangeEnd();
  328. if (seekEnd - seekStart < this.minSeekRange_) {
  329. seekStart = seekEnd - this.minSeekRange_;
  330. }
  331. if (currentTime < seekStart) {
  332. // The seek range has moved past the playhead. Move ahead to catch up.
  333. const targetTime = this.reposition_(currentTime);
  334. shaka.log.info('Jumping forward ' + (targetTime - currentTime) +
  335. ' seconds to catch up with the seek range.');
  336. this.mediaElement_.currentTime = targetTime;
  337. }
  338. }
  339. /**
  340. * Called when the video element has started up and is listening for new seeks
  341. *
  342. * @param {number} startTime
  343. * @private
  344. */
  345. onStarted_(startTime) {
  346. this.gapController_.onStarted(startTime);
  347. }
  348. /**
  349. * Handles when a seek happens on the video.
  350. *
  351. * @private
  352. */
  353. onSeeking_() {
  354. this.gapController_.onSeeking();
  355. const currentTime = this.videoWrapper_.getTime();
  356. const targetTime = this.reposition_(currentTime);
  357. const gapLimit = shaka.media.GapJumpingController.BROWSER_GAP_TOLERANCE;
  358. if (Math.abs(targetTime - currentTime) > gapLimit) {
  359. let canCorrectiveSeek = false;
  360. if (shaka.util.Platform.isSeekingSlow()) {
  361. // You can only seek like this every so often. This is to prevent an
  362. // infinite loop on systems where changing currentTime takes a
  363. // significant amount of time (e.g. Chromecast).
  364. const time = Date.now() / 1000;
  365. const seekDelay = shaka.util.Platform.isFuchsiaCastDevice() ? 3 : 1;
  366. if (!this.lastCorrectiveSeek_ ||
  367. this.lastCorrectiveSeek_ < time - seekDelay) {
  368. this.lastCorrectiveSeek_ = time;
  369. canCorrectiveSeek = true;
  370. }
  371. } else {
  372. canCorrectiveSeek = true;
  373. }
  374. if (canCorrectiveSeek) {
  375. this.videoWrapper_.setTime(targetTime);
  376. return;
  377. }
  378. }
  379. shaka.log.v1('Seek to ' + currentTime);
  380. this.onSeek_();
  381. }
  382. /**
  383. * Clamp seek times and playback start times so that we never seek to the
  384. * presentation duration. Seeking to or starting at duration does not work
  385. * consistently across browsers.
  386. *
  387. * @see https://github.com/shaka-project/shaka-player/issues/979
  388. * @param {number} time
  389. * @return {number} The adjusted seek time.
  390. * @private
  391. */
  392. clampSeekToDuration_(time) {
  393. const duration = this.timeline_.getDuration();
  394. if (time >= duration) {
  395. goog.asserts.assert(this.config_.durationBackoff >= 0,
  396. 'Duration backoff must be non-negative!');
  397. return duration - this.config_.durationBackoff;
  398. }
  399. return time;
  400. }
  401. /**
  402. * Computes a new playhead position that's within the presentation timeline.
  403. *
  404. * @param {number} currentTime
  405. * @return {number} The time to reposition the playhead to.
  406. * @private
  407. */
  408. reposition_(currentTime) {
  409. goog.asserts.assert(
  410. this.config_,
  411. 'Cannot reposition playhead when it has been destroyed');
  412. /** @type {function(number)} */
  413. const isBuffered = (playheadTime) => shaka.media.TimeRangesUtils.isBuffered(
  414. this.mediaElement_.buffered, playheadTime);
  415. const rebufferingGoal = this.config_.rebufferingGoal;
  416. const safeSeekOffset = this.config_.safeSeekOffset;
  417. let start = this.timeline_.getSeekRangeStart();
  418. const end = this.timeline_.getSeekRangeEnd();
  419. const duration = this.timeline_.getDuration();
  420. if (end - start < this.minSeekRange_) {
  421. start = end - this.minSeekRange_;
  422. }
  423. // With live content, the beginning of the availability window is moving
  424. // forward. This means we cannot seek to it since we will "fall" outside
  425. // the window while we buffer. So we define a "safe" region that is far
  426. // enough away. For VOD, |safe == start|.
  427. const safe = this.timeline_.getSafeSeekRangeStart(rebufferingGoal);
  428. // These are the times to seek to rather than the exact destinations. When
  429. // we seek, we will get another event (after a slight delay) and these steps
  430. // will run again. So if we seeked directly to |start|, |start| would move
  431. // on the next call and we would loop forever.
  432. const seekStart = this.timeline_.getSafeSeekRangeStart(safeSeekOffset);
  433. const seekSafe = this.timeline_.getSafeSeekRangeStart(
  434. rebufferingGoal + safeSeekOffset);
  435. if (currentTime >= duration) {
  436. shaka.log.v1('Playhead past duration.');
  437. return this.clampSeekToDuration_(currentTime);
  438. }
  439. if (currentTime > end) {
  440. shaka.log.v1('Playhead past end.');
  441. // We remove the safeSeekEndOffset of the seek end to avoid the player
  442. // to be block at the edge in a live stream
  443. return end - this.config_.safeSeekEndOffset;
  444. }
  445. if (currentTime < start) {
  446. if (isBuffered(seekStart)) {
  447. shaka.log.v1('Playhead before start & start is buffered');
  448. return seekStart;
  449. } else {
  450. shaka.log.v1('Playhead before start & start is unbuffered');
  451. return seekSafe;
  452. }
  453. }
  454. if (currentTime >= safe || isBuffered(currentTime)) {
  455. shaka.log.v1('Playhead in safe region or in buffered region.');
  456. return currentTime;
  457. } else {
  458. shaka.log.v1('Playhead outside safe region & in unbuffered region.');
  459. return seekSafe;
  460. }
  461. }
  462. /**
  463. * Clamps the given time to the seek range.
  464. *
  465. * @param {number} time The time in seconds.
  466. * @return {number} The clamped time in seconds.
  467. * @private
  468. */
  469. clampTime_(time) {
  470. const start = this.timeline_.getSeekRangeStart();
  471. if (time < start) {
  472. return start;
  473. }
  474. const end = this.timeline_.getSeekRangeEnd();
  475. if (time > end) {
  476. return end;
  477. }
  478. return time;
  479. }
  480. };