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