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