Source: lib/player.js

  1. /*! @license
  2. * Shaka Player
  3. * Copyright 2016 Google LLC
  4. * SPDX-License-Identifier: Apache-2.0
  5. */
  6. goog.provide('shaka.Player');
  7. goog.require('goog.asserts');
  8. goog.require('shaka.config.AutoShowText');
  9. goog.require('shaka.Deprecate');
  10. goog.require('shaka.log');
  11. goog.require('shaka.media.AdaptationSetCriteria');
  12. goog.require('shaka.media.BufferingObserver');
  13. goog.require('shaka.media.DrmEngine');
  14. goog.require('shaka.media.ExampleBasedCriteria');
  15. goog.require('shaka.media.ManifestFilterer');
  16. goog.require('shaka.media.ManifestParser');
  17. goog.require('shaka.media.MediaSourceEngine');
  18. goog.require('shaka.media.MediaSourcePlayhead');
  19. goog.require('shaka.media.MetaSegmentIndex');
  20. goog.require('shaka.media.PlayRateController');
  21. goog.require('shaka.media.Playhead');
  22. goog.require('shaka.media.PlayheadObserverManager');
  23. goog.require('shaka.media.PreferenceBasedCriteria');
  24. goog.require('shaka.media.PreloadManager');
  25. goog.require('shaka.media.QualityObserver');
  26. goog.require('shaka.media.RegionObserver');
  27. goog.require('shaka.media.RegionTimeline');
  28. goog.require('shaka.media.SegmentIndex');
  29. goog.require('shaka.media.SegmentPrefetch');
  30. goog.require('shaka.media.SegmentReference');
  31. goog.require('shaka.media.SrcEqualsPlayhead');
  32. goog.require('shaka.media.StreamingEngine');
  33. goog.require('shaka.media.TimeRangesUtils');
  34. goog.require('shaka.net.NetworkingEngine');
  35. goog.require('shaka.net.NetworkingUtils');
  36. goog.require('shaka.text.SimpleTextDisplayer');
  37. goog.require('shaka.text.StubTextDisplayer');
  38. goog.require('shaka.text.TextEngine');
  39. goog.require('shaka.text.UITextDisplayer');
  40. goog.require('shaka.text.WebVttGenerator');
  41. goog.require('shaka.util.BufferUtils');
  42. goog.require('shaka.util.CmcdManager');
  43. goog.require('shaka.util.CmsdManager');
  44. goog.require('shaka.util.ConfigUtils');
  45. goog.require('shaka.util.Dom');
  46. goog.require('shaka.util.Error');
  47. goog.require('shaka.util.EventManager');
  48. goog.require('shaka.util.FakeEvent');
  49. goog.require('shaka.util.FakeEventTarget');
  50. goog.require('shaka.util.IDestroyable');
  51. goog.require('shaka.util.LanguageUtils');
  52. goog.require('shaka.util.ManifestParserUtils');
  53. goog.require('shaka.util.MediaReadyState');
  54. goog.require('shaka.util.MimeUtils');
  55. goog.require('shaka.util.Mutex');
  56. goog.require('shaka.util.ObjectUtils');
  57. goog.require('shaka.util.Platform');
  58. goog.require('shaka.util.PlayerConfiguration');
  59. goog.require('shaka.util.PublicPromise');
  60. goog.require('shaka.util.Stats');
  61. goog.require('shaka.util.StreamUtils');
  62. goog.require('shaka.util.Timer');
  63. goog.require('shaka.lcevc.Dec');
  64. goog.requireType('shaka.media.PresentationTimeline');
  65. /**
  66. * @event shaka.Player.ErrorEvent
  67. * @description Fired when a playback error occurs.
  68. * @property {string} type
  69. * 'error'
  70. * @property {!shaka.util.Error} detail
  71. * An object which contains details on the error. The error's
  72. * <code>category</code> and <code>code</code> properties will identify the
  73. * specific error that occurred. In an uncompiled build, you can also use the
  74. * <code>message</code> and <code>stack</code> properties to debug.
  75. * @exportDoc
  76. */
  77. /**
  78. * @event shaka.Player.StateChangeEvent
  79. * @description Fired when the player changes load states.
  80. * @property {string} type
  81. * 'onstatechange'
  82. * @property {string} state
  83. * The name of the state that the player just entered.
  84. * @exportDoc
  85. */
  86. /**
  87. * @event shaka.Player.EmsgEvent
  88. * @description Fired when an emsg box is found in a segment.
  89. * If the application calls preventDefault() on this event, further parsing
  90. * will not happen, and no 'metadata' event will be raised for ID3 payloads.
  91. * @property {string} type
  92. * 'emsg'
  93. * @property {shaka.extern.EmsgInfo} detail
  94. * An object which contains the content of the emsg box.
  95. * @exportDoc
  96. */
  97. /**
  98. * @event shaka.Player.DownloadFailed
  99. * @description Fired when a download has failed, for any reason.
  100. * 'downloadfailed'
  101. * @property {!shaka.extern.Request} request
  102. * @property {?shaka.util.Error} error
  103. * @param {number} httpResponseCode
  104. * @param {boolean} aborted
  105. * @exportDoc
  106. */
  107. /**
  108. * @event shaka.Player.DownloadHeadersReceived
  109. * @description Fired when the networking engine has received the headers for
  110. * a download, but before the body has been downloaded.
  111. * If the HTTP plugin being used does not track this information, this event
  112. * will default to being fired when the body is received, instead.
  113. * @property {!Object.<string, string>} headers
  114. * @property {!shaka.extern.Request} request
  115. * @property {!shaka.net.NetworkingEngine.RequestType} type
  116. * 'downloadheadersreceived'
  117. * @exportDoc
  118. */
  119. /**
  120. * @event shaka.Player.DrmSessionUpdateEvent
  121. * @description Fired when the CDM has accepted the license response.
  122. * @property {string} type
  123. * 'drmsessionupdate'
  124. * @exportDoc
  125. */
  126. /**
  127. * @event shaka.Player.TimelineRegionAddedEvent
  128. * @description Fired when a media timeline region is added.
  129. * @property {string} type
  130. * 'timelineregionadded'
  131. * @property {shaka.extern.TimelineRegionInfo} detail
  132. * An object which contains a description of the region.
  133. * @exportDoc
  134. */
  135. /**
  136. * @event shaka.Player.TimelineRegionEnterEvent
  137. * @description Fired when the playhead enters a timeline region.
  138. * @property {string} type
  139. * 'timelineregionenter'
  140. * @property {shaka.extern.TimelineRegionInfo} detail
  141. * An object which contains a description of the region.
  142. * @exportDoc
  143. */
  144. /**
  145. * @event shaka.Player.TimelineRegionExitEvent
  146. * @description Fired when the playhead exits a timeline region.
  147. * @property {string} type
  148. * 'timelineregionexit'
  149. * @property {shaka.extern.TimelineRegionInfo} detail
  150. * An object which contains a description of the region.
  151. * @exportDoc
  152. */
  153. /**
  154. * @event shaka.Player.MediaQualityChangedEvent
  155. * @description Fired when the media quality changes at the playhead.
  156. * That may be caused by an adaptation change or a DASH period transition.
  157. * Separate events are emitted for audio and video contentTypes.
  158. * This is supported for only DASH streams at this time.
  159. * @property {string} type
  160. * 'mediaqualitychanged'
  161. * @property {shaka.extern.MediaQualityInfo} mediaQuality
  162. * Information about media quality at the playhead position.
  163. * @property {number} position
  164. * The playhead position.
  165. * @exportDoc
  166. */
  167. /**
  168. * @event shaka.Player.BufferingEvent
  169. * @description Fired when the player's buffering state changes.
  170. * @property {string} type
  171. * 'buffering'
  172. * @property {boolean} buffering
  173. * True when the Player enters the buffering state.
  174. * False when the Player leaves the buffering state.
  175. * @exportDoc
  176. */
  177. /**
  178. * @event shaka.Player.LoadingEvent
  179. * @description Fired when the player begins loading. The start of loading is
  180. * defined as when the user has communicated intent to load content (i.e.
  181. * <code>Player.load</code> has been called).
  182. * @property {string} type
  183. * 'loading'
  184. * @exportDoc
  185. */
  186. /**
  187. * @event shaka.Player.LoadedEvent
  188. * @description Fired when the player ends the load.
  189. * @property {string} type
  190. * 'loaded'
  191. * @exportDoc
  192. */
  193. /**
  194. * @event shaka.Player.UnloadingEvent
  195. * @description Fired when the player unloads or fails to load.
  196. * Used by the Cast receiver to determine idle state.
  197. * @property {string} type
  198. * 'unloading'
  199. * @exportDoc
  200. */
  201. /**
  202. * @event shaka.Player.TextTrackVisibilityEvent
  203. * @description Fired when text track visibility changes.
  204. * @property {string} type
  205. * 'texttrackvisibility'
  206. * @exportDoc
  207. */
  208. /**
  209. * @event shaka.Player.TracksChangedEvent
  210. * @description Fired when the list of tracks changes. For example, this will
  211. * happen when new tracks are added/removed or when track restrictions change.
  212. * @property {string} type
  213. * 'trackschanged'
  214. * @exportDoc
  215. */
  216. /**
  217. * @event shaka.Player.AdaptationEvent
  218. * @description Fired when an automatic adaptation causes the active tracks
  219. * to change. Does not fire when the application calls
  220. * <code>selectVariantTrack()</code>, <code>selectTextTrack()</code>,
  221. * <code>selectAudioLanguage()</code>, or <code>selectTextLanguage()</code>.
  222. * @property {string} type
  223. * 'adaptation'
  224. * @property {shaka.extern.Track} oldTrack
  225. * @property {shaka.extern.Track} newTrack
  226. * @exportDoc
  227. */
  228. /**
  229. * @event shaka.Player.VariantChangedEvent
  230. * @description Fired when a call from the application caused a variant change.
  231. * Can be triggered by calls to <code>selectVariantTrack()</code> or
  232. * <code>selectAudioLanguage()</code>. Does not fire when an automatic
  233. * adaptation causes a variant change.
  234. * @property {string} type
  235. * 'variantchanged'
  236. * @property {shaka.extern.Track} oldTrack
  237. * @property {shaka.extern.Track} newTrack
  238. * @exportDoc
  239. */
  240. /**
  241. * @event shaka.Player.TextChangedEvent
  242. * @description Fired when a call from the application caused a text stream
  243. * change. Can be triggered by calls to <code>selectTextTrack()</code> or
  244. * <code>selectTextLanguage()</code>.
  245. * @property {string} type
  246. * 'textchanged'
  247. * @exportDoc
  248. */
  249. /**
  250. * @event shaka.Player.ExpirationUpdatedEvent
  251. * @description Fired when there is a change in the expiration times of an
  252. * EME session.
  253. * @property {string} type
  254. * 'expirationupdated'
  255. * @exportDoc
  256. */
  257. /**
  258. * @event shaka.Player.ManifestParsedEvent
  259. * @description Fired after the manifest has been parsed, but before anything
  260. * else happens. The manifest may contain streams that will be filtered out,
  261. * at this stage of the loading process.
  262. * @property {string} type
  263. * 'manifestparsed'
  264. * @exportDoc
  265. */
  266. /**
  267. * @event shaka.Player.ManifestUpdatedEvent
  268. * @description Fired after the manifest has been updated (live streams).
  269. * @property {string} type
  270. * 'manifestupdated'
  271. * @property {boolean} isLive
  272. * True when the playlist is live. Useful to detect transition from live
  273. * to static playlist..
  274. * @exportDoc
  275. */
  276. /**
  277. * @event shaka.Player.MetadataEvent
  278. * @description Triggers after metadata associated with the stream is found.
  279. * Usually they are metadata of type ID3.
  280. * @property {string} type
  281. * 'metadata'
  282. * @property {number} startTime
  283. * The time that describes the beginning of the range of the metadata to
  284. * which the cue applies.
  285. * @property {?number} endTime
  286. * The time that describes the end of the range of the metadata to which
  287. * the cue applies.
  288. * @property {string} metadataType
  289. * Type of metadata. Eg: org.id3 or org.mp4ra
  290. * @property {shaka.extern.MetadataFrame} payload
  291. * The metadata itself
  292. * @exportDoc
  293. */
  294. /**
  295. * @event shaka.Player.StreamingEvent
  296. * @description Fired after the manifest has been parsed and track information
  297. * is available, but before streams have been chosen and before any segments
  298. * have been fetched. You may use this event to configure the player based on
  299. * information found in the manifest.
  300. * @property {string} type
  301. * 'streaming'
  302. * @exportDoc
  303. */
  304. /**
  305. * @event shaka.Player.AbrStatusChangedEvent
  306. * @description Fired when the state of abr has been changed.
  307. * (Enabled or disabled).
  308. * @property {string} type
  309. * 'abrstatuschanged'
  310. * @property {boolean} newStatus
  311. * The new status of the application. True for 'is enabled' and
  312. * false otherwise.
  313. * @exportDoc
  314. */
  315. /**
  316. * @event shaka.Player.RateChangeEvent
  317. * @description Fired when the video's playback rate changes.
  318. * This allows the PlayRateController to update it's internal rate field,
  319. * before the UI updates playback button with the newest playback rate.
  320. * @property {string} type
  321. * 'ratechange'
  322. * @exportDoc
  323. */
  324. /**
  325. * @event shaka.Player.SegmentAppended
  326. * @description Fired when a segment is appended to the media element.
  327. * @property {string} type
  328. * 'segmentappended'
  329. * @property {number} start
  330. * The start time of the segment.
  331. * @property {number} end
  332. * The end time of the segment.
  333. * @property {string} contentType
  334. * The content type of the segment. E.g. 'video', 'audio', or 'text'.
  335. * @exportDoc
  336. */
  337. /**
  338. * @event shaka.Player.SessionDataEvent
  339. * @description Fired when the manifest parser find info about session data.
  340. * Specification: https://tools.ietf.org/html/rfc8216#section-4.3.4.4
  341. * @property {string} type
  342. * 'sessiondata'
  343. * @property {string} id
  344. * The id of the session data.
  345. * @property {string} uri
  346. * The uri with the session data info.
  347. * @property {string} language
  348. * The language of the session data.
  349. * @property {string} value
  350. * The value of the session data.
  351. * @exportDoc
  352. */
  353. /**
  354. * @event shaka.Player.StallDetectedEvent
  355. * @description Fired when a stall in playback is detected by the StallDetector.
  356. * Not all stalls are caused by gaps in the buffered ranges.
  357. * @property {string} type
  358. * 'stalldetected'
  359. * @exportDoc
  360. */
  361. /**
  362. * @event shaka.Player.GapJumpedEvent
  363. * @description Fired when the GapJumpingController jumps over a gap in the
  364. * buffered ranges.
  365. * @property {string} type
  366. * 'gapjumped'
  367. * @exportDoc
  368. */
  369. /**
  370. * @event shaka.Player.KeyStatusChanged
  371. * @description Fired when the key status changed.
  372. * @property {string} type
  373. * 'keystatuschanged'
  374. * @exportDoc
  375. */
  376. /**
  377. * @event shaka.Player.StateChanged
  378. * @description Fired when player state is changed.
  379. * @property {string} type
  380. * 'statechanged'
  381. * @property {string} newstate
  382. * The new state.
  383. * @exportDoc
  384. */
  385. /**
  386. * @event shaka.Player.Started
  387. * @description Fires when the content starts playing.
  388. * Only for VoD.
  389. * @property {string} type
  390. * 'started'
  391. * @exportDoc
  392. */
  393. /**
  394. * @event shaka.Player.FirstQuartile
  395. * @description Fires when the content playhead crosses first quartile.
  396. * Only for VoD.
  397. * @property {string} type
  398. * 'firstquartile'
  399. * @exportDoc
  400. */
  401. /**
  402. * @event shaka.Player.Midpoint
  403. * @description Fires when the content playhead crosses midpoint.
  404. * Only for VoD.
  405. * @property {string} type
  406. * 'midpoint'
  407. * @exportDoc
  408. */
  409. /**
  410. * @event shaka.Player.ThirdQuartile
  411. * @description Fires when the content playhead crosses third quartile.
  412. * Only for VoD.
  413. * @property {string} type
  414. * 'thirdquartile'
  415. * @exportDoc
  416. */
  417. /**
  418. * @event shaka.Player.Complete
  419. * @description Fires when the content completes playing.
  420. * Only for VoD.
  421. * @property {string} type
  422. * 'complete'
  423. * @exportDoc
  424. */
  425. /**
  426. * @event shaka.Player.SpatialVideoInfoEvent
  427. * @description Fired when the video has spatial video info. If a previous
  428. * event was fired, this include the new info.
  429. * @property {string} type
  430. * 'spatialvideoinfo'
  431. * @property {shaka.extern.SpatialVideoInfo} detail
  432. * An object which contains the content of the emsg box.
  433. * @exportDoc
  434. */
  435. /**
  436. * @event shaka.Player.NoSpatialVideoInfoEvent
  437. * @description Fired when the video no longer has spatial video information.
  438. * For it to be fired, the shaka.Player.SpatialVideoInfoEvent event must
  439. * have been previously fired.
  440. * @property {string} type
  441. * 'nospatialvideoinfo'
  442. * @exportDoc
  443. */
  444. /**
  445. * @summary The main player object for Shaka Player.
  446. *
  447. * @implements {shaka.util.IDestroyable}
  448. * @export
  449. */
  450. shaka.Player = class extends shaka.util.FakeEventTarget {
  451. /**
  452. * @param {HTMLMediaElement=} mediaElement
  453. * When provided, the player will attach to <code>mediaElement</code>,
  454. * similar to calling <code>attach</code>. When not provided, the player
  455. * will remain detached.
  456. * @param {function(shaka.Player)=} dependencyInjector Optional callback
  457. * which is called to inject mocks into the Player. Used for testing.
  458. */
  459. constructor(mediaElement, dependencyInjector) {
  460. super();
  461. /** @private {shaka.Player.LoadMode} */
  462. this.loadMode_ = shaka.Player.LoadMode.NOT_LOADED;
  463. /** @private {HTMLMediaElement} */
  464. this.video_ = null;
  465. /** @private {HTMLElement} */
  466. this.videoContainer_ = null;
  467. /**
  468. * Since we may not always have a text displayer created (e.g. before |load|
  469. * is called), we need to track what text visibility SHOULD be so that we
  470. * can ensure that when we create the text displayer. When we create our
  471. * text displayer, we will use this to show (or not show) text as per the
  472. * user's requests.
  473. *
  474. * @private {boolean}
  475. */
  476. this.isTextVisible_ = false;
  477. /**
  478. * For listeners scoped to the lifetime of the Player instance.
  479. * @private {shaka.util.EventManager}
  480. */
  481. this.globalEventManager_ = new shaka.util.EventManager();
  482. /**
  483. * For listeners scoped to the lifetime of the media element attachment.
  484. * @private {shaka.util.EventManager}
  485. */
  486. this.attachEventManager_ = new shaka.util.EventManager();
  487. /**
  488. * For listeners scoped to the lifetime of the loaded content.
  489. * @private {shaka.util.EventManager}
  490. */
  491. this.loadEventManager_ = new shaka.util.EventManager();
  492. /**
  493. * For listeners scoped to the lifetime of the loaded content.
  494. * @private {shaka.util.EventManager}
  495. */
  496. this.trickPlayEventManager_ = new shaka.util.EventManager();
  497. /**
  498. * For listeners scoped to the lifetime of the ad manager.
  499. * @private {shaka.util.EventManager}
  500. */
  501. this.adManagerEventManager_ = new shaka.util.EventManager();
  502. /** @private {shaka.net.NetworkingEngine} */
  503. this.networkingEngine_ = null;
  504. /** @private {shaka.media.DrmEngine} */
  505. this.drmEngine_ = null;
  506. /** @private {shaka.media.MediaSourceEngine} */
  507. this.mediaSourceEngine_ = null;
  508. /** @private {shaka.media.Playhead} */
  509. this.playhead_ = null;
  510. /**
  511. * Incremented whenever a top-level operation (load, attach, etc) is
  512. * performed.
  513. * Used to determine if a load operation has been interrupted.
  514. * @private {number}
  515. */
  516. this.operationId_ = 0;
  517. /** @private {!shaka.util.Mutex} */
  518. this.mutex_ = new shaka.util.Mutex();
  519. /**
  520. * The playhead observers are used to monitor the position of the playhead
  521. * and some other source of data (e.g. buffered content), and raise events.
  522. *
  523. * @private {shaka.media.PlayheadObserverManager}
  524. */
  525. this.playheadObservers_ = null;
  526. /**
  527. * This is our control over the playback rate of the media element. This
  528. * provides the missing functionality that we need to provide trick play,
  529. * for example a negative playback rate.
  530. *
  531. * @private {shaka.media.PlayRateController}
  532. */
  533. this.playRateController_ = null;
  534. // We use the buffering observer and timer to track when we move from having
  535. // enough buffered content to not enough. They only exist when content has
  536. // been loaded and are not re-used between loads.
  537. /** @private {shaka.util.Timer} */
  538. this.bufferPoller_ = null;
  539. /** @private {shaka.media.BufferingObserver} */
  540. this.bufferObserver_ = null;
  541. /** @private {shaka.media.RegionTimeline} */
  542. this.regionTimeline_ = null;
  543. /** @private {shaka.util.CmcdManager} */
  544. this.cmcdManager_ = null;
  545. /** @private {shaka.util.CmsdManager} */
  546. this.cmsdManager_ = null;
  547. // This is the canvas element that will be used for rendering LCEVC
  548. // enhanced frames.
  549. /** @private {?HTMLCanvasElement} */
  550. this.lcevcCanvas_ = null;
  551. // This is the LCEVC Decoder object to decode LCEVC.
  552. /** @private {?shaka.lcevc.Dec} */
  553. this.lcevcDec_ = null;
  554. /** @private {shaka.media.QualityObserver} */
  555. this.qualityObserver_ = null;
  556. /** @private {shaka.media.StreamingEngine} */
  557. this.streamingEngine_ = null;
  558. /** @private {shaka.extern.ManifestParser} */
  559. this.parser_ = null;
  560. /** @private {?shaka.extern.ManifestParser.Factory} */
  561. this.parserFactory_ = null;
  562. /** @private {?shaka.extern.Manifest} */
  563. this.manifest_ = null;
  564. /** @private {?string} */
  565. this.assetUri_ = null;
  566. /** @private {?string} */
  567. this.mimeType_ = null;
  568. /** @private {?number} */
  569. this.startTime_ = null;
  570. /** @private {boolean} */
  571. this.fullyLoaded_ = false;
  572. /** @private {shaka.extern.AbrManager} */
  573. this.abrManager_ = null;
  574. /**
  575. * The factory that was used to create the abrManager_ instance.
  576. * @private {?shaka.extern.AbrManager.Factory}
  577. */
  578. this.abrManagerFactory_ = null;
  579. /**
  580. * Contains an ID for use with creating streams. The manifest parser should
  581. * start with small IDs, so this starts with a large one.
  582. * @private {number}
  583. */
  584. this.nextExternalStreamId_ = 1e9;
  585. /** @private {!Array.<shaka.extern.Stream>} */
  586. this.externalSrcEqualsThumbnailsStreams_ = [];
  587. /** @private {number} */
  588. this.completionPercent_ = NaN;
  589. /** @private {?shaka.extern.PlayerConfiguration} */
  590. this.config_ = this.defaultConfig_();
  591. /**
  592. * The TextDisplayerFactory that was last used to make a text displayer.
  593. * Stored so that we can tell if a new type of text displayer is desired.
  594. * @private {?shaka.extern.TextDisplayer.Factory}
  595. */
  596. this.lastTextFactory_;
  597. /** @private {shaka.extern.Resolution} */
  598. this.maxHwRes_ = {width: Infinity, height: Infinity};
  599. /** @private {!shaka.media.ManifestFilterer} */
  600. this.manifestFilterer_ = new shaka.media.ManifestFilterer(
  601. this.config_, this.maxHwRes_, null);
  602. /** @private {!Array.<shaka.media.PreloadManager>} */
  603. this.createdPreloadManagers_ = [];
  604. /** @private {shaka.util.Stats} */
  605. this.stats_ = null;
  606. /** @private {!shaka.media.AdaptationSetCriteria} */
  607. this.currentAdaptationSetCriteria_ =
  608. new shaka.media.PreferenceBasedCriteria(
  609. this.config_.preferredAudioLanguage,
  610. this.config_.preferredVariantRole,
  611. this.config_.preferredAudioChannelCount,
  612. this.config_.preferredVideoHdrLevel,
  613. this.config_.preferSpatialAudio,
  614. this.config_.preferredVideoLayout,
  615. this.config_.preferredAudioLabel,
  616. this.config_.preferredVideoLabel,
  617. this.config_.mediaSource.codecSwitchingStrategy,
  618. this.config_.manifest.dash.enableAudioGroups);
  619. /** @private {string} */
  620. this.currentTextLanguage_ = this.config_.preferredTextLanguage;
  621. /** @private {string} */
  622. this.currentTextRole_ = this.config_.preferredTextRole;
  623. /** @private {boolean} */
  624. this.currentTextForced_ = this.config_.preferForcedSubs;
  625. /** @private {!Array.<function():(!Promise|undefined)>} */
  626. this.cleanupOnUnload_ = [];
  627. if (dependencyInjector) {
  628. dependencyInjector(this);
  629. }
  630. // Create the CMCD manager so client data can be attached to all requests
  631. this.cmcdManager_ = this.createCmcd_();
  632. this.cmsdManager_ = this.createCmsd_();
  633. this.networkingEngine_ = this.createNetworkingEngine();
  634. this.networkingEngine_.setForceHTTP(this.config_.streaming.forceHTTP);
  635. this.networkingEngine_.setForceHTTPS(this.config_.streaming.forceHTTPS);
  636. /** @private {shaka.extern.IAdManager} */
  637. this.adManager_ = null;
  638. /** @private {?shaka.media.PreloadManager} */
  639. this.preloadDueAdManager_ = null;
  640. /** @private {HTMLMediaElement} */
  641. this.preloadDueAdManagerVideo_ = null;
  642. /** @private {shaka.util.Timer} */
  643. this.preloadDueAdManagerTimer_ = new shaka.util.Timer(async () => {
  644. if (this.preloadDueAdManager_) {
  645. goog.asserts.assert(this.preloadDueAdManagerVideo_, 'Must have video');
  646. await this.attach(
  647. this.preloadDueAdManagerVideo_, /* initializeMediaSource= */ true);
  648. await this.load(this.preloadDueAdManager_);
  649. this.preloadDueAdManagerVideo_.play();
  650. this.preloadDueAdManager_ = null;
  651. }
  652. });
  653. if (shaka.Player.adManagerFactory_) {
  654. this.adManager_ = shaka.Player.adManagerFactory_();
  655. this.adManager_.configure(this.config_.ads);
  656. // Note: we don't use shaka.ads.AdManager.AD_STARTED to avoid add a
  657. // optional module in the player.
  658. this.adManagerEventManager_.listen(
  659. this.adManager_, 'ad-started', async (e) => {
  660. if (this.config_.ads.supportsMultipleMediaElements) {
  661. return;
  662. }
  663. const event = /** @type {?google.ima.AdEvent} */
  664. (e['originalEvent']);
  665. if (!event) {
  666. return;
  667. }
  668. const contentPauseRequested =
  669. google.ima.AdEvent.Type.CONTENT_PAUSE_REQUESTED;
  670. if (event.type != contentPauseRequested) {
  671. return;
  672. }
  673. this.preloadDueAdManagerTimer_.stop();
  674. if (!this.preloadDueAdManager_) {
  675. this.preloadDueAdManagerVideo_ = this.video_;
  676. this.preloadDueAdManager_ =
  677. await this.detachAndSavePreload(true);
  678. }
  679. });
  680. // Note: we don't use shaka.ads.AdManager.AD_STOPPED to avoid add a
  681. // optional module in the player.
  682. this.adManagerEventManager_.listen(
  683. this.adManager_, 'ad-stopped', (e) => {
  684. if (this.config_.ads.supportsMultipleMediaElements) {
  685. return;
  686. }
  687. const event = /** @type {?google.ima.AdEvent} */
  688. (e['originalEvent']);
  689. if (!event) {
  690. return;
  691. }
  692. const contentResumeRequested =
  693. google.ima.AdEvent.Type.CONTENT_RESUME_REQUESTED;
  694. if (event.type != contentResumeRequested) {
  695. return;
  696. }
  697. this.preloadDueAdManagerTimer_.tickAfter(0.1);
  698. });
  699. }
  700. // If the browser comes back online after being offline, then try to play
  701. // again.
  702. this.globalEventManager_.listen(window, 'online', () => {
  703. this.restoreDisabledVariants_();
  704. this.retryStreaming();
  705. });
  706. /** @private {shaka.util.Timer} */
  707. this.checkVariantsTimer_ =
  708. new shaka.util.Timer(() => this.checkVariants_());
  709. /** @private {?shaka.media.PreloadManager} */
  710. this.preloadNextUrl_ = null;
  711. // Even though |attach| will start in later interpreter cycles, it should be
  712. // the LAST thing we do in the constructor because conceptually it relies on
  713. // player having been initialized.
  714. if (mediaElement) {
  715. shaka.Deprecate.deprecateFeature(5,
  716. 'Player w/ mediaElement',
  717. 'Please migrate from initializing Player with a mediaElement; ' +
  718. 'use the attach method instead.');
  719. this.attach(mediaElement, /* initializeMediaSource= */ true);
  720. }
  721. }
  722. /**
  723. * Create a shaka.lcevc.Dec object
  724. * @param {shaka.extern.LcevcConfiguration} config
  725. * @private
  726. */
  727. createLcevcDec_(config) {
  728. if (this.lcevcDec_ == null) {
  729. this.lcevcDec_ = new shaka.lcevc.Dec(
  730. /** @type {HTMLVideoElement} */ (this.video_),
  731. this.lcevcCanvas_,
  732. config,
  733. );
  734. if (this.mediaSourceEngine_) {
  735. this.mediaSourceEngine_.updateLcevcDec(this.lcevcDec_);
  736. }
  737. }
  738. }
  739. /**
  740. * Close a shaka.lcevc.Dec object if present and hide the canvas.
  741. * @private
  742. */
  743. closeLcevcDec_() {
  744. if (this.lcevcDec_ != null) {
  745. this.lcevcDec_.hideCanvas();
  746. this.lcevcDec_.release();
  747. this.lcevcDec_ = null;
  748. }
  749. }
  750. /**
  751. * Setup shaka.lcevc.Dec object
  752. * @param {?shaka.extern.PlayerConfiguration} config
  753. * @private
  754. */
  755. setupLcevc_(config) {
  756. if (config.lcevc.enabled) {
  757. this.closeLcevcDec_();
  758. this.createLcevcDec_(config.lcevc);
  759. } else {
  760. this.closeLcevcDec_();
  761. }
  762. }
  763. /**
  764. * @param {!shaka.util.FakeEvent.EventName} name
  765. * @param {Map.<string, Object>=} data
  766. * @return {!shaka.util.FakeEvent}
  767. * @private
  768. */
  769. static makeEvent_(name, data) {
  770. return new shaka.util.FakeEvent(name, data);
  771. }
  772. /**
  773. * After destruction, a Player object cannot be used again.
  774. *
  775. * @override
  776. * @export
  777. */
  778. async destroy() {
  779. // Make sure we only execute the destroy logic once.
  780. if (this.loadMode_ == shaka.Player.LoadMode.DESTROYED) {
  781. return;
  782. }
  783. // If LCEVC Decoder exists close it.
  784. this.closeLcevcDec_();
  785. const detachPromise = this.detach();
  786. // Mark as "dead". This should stop external-facing calls from changing our
  787. // internal state any more. This will stop calls to |attach|, |detach|, etc.
  788. // from interrupting our final move to the detached state.
  789. this.loadMode_ = shaka.Player.LoadMode.DESTROYED;
  790. await detachPromise;
  791. // A PreloadManager can only be used with the Player instance that created
  792. // it, so all PreloadManagers this Player has created are now useless.
  793. // Destroy any remaining managers now, to help prevent memory leaks.
  794. const preloadManagerDestroys = [];
  795. for (const preloadManager of this.createdPreloadManagers_) {
  796. if (!preloadManager.isDestroyed()) {
  797. preloadManagerDestroys.push(preloadManager.destroy());
  798. }
  799. }
  800. this.createdPreloadManagers_ = [];
  801. await Promise.all(preloadManagerDestroys);
  802. // Tear-down the event managers to ensure handlers stop firing.
  803. if (this.globalEventManager_) {
  804. this.globalEventManager_.release();
  805. this.globalEventManager_ = null;
  806. }
  807. if (this.attachEventManager_) {
  808. this.attachEventManager_.release();
  809. this.attachEventManager_ = null;
  810. }
  811. if (this.loadEventManager_) {
  812. this.loadEventManager_.release();
  813. this.loadEventManager_ = null;
  814. }
  815. if (this.trickPlayEventManager_) {
  816. this.trickPlayEventManager_.release();
  817. this.trickPlayEventManager_ = null;
  818. }
  819. if (this.adManagerEventManager_) {
  820. this.adManagerEventManager_.release();
  821. this.adManagerEventManager_ = null;
  822. }
  823. this.abrManagerFactory_ = null;
  824. this.config_ = null;
  825. this.stats_ = null;
  826. this.videoContainer_ = null;
  827. this.cmcdManager_ = null;
  828. this.cmsdManager_ = null;
  829. if (this.networkingEngine_) {
  830. await this.networkingEngine_.destroy();
  831. this.networkingEngine_ = null;
  832. }
  833. if (this.abrManager_) {
  834. this.abrManager_.release();
  835. this.abrManager_ = null;
  836. }
  837. // FakeEventTarget implements IReleasable
  838. super.release();
  839. }
  840. /**
  841. * Registers a plugin callback that will be called with
  842. * <code>support()</code>. The callback will return the value that will be
  843. * stored in the return value from <code>support()</code>.
  844. *
  845. * @param {string} name
  846. * @param {function():*} callback
  847. * @export
  848. */
  849. static registerSupportPlugin(name, callback) {
  850. shaka.Player.supportPlugins_[name] = callback;
  851. }
  852. /**
  853. * Set a factory to create an ad manager during player construction time.
  854. * This method needs to be called bafore instantiating the Player class.
  855. *
  856. * @param {!shaka.extern.IAdManager.Factory} factory
  857. * @export
  858. */
  859. static setAdManagerFactory(factory) {
  860. shaka.Player.adManagerFactory_ = factory;
  861. }
  862. /**
  863. * Return whether the browser provides basic support. If this returns false,
  864. * Shaka Player cannot be used at all. In this case, do not construct a
  865. * Player instance and do not use the library.
  866. *
  867. * @return {boolean}
  868. * @export
  869. */
  870. static isBrowserSupported() {
  871. if (!window.Promise) {
  872. shaka.log.alwaysWarn('A Promise implementation or polyfill is required');
  873. }
  874. // Basic features needed for the library to be usable.
  875. const basicSupport = !!window.Promise && !!window.Uint8Array &&
  876. // eslint-disable-next-line no-restricted-syntax
  877. !!Array.prototype.forEach;
  878. if (!basicSupport) {
  879. return false;
  880. }
  881. // We do not support IE
  882. if (shaka.util.Platform.isIE()) {
  883. return false;
  884. }
  885. const safariVersion = shaka.util.Platform.safariVersion();
  886. if (safariVersion && safariVersion < 9) {
  887. return false;
  888. }
  889. // DRM support is not strictly necessary, but the APIs at least need to be
  890. // there. Our no-op DRM polyfill should handle that.
  891. // TODO(#1017): Consider making even DrmEngine optional.
  892. const drmSupport = shaka.media.DrmEngine.isBrowserSupported();
  893. if (!drmSupport) {
  894. return false;
  895. }
  896. // If we have MediaSource (MSE) support, we should be able to use Shaka.
  897. if (shaka.util.Platform.supportsMediaSource()) {
  898. return true;
  899. }
  900. // If we don't have MSE, we _may_ be able to use Shaka. Look for native HLS
  901. // support, and call this platform usable if we have it.
  902. return shaka.util.Platform.supportsMediaType('application/x-mpegurl');
  903. }
  904. /**
  905. * Probes the browser to determine what features are supported. This makes a
  906. * number of requests to EME/MSE/etc which may result in user prompts. This
  907. * should only be used for diagnostics.
  908. *
  909. * <p>
  910. * NOTE: This may show a request to the user for permission.
  911. *
  912. * @see https://bit.ly/2ywccmH
  913. * @param {boolean=} promptsOkay
  914. * @return {!Promise.<shaka.extern.SupportType>}
  915. * @export
  916. */
  917. static async probeSupport(promptsOkay=true) {
  918. goog.asserts.assert(shaka.Player.isBrowserSupported(),
  919. 'Must have basic support');
  920. let drm = {};
  921. if (promptsOkay) {
  922. drm = await shaka.media.DrmEngine.probeSupport();
  923. }
  924. const manifest = shaka.media.ManifestParser.probeSupport();
  925. const media = shaka.media.MediaSourceEngine.probeSupport();
  926. const hardwareResolution =
  927. await shaka.util.Platform.detectMaxHardwareResolution();
  928. /** @type {shaka.extern.SupportType} */
  929. const ret = {
  930. manifest,
  931. media,
  932. drm,
  933. hardwareResolution,
  934. };
  935. const plugins = shaka.Player.supportPlugins_;
  936. for (const name in plugins) {
  937. ret[name] = plugins[name]();
  938. }
  939. return ret;
  940. }
  941. /**
  942. * Makes a fires an event corresponding to entering a state of the loading
  943. * process.
  944. * @param {string} nodeName
  945. * @private
  946. */
  947. makeStateChangeEvent_(nodeName) {
  948. this.dispatchEvent(shaka.Player.makeEvent_(
  949. /* name= */ shaka.util.FakeEvent.EventName.OnStateChange,
  950. /* data= */ (new Map()).set('state', nodeName)));
  951. }
  952. /**
  953. * Attaches the player to a media element.
  954. * If the player was already attached to a media element, first detaches from
  955. * that media element.
  956. *
  957. * @param {!HTMLMediaElement} mediaElement
  958. * @param {boolean=} initializeMediaSource
  959. * @return {!Promise}
  960. * @export
  961. */
  962. async attach(mediaElement, initializeMediaSource = true) {
  963. // Do not allow the player to be used after |destroy| is called.
  964. if (this.loadMode_ == shaka.Player.LoadMode.DESTROYED) {
  965. throw this.createAbortLoadError_();
  966. }
  967. const noop = this.video_ && this.video_ == mediaElement;
  968. if (this.video_ && this.video_ != mediaElement) {
  969. await this.detach();
  970. }
  971. if (await this.atomicOperationAcquireMutex_('attach')) {
  972. return;
  973. }
  974. try {
  975. if (!noop) {
  976. this.makeStateChangeEvent_('attach');
  977. const onError = (error) => this.onVideoError_(error);
  978. this.attachEventManager_.listen(mediaElement, 'error', onError);
  979. this.video_ = mediaElement;
  980. }
  981. // Only initialize media source if the platform supports it.
  982. if (initializeMediaSource &&
  983. shaka.util.Platform.supportsMediaSource() &&
  984. !this.mediaSourceEngine_) {
  985. await this.initializeMediaSourceEngineInner_();
  986. }
  987. } catch (error) {
  988. await this.detach();
  989. throw error;
  990. } finally {
  991. this.mutex_.release();
  992. }
  993. }
  994. /**
  995. * Calling <code>attachCanvas</code> will tell the player to set canvas
  996. * element for LCEVC decoding.
  997. *
  998. * @param {HTMLCanvasElement} canvas
  999. * @export
  1000. */
  1001. attachCanvas(canvas) {
  1002. this.lcevcCanvas_ = canvas;
  1003. }
  1004. /**
  1005. * Detach the player from the current media element. Leaves the player in a
  1006. * state where it cannot play media, until it has been attached to something
  1007. * else.
  1008. *
  1009. * @param {boolean=} keepAdManager
  1010. *
  1011. * @return {!Promise}
  1012. * @export
  1013. */
  1014. async detach(keepAdManager = false) {
  1015. // Do not allow the player to be used after |destroy| is called.
  1016. if (this.loadMode_ == shaka.Player.LoadMode.DESTROYED) {
  1017. throw this.createAbortLoadError_();
  1018. }
  1019. await this.unload(/* initializeMediaSource= */ false, keepAdManager);
  1020. if (await this.atomicOperationAcquireMutex_('detach')) {
  1021. return;
  1022. }
  1023. try {
  1024. // If we were going from "detached" to "detached" we wouldn't have
  1025. // a media element to detach from.
  1026. if (this.video_) {
  1027. this.attachEventManager_.removeAll();
  1028. this.video_ = null;
  1029. }
  1030. this.makeStateChangeEvent_('detach');
  1031. if (this.adManager_ && !keepAdManager) {
  1032. // The ad manager is specific to the video, so detach it too.
  1033. this.adManager_.release();
  1034. }
  1035. } finally {
  1036. this.mutex_.release();
  1037. }
  1038. }
  1039. /**
  1040. * Tries to acquire the mutex, and then returns if the operation should end
  1041. * early due to someone else starting a mutex-acquiring operation.
  1042. * Meant for operations that can't be interrupted midway through (e.g.
  1043. * everything but load).
  1044. * @param {string} mutexIdentifier
  1045. * @return {!Promise.<boolean>} endEarly If false, the calling context will
  1046. * need to release the mutex.
  1047. * @private
  1048. */
  1049. async atomicOperationAcquireMutex_(mutexIdentifier) {
  1050. const operationId = ++this.operationId_;
  1051. await this.mutex_.acquire(mutexIdentifier);
  1052. if (operationId != this.operationId_) {
  1053. this.mutex_.release();
  1054. return true;
  1055. }
  1056. return false;
  1057. }
  1058. /**
  1059. * Unloads the currently playing stream, if any.
  1060. *
  1061. * @param {boolean=} initializeMediaSource
  1062. * @param {boolean=} keepAdManager
  1063. * @return {!Promise}
  1064. * @export
  1065. */
  1066. async unload(initializeMediaSource = true, keepAdManager = false) {
  1067. // Set the load mode to unload right away so that all the public methods
  1068. // will stop using the internal components. We need to make sure that we
  1069. // are not overriding the destroyed state because we will unload when we are
  1070. // destroying the player.
  1071. if (this.loadMode_ != shaka.Player.LoadMode.DESTROYED) {
  1072. this.loadMode_ = shaka.Player.LoadMode.NOT_LOADED;
  1073. }
  1074. if (await this.atomicOperationAcquireMutex_('unload')) {
  1075. return;
  1076. }
  1077. try {
  1078. this.fullyLoaded_ = false;
  1079. this.makeStateChangeEvent_('unload');
  1080. // If the platform does not support media source, we will never want to
  1081. // initialize media source.
  1082. if (initializeMediaSource && !shaka.util.Platform.supportsMediaSource()) {
  1083. initializeMediaSource = false;
  1084. }
  1085. // If LCEVC Decoder exists close it.
  1086. this.closeLcevcDec_();
  1087. // Run any general cleanup tasks now. This should be here at the top,
  1088. // right after setting loadMode_, so that internal components still exist
  1089. // as they did when the cleanup tasks were registered in the array.
  1090. const cleanupTasks = this.cleanupOnUnload_.map((cb) => cb());
  1091. this.cleanupOnUnload_ = [];
  1092. await Promise.all(cleanupTasks);
  1093. // Dispatch the unloading event.
  1094. this.dispatchEvent(
  1095. shaka.Player.makeEvent_(shaka.util.FakeEvent.EventName.Unloading));
  1096. // Release the region timeline, which is created when parsing the
  1097. // manifest.
  1098. if (this.regionTimeline_) {
  1099. this.regionTimeline_.release();
  1100. this.regionTimeline_ = null;
  1101. }
  1102. // In most cases we should have a media element. The one exception would
  1103. // be if there was an error and we, by chance, did not have a media
  1104. // element.
  1105. if (this.video_) {
  1106. this.loadEventManager_.removeAll();
  1107. this.trickPlayEventManager_.removeAll();
  1108. }
  1109. // Stop the variant checker timer
  1110. this.checkVariantsTimer_.stop();
  1111. // Some observers use some playback components, shutting down the
  1112. // observers first ensures that they don't try to use the playback
  1113. // components mid-destroy.
  1114. if (this.playheadObservers_) {
  1115. this.playheadObservers_.release();
  1116. this.playheadObservers_ = null;
  1117. }
  1118. if (this.bufferPoller_) {
  1119. this.bufferPoller_.stop();
  1120. this.bufferPoller_ = null;
  1121. }
  1122. // Stop the parser early. Since it is at the start of the pipeline, it
  1123. // should be start early to avoid is pushing new data downstream.
  1124. if (this.parser_) {
  1125. await this.parser_.stop();
  1126. this.parser_ = null;
  1127. this.parserFactory_ = null;
  1128. }
  1129. // Abr Manager will tell streaming engine what to do, so we need to stop
  1130. // it before we destroy streaming engine. Unlike with the other
  1131. // components, we do not release the instance, we will reuse it in later
  1132. // loads.
  1133. if (this.abrManager_) {
  1134. await this.abrManager_.stop();
  1135. }
  1136. // Streaming engine will push new data to media source engine, so we need
  1137. // to shut it down before destroy media source engine.
  1138. if (this.streamingEngine_) {
  1139. await this.streamingEngine_.destroy();
  1140. this.streamingEngine_ = null;
  1141. }
  1142. if (this.playRateController_) {
  1143. this.playRateController_.release();
  1144. this.playRateController_ = null;
  1145. }
  1146. // Playhead is used by StreamingEngine, so we can't destroy this until
  1147. // after StreamingEngine has stopped.
  1148. if (this.playhead_) {
  1149. this.playhead_.release();
  1150. this.playhead_ = null;
  1151. }
  1152. // EME v0.1b requires the media element to clear the MediaKeys
  1153. if (shaka.util.Platform.isMediaKeysPolyfilled('webkit') &&
  1154. this.drmEngine_) {
  1155. await this.drmEngine_.destroy();
  1156. this.drmEngine_ = null;
  1157. }
  1158. // Media source engine holds onto the media element, and in order to
  1159. // detach the media keys (with drm engine), we need to break the
  1160. // connection between media source engine and the media element.
  1161. if (this.mediaSourceEngine_) {
  1162. await this.mediaSourceEngine_.destroy();
  1163. this.mediaSourceEngine_ = null;
  1164. }
  1165. if (this.adManager_ && !keepAdManager) {
  1166. this.adManager_.onAssetUnload();
  1167. }
  1168. if (this.preloadDueAdManager_ && !keepAdManager) {
  1169. this.preloadDueAdManager_.destroy();
  1170. this.preloadDueAdManager_ = null;
  1171. }
  1172. if (!keepAdManager) {
  1173. this.preloadDueAdManagerTimer_.stop();
  1174. }
  1175. if (this.cmcdManager_) {
  1176. this.cmcdManager_.reset();
  1177. }
  1178. if (this.cmsdManager_) {
  1179. this.cmsdManager_.reset();
  1180. }
  1181. if (this.video_) {
  1182. // Remove all track nodes
  1183. shaka.util.Dom.removeAllChildren(this.video_);
  1184. }
  1185. // In order to unload a media element, we need to remove the src attribute
  1186. // and then load again. When we destroy media source engine, this will be
  1187. // done for us, but for src=, we need to do it here.
  1188. //
  1189. // DrmEngine requires this to be done before we destroy DrmEngine itself.
  1190. if (this.video_ && this.video_.src) {
  1191. // TODO: Investigate this more. Only reproduces on Firefox 69.
  1192. // Introduce a delay before detaching the video source. We are seeing
  1193. // spurious Promise rejections involving an AbortError in our tests
  1194. // otherwise.
  1195. await new Promise(
  1196. (resolve) => new shaka.util.Timer(resolve).tickAfter(0.1));
  1197. this.video_.removeAttribute('src');
  1198. this.video_.load();
  1199. }
  1200. if (this.drmEngine_) {
  1201. await this.drmEngine_.destroy();
  1202. this.drmEngine_ = null;
  1203. }
  1204. if (this.preloadNextUrl_ &&
  1205. this.assetUri_ != this.preloadNextUrl_.getAssetUri()) {
  1206. if (!this.preloadNextUrl_.isDestroyed()) {
  1207. this.preloadNextUrl_.destroy();
  1208. }
  1209. this.preloadNextUrl_ = null;
  1210. }
  1211. this.assetUri_ = null;
  1212. this.mimeType_ = null;
  1213. this.bufferObserver_ = null;
  1214. if (this.manifest_) {
  1215. for (const variant of this.manifest_.variants) {
  1216. for (const stream of [variant.audio, variant.video]) {
  1217. if (stream && stream.segmentIndex) {
  1218. stream.segmentIndex.release();
  1219. }
  1220. }
  1221. }
  1222. for (const stream of this.manifest_.textStreams) {
  1223. if (stream.segmentIndex) {
  1224. stream.segmentIndex.release();
  1225. }
  1226. }
  1227. }
  1228. // On some devices, cached MediaKeySystemAccess objects may corrupt
  1229. // after several playbacks, and they are not able anymore to properly
  1230. // create MediaKeys objects. To prevent it, clear the cache after
  1231. // each playback.
  1232. if (this.config_.streaming.clearDecodingCache) {
  1233. shaka.util.StreamUtils.clearDecodingConfigCache();
  1234. shaka.media.DrmEngine.clearMediaKeySystemAccessMap();
  1235. }
  1236. this.manifest_ = null;
  1237. this.stats_ = new shaka.util.Stats(); // Replace with a clean object.
  1238. this.lastTextFactory_ = null;
  1239. this.externalSrcEqualsThumbnailsStreams_ = [];
  1240. this.completionPercent_ = NaN;
  1241. // Make sure that the app knows of the new buffering state.
  1242. this.updateBufferState_();
  1243. } finally {
  1244. this.mutex_.release();
  1245. }
  1246. if (initializeMediaSource && shaka.util.Platform.supportsMediaSource() &&
  1247. !this.mediaSourceEngine_) {
  1248. await this.initializeMediaSourceEngineInner_();
  1249. }
  1250. }
  1251. /**
  1252. * Provides a way to update the stream start position during the media loading
  1253. * process. Can for example be called from the <code>manifestparsed</code>
  1254. * event handler to update the start position based on information in the
  1255. * manifest.
  1256. *
  1257. * @param {number} startTime
  1258. * @export
  1259. */
  1260. updateStartTime(startTime) {
  1261. this.startTime_ = startTime;
  1262. }
  1263. /**
  1264. * Loads a new stream.
  1265. * If another stream was already playing, first unloads that stream.
  1266. *
  1267. * @param {string|shaka.media.PreloadManager} assetUriOrPreloader
  1268. * @param {?number=} startTime
  1269. * When <code>startTime</code> is <code>null</code> or
  1270. * <code>undefined</code>, playback will start at the default start time (0
  1271. * for VOD and liveEdge for LIVE).
  1272. * @param {?string=} mimeType
  1273. * @return {!Promise}
  1274. * @export
  1275. */
  1276. async load(assetUriOrPreloader, startTime = null, mimeType) {
  1277. // Do not allow the player to be used after |destroy| is called.
  1278. if (this.loadMode_ == shaka.Player.LoadMode.DESTROYED) {
  1279. throw this.createAbortLoadError_();
  1280. }
  1281. /** @type {?shaka.media.PreloadManager} */
  1282. let preloadManager = null;
  1283. let assetUri = '';
  1284. if (assetUriOrPreloader instanceof shaka.media.PreloadManager) {
  1285. preloadManager = assetUriOrPreloader;
  1286. assetUri = preloadManager.getAssetUri() || '';
  1287. } else {
  1288. assetUri = assetUriOrPreloader || '';
  1289. }
  1290. // Quickly acquire the mutex, so this will wait for other top-level
  1291. // operations.
  1292. await this.mutex_.acquire('load');
  1293. this.mutex_.release();
  1294. if (!this.video_) {
  1295. throw new shaka.util.Error(
  1296. shaka.util.Error.Severity.CRITICAL,
  1297. shaka.util.Error.Category.PLAYER,
  1298. shaka.util.Error.Code.NO_VIDEO_ELEMENT);
  1299. }
  1300. if (this.assetUri_) {
  1301. // Note: This is used to avoid the destruction of the nextUrl
  1302. // preloadManager that can be the current one.
  1303. this.assetUri_ = assetUri;
  1304. await this.unload(/* initializeMediaSource= */ false);
  1305. }
  1306. // Add a mechanism to detect if the load process has been interrupted by a
  1307. // call to another top-level operation (unload, load, etc).
  1308. const operationId = ++this.operationId_;
  1309. const detectInterruption = async () => {
  1310. if (this.operationId_ != operationId) {
  1311. if (preloadManager) {
  1312. await preloadManager.destroy();
  1313. }
  1314. throw this.createAbortLoadError_();
  1315. }
  1316. };
  1317. /**
  1318. * Wraps a given operation with mutex.acquire and mutex.release, along with
  1319. * calls to detectInterruption, to catch any other top-level calls happening
  1320. * while waiting for the mutex.
  1321. * @param {function():!Promise} operation
  1322. * @param {string} mutexIdentifier
  1323. * @return {!Promise}
  1324. */
  1325. const mutexWrapOperation = async (operation, mutexIdentifier) => {
  1326. try {
  1327. await this.mutex_.acquire(mutexIdentifier);
  1328. await detectInterruption();
  1329. await operation();
  1330. await detectInterruption();
  1331. if (preloadManager && this.config_) {
  1332. preloadManager.reconfigure(this.config_);
  1333. }
  1334. } finally {
  1335. this.mutex_.release();
  1336. }
  1337. };
  1338. try {
  1339. if (startTime == null && preloadManager) {
  1340. startTime = preloadManager.getStartTime();
  1341. }
  1342. this.startTime_ = startTime;
  1343. this.fullyLoaded_ = false;
  1344. // We dispatch the loading event when someone calls |load| because we want
  1345. // to surface the user intent.
  1346. this.dispatchEvent(shaka.Player.makeEvent_(
  1347. shaka.util.FakeEvent.EventName.Loading));
  1348. if (preloadManager) {
  1349. mimeType = preloadManager.getMimeType();
  1350. } else if (!mimeType) {
  1351. await mutexWrapOperation(async () => {
  1352. mimeType = await this.guessMimeType_(assetUri);
  1353. }, 'guessMimeType_');
  1354. }
  1355. const wasPreloaded = !!preloadManager;
  1356. if (!preloadManager) {
  1357. // For simplicity, if an asset is NOT preloaded, start an internal
  1358. // "preload" here without prefetch.
  1359. // That way, both a preload and normal load can follow the same code
  1360. // paths.
  1361. // NOTE: await preloadInner_ can be outside the mutex because it should
  1362. // not mutate "this".
  1363. preloadManager = await this.preloadInner_(
  1364. assetUri, startTime, mimeType, /* standardLoad= */ true);
  1365. if (preloadManager) {
  1366. preloadManager.setEventHandoffTarget(this);
  1367. this.stats_ = preloadManager.getStats();
  1368. preloadManager.start();
  1369. // Silence "uncaught error" warnings from this. Unless we are
  1370. // interrupted, we will check the result of this process and respond
  1371. // appropriately. If we are interrupted, we can ignore any error
  1372. // there.
  1373. preloadManager.waitForFinish().catch(() => {});
  1374. } else {
  1375. this.stats_ = new shaka.util.Stats();
  1376. }
  1377. } else {
  1378. // Hook up events, so any events emitted by the preloadManager will
  1379. // instead be emitted by the player.
  1380. preloadManager.setEventHandoffTarget(this);
  1381. this.stats_ = preloadManager.getStats();
  1382. }
  1383. // Now, if there is no preload manager, that means that this is a src=
  1384. // asset.
  1385. const shouldUseSrcEquals = !preloadManager;
  1386. const startTimeOfLoad = preloadManager ?
  1387. preloadManager.getStartTimeOfLoad() : (Date.now() / 1000);
  1388. // Stats are for a single playback/load session. Stats must be initialized
  1389. // before we allow calls to |updateStateHistory|.
  1390. this.stats_ =
  1391. preloadManager ? preloadManager.getStats() : new shaka.util.Stats();
  1392. this.assetUri_ = assetUri;
  1393. this.mimeType_ = mimeType || null;
  1394. if (shouldUseSrcEquals) {
  1395. await mutexWrapOperation(async () => {
  1396. goog.asserts.assert(mimeType, 'We should know the mimeType by now!');
  1397. await this.initializeSrcEqualsDrmInner_(mimeType);
  1398. }, 'initializeSrcEqualsDrmInner_');
  1399. await mutexWrapOperation(async () => {
  1400. goog.asserts.assert(mimeType, 'We should know the mimeType by now!');
  1401. await this.srcEqualsInner_(startTimeOfLoad, mimeType);
  1402. }, 'srcEqualsInner_');
  1403. } else {
  1404. if (!this.mediaSourceEngine_) {
  1405. await mutexWrapOperation(async () => {
  1406. await this.initializeMediaSourceEngineInner_();
  1407. }, 'initializeMediaSourceEngineInner_');
  1408. }
  1409. // Wait for the preload manager to do all of the loading it can do.
  1410. await mutexWrapOperation(async () => {
  1411. await preloadManager.waitForFinish();
  1412. }, 'waitForFinish');
  1413. // Get manifest and associated values from preloader.
  1414. this.config_ = preloadManager.getConfiguration();
  1415. this.manifestFilterer_ = preloadManager.getManifestFilterer();
  1416. this.parserFactory_ = preloadManager.getParserFactory();
  1417. this.parser_ = preloadManager.receiveParser();
  1418. this.regionTimeline_ = preloadManager.receiveRegionTimeline();
  1419. this.qualityObserver_ = preloadManager.getQualityObserver();
  1420. this.manifest_ = preloadManager.getManifest();
  1421. const currentAdaptationSetCriteria =
  1422. preloadManager.getCurrentAdaptationSetCriteria();
  1423. if (currentAdaptationSetCriteria) {
  1424. this.currentAdaptationSetCriteria_ = currentAdaptationSetCriteria;
  1425. }
  1426. if (wasPreloaded && this.video_ && this.video_.nodeName === 'AUDIO') {
  1427. // Filter the variants to be audio-only after the fact.
  1428. // As, when preloading, we don't know if we are going to be attached
  1429. // to a video or audio element when we load, we have to do the auto
  1430. // audio-only filtering here, post-facto.
  1431. this.makeManifestAudioOnly_();
  1432. // And continue to do so in the future.
  1433. this.configure('manifest.disableVideo', true);
  1434. }
  1435. // Get drm engine from preloader, then finalize it.
  1436. this.drmEngine_ = preloadManager.receiveDrmEngine();
  1437. await mutexWrapOperation(async () => {
  1438. await this.drmEngine_.attach(this.video_);
  1439. }, 'drmEngine_.attach');
  1440. // Also get the ABR manager, which has special logic related to being
  1441. // received.
  1442. const abrManagerFactory = preloadManager.getAbrManagerFactory();
  1443. if (abrManagerFactory) {
  1444. if (!this.abrManagerFactory_ ||
  1445. this.abrManagerFactory_ != abrManagerFactory) {
  1446. this.abrManager_ = preloadManager.receiveAbrManager();
  1447. this.abrManagerFactory_ = preloadManager.getAbrManagerFactory();
  1448. if (typeof this.abrManager_.setMediaElement != 'function') {
  1449. shaka.Deprecate.deprecateFeature(5,
  1450. 'AbrManager w/o setMediaElement',
  1451. 'Please use an AbrManager with setMediaElement function.');
  1452. this.abrManager_.setMediaElement = () => {};
  1453. }
  1454. if (typeof this.abrManager_.setCmsdManager != 'function') {
  1455. shaka.Deprecate.deprecateFeature(5,
  1456. 'AbrManager w/o setCmsdManager',
  1457. 'Please use an AbrManager with setCmsdManager function.');
  1458. this.abrManager_.setCmsdManager = () => {};
  1459. }
  1460. if (typeof this.abrManager_.trySuggestStreams != 'function') {
  1461. shaka.Deprecate.deprecateFeature(5,
  1462. 'AbrManager w/o trySuggestStreams',
  1463. 'Please use an AbrManager with trySuggestStreams function.');
  1464. this.abrManager_.trySuggestStreams = () => {};
  1465. }
  1466. }
  1467. }
  1468. // Load the asset.
  1469. const segmentPrefetchById =
  1470. preloadManager.receiveSegmentPrefetchesById();
  1471. const prefetchedVariant = preloadManager.getPrefetchedVariant();
  1472. await mutexWrapOperation(async () => {
  1473. await this.loadInner_(
  1474. startTimeOfLoad, prefetchedVariant, segmentPrefetchById);
  1475. }, 'loadInner_');
  1476. preloadManager.stopQueuingLatePhaseQueuedOperations();
  1477. }
  1478. this.dispatchEvent(shaka.Player.makeEvent_(
  1479. shaka.util.FakeEvent.EventName.Loaded));
  1480. } catch (error) {
  1481. if (error.code != shaka.util.Error.Code.LOAD_INTERRUPTED) {
  1482. await this.unload(/* initializeMediaSource= */ false);
  1483. }
  1484. throw error;
  1485. } finally {
  1486. if (preloadManager) {
  1487. // This will cause any resources that were generated but not used to be
  1488. // properly destroyed or released.
  1489. await preloadManager.destroy();
  1490. }
  1491. this.preloadNextUrl_ = null;
  1492. }
  1493. }
  1494. /**
  1495. * Modifies the current manifest so that it is audio-only.
  1496. * @private
  1497. */
  1498. makeManifestAudioOnly_() {
  1499. for (const variant of this.manifest_.variants) {
  1500. if (variant.video) {
  1501. variant.video.closeSegmentIndex();
  1502. variant.video = null;
  1503. }
  1504. if (variant.audio && variant.audio.bandwidth) {
  1505. variant.bandwidth = variant.audio.bandwidth;
  1506. } else {
  1507. variant.bandwidth = 0;
  1508. }
  1509. }
  1510. this.manifest_.variants = this.manifest_.variants.filter((v) => {
  1511. return v.audio;
  1512. });
  1513. }
  1514. /**
  1515. * Unloads the currently playing stream, if any, and returns a PreloadManager
  1516. * that contains the loaded manifest of that asset, if any.
  1517. * Allows for the asset to be re-loaded by this player faster, in the future.
  1518. * When in src= mode, this unloads but does not make a PreloadManager.
  1519. *
  1520. * @param {boolean=} initializeMediaSource
  1521. * @param {boolean=} keepAdManager
  1522. * @return {!Promise.<?shaka.media.PreloadManager>}
  1523. * @export
  1524. */
  1525. async unloadAndSavePreload(
  1526. initializeMediaSource = true, keepAdManager = false) {
  1527. const preloadManager = await this.savePreload_();
  1528. await this.unload(initializeMediaSource, keepAdManager);
  1529. return preloadManager;
  1530. }
  1531. /**
  1532. * Detach the player from the current media element, if any, and returns a
  1533. * PreloadManager that contains the loaded manifest of that asset, if any.
  1534. * Allows for the asset to be re-loaded by this player faster, in the future.
  1535. * When in src= mode, this detach but does not make a PreloadManager.
  1536. * Leaves the player in a state where it cannot play media, until it has been
  1537. * attached to something else.
  1538. *
  1539. * @param {boolean=} keepAdManager
  1540. * @return {!Promise.<?shaka.media.PreloadManager>}
  1541. * @export
  1542. */
  1543. async detachAndSavePreload(keepAdManager = false) {
  1544. const preloadManager = await this.savePreload_();
  1545. await this.detach(keepAdManager);
  1546. return preloadManager;
  1547. }
  1548. /**
  1549. * @return {!Promise.<?shaka.media.PreloadManager>}
  1550. * @private
  1551. */
  1552. async savePreload_() {
  1553. let preloadManager = null;
  1554. if (this.manifest_ && this.parser_ && this.parserFactory_ &&
  1555. this.assetUri_) {
  1556. let startTime = this.video_.currentTime;
  1557. if (this.isLive()) {
  1558. startTime = null;
  1559. }
  1560. // We have enough information to make a PreloadManager!
  1561. const startTimeOfLoad = Date.now() / 1000;
  1562. preloadManager = await this.makePreloadManager_(
  1563. this.assetUri_,
  1564. startTime,
  1565. this.mimeType_,
  1566. startTimeOfLoad,
  1567. /* allowPrefetch= */ true,
  1568. /* disableVideo= */ false,
  1569. /* allowMakeAbrManager= */ false);
  1570. preloadManager.attachManifest(
  1571. this.manifest_, this.parser_, this.parserFactory_);
  1572. preloadManager.attachAbrManager(
  1573. this.abrManager_, this.abrManagerFactory_);
  1574. preloadManager.attachAdaptationSetCriteria(
  1575. this.currentAdaptationSetCriteria_);
  1576. preloadManager.start();
  1577. // Null the manifest and manifestParser, so that they won't be shut down
  1578. // during unload and will continue to live inside the preloadManager.
  1579. this.manifest_ = null;
  1580. this.parser_ = null;
  1581. this.parserFactory_ = null;
  1582. // Null the abrManager and abrManagerFactory, so that they won't be shut
  1583. // down during unload and will continue to live inside the preloadManager.
  1584. this.abrManager_ = null;
  1585. this.abrManagerFactory_ = null;
  1586. }
  1587. return preloadManager;
  1588. }
  1589. /**
  1590. * Starts to preload a given asset, and returns a PreloadManager object that
  1591. * represents that preloading process.
  1592. * The PreloadManager will load the manifest for that asset, as well as the
  1593. * initialization segment. It will not preload anything more than that;
  1594. * this feature is intended for reducing start-time latency, not for fully
  1595. * downloading assets before playing them (for that, use
  1596. * |shaka.offline.Storage|).
  1597. * You can pass that PreloadManager object in to the |load| method on this
  1598. * Player instance to finish loading that particular asset, or you can call
  1599. * the |destroy| method on the manager if the preload is no longer necessary.
  1600. * If this returns null rather than a PreloadManager, that indicates that the
  1601. * asset must be played with src=, which cannot be preloaded.
  1602. *
  1603. * @param {string} assetUri
  1604. * @param {?number=} startTime
  1605. * When <code>startTime</code> is <code>null</code> or
  1606. * <code>undefined</code>, playback will start at the default start time (0
  1607. * for VOD and liveEdge for LIVE).
  1608. * @param {?string=} mimeType
  1609. * @return {!Promise.<?shaka.media.PreloadManager>}
  1610. * @export
  1611. */
  1612. async preload(assetUri, startTime = null, mimeType) {
  1613. const preloadManager = await this.preloadInner_(
  1614. assetUri, startTime, mimeType);
  1615. if (!preloadManager) {
  1616. this.onError_(new shaka.util.Error(
  1617. shaka.util.Error.Severity.CRITICAL,
  1618. shaka.util.Error.Category.PLAYER,
  1619. shaka.util.Error.Code.SRC_EQUALS_PRELOAD_NOT_SUPPORTED));
  1620. } else {
  1621. preloadManager.start();
  1622. }
  1623. return preloadManager;
  1624. }
  1625. /**
  1626. * @param {string} assetUri
  1627. * @param {?number} startTime
  1628. * @param {?string=} mimeType
  1629. * @param {boolean=} standardLoad
  1630. * @return {!Promise.<?shaka.media.PreloadManager>}
  1631. * @private
  1632. */
  1633. async preloadInner_(assetUri, startTime, mimeType, standardLoad = false) {
  1634. goog.asserts.assert(this.networkingEngine_, 'Should have a net engine!');
  1635. goog.asserts.assert(this.config_, 'Config must not be null!');
  1636. const startTimeOfLoad = Date.now() / 1000;
  1637. if (!mimeType) {
  1638. mimeType = await this.guessMimeType_(assetUri);
  1639. }
  1640. const shouldUseSrcEquals = this.shouldUseSrcEquals_(assetUri, mimeType);
  1641. if (shouldUseSrcEquals) {
  1642. // We cannot preload src= content.
  1643. return null;
  1644. }
  1645. let disableVideo = false;
  1646. let allowMakeAbrManager = true;
  1647. if (standardLoad) {
  1648. if (this.abrManager_ &&
  1649. this.abrManagerFactory_ == this.config_.abrFactory) {
  1650. // If there's already an abr manager, don't make a new abr manager at
  1651. // all.
  1652. // In standardLoad mode, the abr manager isn't used for anything anyway,
  1653. // so it should only be created to create an abr manager for the player
  1654. // to use... which is unnecessary if we already have one of the right
  1655. // type.
  1656. allowMakeAbrManager = false;
  1657. }
  1658. if (this.video_ && this.video_.nodeName === 'AUDIO') {
  1659. disableVideo = true;
  1660. }
  1661. }
  1662. return this.makePreloadManager_(
  1663. assetUri, startTime, mimeType || null, startTimeOfLoad,
  1664. /* allowPrefetch= */ !standardLoad, disableVideo, allowMakeAbrManager);
  1665. }
  1666. /**
  1667. * @param {string} assetUri
  1668. * @param {?number} startTime
  1669. * @param {?string} mimeType
  1670. * @param {number} startTimeOfLoad
  1671. * @param {boolean=} allowPrefetch
  1672. * @param {boolean=} disableVideo
  1673. * @param {boolean=} allowMakeAbrManager
  1674. * @return {!Promise.<!shaka.media.PreloadManager>}
  1675. * @private
  1676. */
  1677. async makePreloadManager_(assetUri, startTime, mimeType, startTimeOfLoad,
  1678. allowPrefetch = true, disableVideo = false, allowMakeAbrManager = true) {
  1679. goog.asserts.assert(this.networkingEngine_, 'Must have net engine');
  1680. /** @type {?shaka.media.PreloadManager} */
  1681. let preloadManager = null;
  1682. const config = shaka.util.ObjectUtils.cloneObject(this.config_);
  1683. if (disableVideo) {
  1684. config.manifest.disableVideo = true;
  1685. }
  1686. const getPreloadManager = () => {
  1687. goog.asserts.assert(preloadManager, 'Must have preload manager');
  1688. if (preloadManager.hasBeenAttached() && preloadManager.isDestroyed()) {
  1689. return null;
  1690. }
  1691. return preloadManager;
  1692. };
  1693. const getConfig = () => {
  1694. if (getPreloadManager()) {
  1695. return getPreloadManager().getConfiguration();
  1696. } else {
  1697. return this.config_;
  1698. }
  1699. };
  1700. const setConfig = (name, value) => {
  1701. if (getPreloadManager()) {
  1702. preloadManager.configure(name, value);
  1703. } else {
  1704. this.configure(name, value);
  1705. }
  1706. };
  1707. // Avoid having to detect the resolution again if it has already been
  1708. // detected or set
  1709. if (this.maxHwRes_.width == Infinity &&
  1710. this.maxHwRes_.height == Infinity) {
  1711. const maxResolution =
  1712. await shaka.util.Platform.detectMaxHardwareResolution();
  1713. this.maxHwRes_.width = maxResolution.width;
  1714. this.maxHwRes_.height = maxResolution.height;
  1715. }
  1716. const manifestFilterer = new shaka.media.ManifestFilterer(
  1717. config, this.maxHwRes_, null);
  1718. const manifestPlayerInterface = {
  1719. networkingEngine: this.networkingEngine_,
  1720. filter: async (manifest) => {
  1721. const tracksChanged = await manifestFilterer.filterManifest(manifest);
  1722. if (tracksChanged) {
  1723. // Delay the 'trackschanged' event so StreamingEngine has time to
  1724. // absorb the changes before the user tries to query it.
  1725. const event = shaka.Player.makeEvent_(
  1726. shaka.util.FakeEvent.EventName.TracksChanged);
  1727. await Promise.resolve();
  1728. preloadManager.dispatchEvent(event);
  1729. }
  1730. },
  1731. makeTextStreamsForClosedCaptions: (manifest) => {
  1732. return this.makeTextStreamsForClosedCaptions_(manifest);
  1733. },
  1734. // Called when the parser finds a timeline region. This can be called
  1735. // before we start playback or during playback (live/in-progress
  1736. // manifest).
  1737. onTimelineRegionAdded: (region) => {
  1738. preloadManager.getRegionTimeline().addRegion(region);
  1739. },
  1740. onEvent: (event) => preloadManager.dispatchEvent(event),
  1741. onError: (error) => preloadManager.onError(error),
  1742. isLowLatencyMode: () => getConfig().streaming.lowLatencyMode,
  1743. isAutoLowLatencyMode: () => getConfig().streaming.autoLowLatencyMode,
  1744. enableLowLatencyMode: () => {
  1745. setConfig('streaming.lowLatencyMode', true);
  1746. },
  1747. updateDuration: () => {
  1748. if (this.streamingEngine_ && preloadManager.hasBeenAttached()) {
  1749. this.streamingEngine_.updateDuration();
  1750. }
  1751. },
  1752. newDrmInfo: (stream) => {
  1753. // We may need to create new sessions for any new init data.
  1754. const drmEngine = preloadManager.getDrmEngine();
  1755. const currentDrmInfo = drmEngine ? drmEngine.getDrmInfo() : null;
  1756. // DrmEngine.newInitData() requires mediaKeys to be available.
  1757. if (currentDrmInfo && drmEngine.getMediaKeys()) {
  1758. manifestFilterer.processDrmInfos(currentDrmInfo.keySystem, stream);
  1759. }
  1760. },
  1761. onManifestUpdated: () => {
  1762. const eventName = shaka.util.FakeEvent.EventName.ManifestUpdated;
  1763. const data = (new Map()).set('isLive', this.isLive());
  1764. preloadManager.dispatchEvent(shaka.Player.makeEvent_(eventName, data));
  1765. preloadManager.addQueuedOperation(false, () => {
  1766. if (this.adManager_) {
  1767. this.adManager_.onManifestUpdated(this.isLive());
  1768. }
  1769. });
  1770. },
  1771. getBandwidthEstimate: () => this.abrManager_.getBandwidthEstimate(),
  1772. };
  1773. const regionTimeline =
  1774. new shaka.media.RegionTimeline(() => this.seekRange());
  1775. regionTimeline.addEventListener('regionadd', (event) => {
  1776. /** @type {shaka.extern.TimelineRegionInfo} */
  1777. const region = event['region'];
  1778. this.onRegionEvent_(
  1779. shaka.util.FakeEvent.EventName.TimelineRegionAdded, region,
  1780. preloadManager);
  1781. preloadManager.addQueuedOperation(false, () => {
  1782. if (this.adManager_) {
  1783. this.adManager_.onDashTimedMetadata(region);
  1784. }
  1785. });
  1786. });
  1787. let qualityObserver = null;
  1788. if (config.streaming.observeQualityChanges) {
  1789. qualityObserver = new shaka.media.QualityObserver(
  1790. () => this.getBufferedInfo());
  1791. qualityObserver.addEventListener('qualitychange', (event) => {
  1792. /** @type {shaka.extern.MediaQualityInfo} */
  1793. const mediaQualityInfo = event['quality'];
  1794. /** @type {number} */
  1795. const position = event['position'];
  1796. this.onMediaQualityChange_(mediaQualityInfo, position);
  1797. });
  1798. }
  1799. let firstEvent = true;
  1800. const drmPlayerInterface = {
  1801. netEngine: this.networkingEngine_,
  1802. onError: (e) => preloadManager.onError(e),
  1803. onKeyStatus: (map) => {
  1804. preloadManager.addQueuedOperation(true, () => {
  1805. this.onKeyStatus_(map);
  1806. });
  1807. },
  1808. onExpirationUpdated: (id, expiration) => {
  1809. const event = shaka.Player.makeEvent_(
  1810. shaka.util.FakeEvent.EventName.ExpirationUpdated);
  1811. preloadManager.dispatchEvent(event);
  1812. const parser = preloadManager.getParser();
  1813. if (parser && parser.onExpirationUpdated) {
  1814. parser.onExpirationUpdated(id, expiration);
  1815. }
  1816. },
  1817. onEvent: (e) => {
  1818. preloadManager.dispatchEvent(e);
  1819. if (e.type == shaka.util.FakeEvent.EventName.DrmSessionUpdate &&
  1820. firstEvent) {
  1821. firstEvent = false;
  1822. const now = Date.now() / 1000;
  1823. const delta = now - preloadManager.getStartTimeOfDRM();
  1824. const stats = this.stats_ || preloadManager.getStats();
  1825. stats.setDrmTime(delta);
  1826. // LCEVC data by itself is not encrypted in DRM protected streams
  1827. // and can therefore be accessed and decoded as normal. However,
  1828. // the LCEVC decoder needs access to the VideoElement output in
  1829. // order to apply the enhancement. In DRM contexts where the
  1830. // browser CDM restricts access from our decoder, the enhancement
  1831. // cannot be applied and therefore the LCEVC output canvas is
  1832. // hidden accordingly.
  1833. if (this.lcevcDec_) {
  1834. this.lcevcDec_.hideCanvas();
  1835. }
  1836. }
  1837. },
  1838. };
  1839. // Sadly, as the network engine creation code must be replaceable by tests,
  1840. // it cannot be made and use the utilities defined in this function.
  1841. const networkingEngine = this.createNetworkingEngine(getPreloadManager);
  1842. this.networkingEngine_.copyFiltersInto(networkingEngine);
  1843. /** @return {!shaka.media.DrmEngine} */
  1844. const createDrmEngine = () => {
  1845. return this.createDrmEngine(drmPlayerInterface);
  1846. };
  1847. /** @type {!shaka.media.PreloadManager.PlayerInterface} */
  1848. const playerInterface = {
  1849. config,
  1850. manifestPlayerInterface,
  1851. regionTimeline,
  1852. qualityObserver,
  1853. createDrmEngine,
  1854. manifestFilterer,
  1855. networkingEngine,
  1856. allowPrefetch,
  1857. allowMakeAbrManager,
  1858. };
  1859. preloadManager = new shaka.media.PreloadManager(
  1860. assetUri, mimeType, startTimeOfLoad, startTime, playerInterface);
  1861. this.createdPreloadManagers_.push(preloadManager);
  1862. return preloadManager;
  1863. }
  1864. /**
  1865. * Determines the mimeType of the given asset, if we are not told that inside
  1866. * the loading process.
  1867. *
  1868. * @param {string} assetUri
  1869. * @return {!Promise.<?string>} mimeType
  1870. * @private
  1871. */
  1872. async guessMimeType_(assetUri) {
  1873. // If no MIME type is provided, and we can't base it on extension, make a
  1874. // HEAD request to determine it.
  1875. goog.asserts.assert(this.networkingEngine_, 'Should have a net engine!');
  1876. const retryParams = this.config_.manifest.retryParameters;
  1877. let mimeType = await shaka.net.NetworkingUtils.getMimeType(
  1878. assetUri, this.networkingEngine_, retryParams);
  1879. if (mimeType == 'application/x-mpegurl' && shaka.util.Platform.isApple()) {
  1880. mimeType = 'application/vnd.apple.mpegurl';
  1881. }
  1882. return mimeType;
  1883. }
  1884. /**
  1885. * Determines if we should use src equals, based on the the mimeType (if
  1886. * known), the URI, and platform information.
  1887. *
  1888. * @param {string} assetUri
  1889. * @param {?string=} mimeType
  1890. * @return {boolean}
  1891. * |true| if the content should be loaded with src=, |false| if the content
  1892. * should be loaded with MediaSource.
  1893. * @private
  1894. */
  1895. shouldUseSrcEquals_(assetUri, mimeType) {
  1896. const Platform = shaka.util.Platform;
  1897. const MimeUtils = shaka.util.MimeUtils;
  1898. // If we are using a platform that does not support media source, we will
  1899. // fall back to src= to handle all playback.
  1900. if (!Platform.supportsMediaSource()) {
  1901. return true;
  1902. }
  1903. if (mimeType) {
  1904. // If we have a MIME type, check if the browser can play it natively.
  1905. // This will cover both single files and native HLS.
  1906. const mediaElement = this.video_ || Platform.anyMediaElement();
  1907. const canPlayNatively = mediaElement.canPlayType(mimeType) != '';
  1908. // If we can't play natively, then src= isn't an option.
  1909. if (!canPlayNatively) {
  1910. return false;
  1911. }
  1912. const canPlayMediaSource =
  1913. shaka.media.ManifestParser.isSupported(mimeType);
  1914. // If MediaSource isn't an option, the native option is our only chance.
  1915. if (!canPlayMediaSource) {
  1916. return true;
  1917. }
  1918. // If we land here, both are feasible.
  1919. goog.asserts.assert(canPlayNatively && canPlayMediaSource,
  1920. 'Both native and MSE playback should be possible!');
  1921. // We would prefer MediaSource in some cases, and src= in others. For
  1922. // example, Android has native HLS, but we'd prefer our own MediaSource
  1923. // version there.
  1924. if (MimeUtils.isHlsType(mimeType)) {
  1925. // Native HLS can be preferred on any platform via this flag:
  1926. if (this.config_.streaming.preferNativeHls) {
  1927. return true;
  1928. }
  1929. // Native FairPlay HLS can be preferred on Apple platfforms.
  1930. if (Platform.isApple() &&
  1931. (this.config_.drm.servers['com.apple.fps'] ||
  1932. this.config_.drm.servers['com.apple.fps.1_0'])) {
  1933. return this.config_.streaming.useNativeHlsForFairPlay;
  1934. }
  1935. // For Safari, we have an older flag which only applies to this one
  1936. // browser:
  1937. if (Platform.isApple()) {
  1938. return this.config_.streaming.useNativeHlsOnSafari;
  1939. }
  1940. }
  1941. // In all other cases, we prefer MediaSource.
  1942. return false;
  1943. }
  1944. // Unless there are good reasons to use src= (single-file playback or native
  1945. // HLS), we prefer MediaSource. So the final return value for choosing src=
  1946. // is false.
  1947. return false;
  1948. }
  1949. /**
  1950. * Initializes the media source engine.
  1951. *
  1952. * @return {!Promise}
  1953. * @private
  1954. */
  1955. async initializeMediaSourceEngineInner_() {
  1956. goog.asserts.assert(
  1957. shaka.util.Platform.supportsMediaSource(),
  1958. 'We should not be initializing media source on a platform that ' +
  1959. 'does not support media source.');
  1960. goog.asserts.assert(
  1961. this.video_,
  1962. 'We should have a media element when initializing media source.');
  1963. goog.asserts.assert(
  1964. this.mediaSourceEngine_ == null,
  1965. 'We should not have a media source engine yet.');
  1966. this.makeStateChangeEvent_('media-source');
  1967. // When changing text visibility we need to update both the text displayer
  1968. // and streaming engine because we don't always stream text. To ensure
  1969. // that the text displayer and streaming engine are always in sync, wait
  1970. // until they are both initialized before setting the initial value.
  1971. const textDisplayerFactory = this.config_.textDisplayFactory;
  1972. const textDisplayer = textDisplayerFactory();
  1973. if (textDisplayer.configure) {
  1974. textDisplayer.configure(this.config_.textDisplayer);
  1975. } else {
  1976. shaka.Deprecate.deprecateFeature(5,
  1977. 'Text displayer w/ configure',
  1978. 'Text displayer should have a "configure" method!');
  1979. }
  1980. this.lastTextFactory_ = textDisplayerFactory;
  1981. const mediaSourceEngine = this.createMediaSourceEngine(
  1982. this.video_,
  1983. textDisplayer,
  1984. {
  1985. getKeySystem: () => this.keySystem(),
  1986. onMetadata: (metadata, offset, endTime) => {
  1987. this.processTimedMetadataMediaSrc_(metadata, offset, endTime);
  1988. },
  1989. },
  1990. this.lcevcDec_);
  1991. mediaSourceEngine.configure(this.config_.mediaSource);
  1992. const {segmentRelativeVttTiming} = this.config_.manifest;
  1993. mediaSourceEngine.setSegmentRelativeVttTiming(segmentRelativeVttTiming);
  1994. // Wait for media source engine to finish opening. This promise should
  1995. // NEVER be rejected as per the media source engine implementation.
  1996. await mediaSourceEngine.open();
  1997. // Wait until it is ready to actually store the reference.
  1998. this.mediaSourceEngine_ = mediaSourceEngine;
  1999. }
  2000. /**
  2001. * Starts loading the content described by the parsed manifest.
  2002. *
  2003. * @param {number} startTimeOfLoad
  2004. * @param {?shaka.extern.Variant} prefetchedVariant
  2005. * @param {!Map.<number, shaka.media.SegmentPrefetch>} segmentPrefetchById
  2006. * @return {!Promise}
  2007. * @private
  2008. */
  2009. async loadInner_(startTimeOfLoad, prefetchedVariant, segmentPrefetchById) {
  2010. goog.asserts.assert(
  2011. this.video_, 'We should have a media element by now.');
  2012. goog.asserts.assert(
  2013. this.manifest_, 'The manifest should already be parsed.');
  2014. goog.asserts.assert(
  2015. this.assetUri_, 'We should have an asset uri by now.');
  2016. goog.asserts.assert(
  2017. this.abrManager_, 'We should have an abr manager by now.');
  2018. this.makeStateChangeEvent_('load');
  2019. const mediaElement = this.video_;
  2020. this.playRateController_ = new shaka.media.PlayRateController({
  2021. getRate: () => mediaElement.playbackRate,
  2022. getDefaultRate: () => mediaElement.defaultPlaybackRate,
  2023. setRate: (rate) => { mediaElement.playbackRate = rate; },
  2024. movePlayhead: (delta) => { mediaElement.currentTime += delta; },
  2025. });
  2026. const updateStateHistory = () => this.updateStateHistory_();
  2027. const onRateChange = () => this.onRateChange_();
  2028. this.loadEventManager_.listen(
  2029. mediaElement, 'playing', updateStateHistory);
  2030. this.loadEventManager_.listen(mediaElement, 'pause', updateStateHistory);
  2031. this.loadEventManager_.listen(mediaElement, 'ended', updateStateHistory);
  2032. this.loadEventManager_.listen(mediaElement, 'ratechange', onRateChange);
  2033. // Check the status of the LCEVC Dec Object. Reset, create, or close
  2034. // depending on the config.
  2035. this.setupLcevc_(this.config_);
  2036. this.currentTextLanguage_ = this.config_.preferredTextLanguage;
  2037. this.currentTextRole_ = this.config_.preferredTextRole;
  2038. this.currentTextForced_ = this.config_.preferForcedSubs;
  2039. shaka.Player.applyPlayRange_(this.manifest_.presentationTimeline,
  2040. this.config_.playRangeStart,
  2041. this.config_.playRangeEnd);
  2042. this.abrManager_.init((variant, clearBuffer, safeMargin) => {
  2043. return this.switch_(variant, clearBuffer, safeMargin);
  2044. });
  2045. this.abrManager_.setMediaElement(mediaElement);
  2046. this.abrManager_.setCmsdManager(this.cmsdManager_);
  2047. this.streamingEngine_ = this.createStreamingEngine();
  2048. this.streamingEngine_.configure(this.config_.streaming);
  2049. // Set the load mode to "loaded with media source" as late as possible so
  2050. // that public methods won't try to access internal components until
  2051. // they're all initialized. We MUST switch to loaded before calling
  2052. // "streaming" so that they can access internal information.
  2053. this.loadMode_ = shaka.Player.LoadMode.MEDIA_SOURCE;
  2054. if (mediaElement.textTracks) {
  2055. this.loadEventManager_.listen(
  2056. mediaElement.textTracks, 'addtrack', (e) => {
  2057. const trackEvent = /** @type {!TrackEvent} */(e);
  2058. if (trackEvent.track) {
  2059. const track = trackEvent.track;
  2060. goog.asserts.assert(
  2061. track instanceof TextTrack, 'Wrong track type!');
  2062. switch (track.kind) {
  2063. case 'chapters':
  2064. this.activateChaptersTrack_(track);
  2065. break;
  2066. }
  2067. }
  2068. });
  2069. }
  2070. // The event must be fired after we filter by restrictions but before the
  2071. // active stream is picked to allow those listening for the "streaming"
  2072. // event to make changes before streaming starts.
  2073. this.dispatchEvent(shaka.Player.makeEvent_(
  2074. shaka.util.FakeEvent.EventName.Streaming));
  2075. // Pick the initial streams to play.
  2076. // Unless the user has already picked a variant, anyway, by calling
  2077. // selectVariantTrack before this loading stage.
  2078. let initialVariant = prefetchedVariant;
  2079. const activeVariant = this.streamingEngine_.getCurrentVariant();
  2080. if (!activeVariant && !initialVariant) {
  2081. initialVariant = this.chooseVariant_(/* initialSelection= */ true);
  2082. goog.asserts.assert(initialVariant, 'Must choose an initial variant!');
  2083. }
  2084. // Lazy-load the stream, so we will have enough info to make the playhead.
  2085. const createSegmentIndexPromises = [];
  2086. const toLazyLoad = activeVariant || initialVariant;
  2087. for (const stream of [toLazyLoad.video, toLazyLoad.audio]) {
  2088. if (stream && !stream.segmentIndex) {
  2089. createSegmentIndexPromises.push(stream.createSegmentIndex());
  2090. }
  2091. }
  2092. if (createSegmentIndexPromises.length > 0) {
  2093. await Promise.all(createSegmentIndexPromises);
  2094. }
  2095. if (this.parser_ && this.parser_.onInitialVariantChosen) {
  2096. this.parser_.onInitialVariantChosen(toLazyLoad);
  2097. }
  2098. shaka.Player.applyPlayRange_(this.manifest_.presentationTimeline,
  2099. this.config_.playRangeStart,
  2100. this.config_.playRangeEnd);
  2101. const setupPlayhead = (startTime) => {
  2102. this.playhead_ = this.createPlayhead(startTime);
  2103. this.playheadObservers_ =
  2104. this.createPlayheadObserversForMSE_(startTime);
  2105. // We need to start the buffer management code near the end because it
  2106. // will set the initial buffering state and that depends on other
  2107. // components being initialized.
  2108. const rebufferThreshold = Math.max(
  2109. this.manifest_.minBufferTime,
  2110. this.config_.streaming.rebufferingGoal);
  2111. this.startBufferManagement_(mediaElement, rebufferThreshold);
  2112. };
  2113. if (!this.config_.streaming.startAtSegmentBoundary) {
  2114. setupPlayhead(this.startTime_);
  2115. }
  2116. // Now we can switch to the initial variant.
  2117. if (!activeVariant) {
  2118. goog.asserts.assert(initialVariant,
  2119. 'Must have choosen an initial variant!');
  2120. // Now that we have initial streams, we may adjust the start time to
  2121. // align to a segment boundary.
  2122. if (this.config_.streaming.startAtSegmentBoundary) {
  2123. const timeline = this.manifest_.presentationTimeline;
  2124. let initialTime = this.startTime_ || this.video_.currentTime;
  2125. const seekRangeStart = timeline.getSeekRangeStart();
  2126. const seekRangeEnd = timeline.getSeekRangeEnd();
  2127. if (initialTime < seekRangeStart) {
  2128. initialTime = seekRangeStart;
  2129. } else if (initialTime > seekRangeEnd) {
  2130. initialTime = seekRangeEnd;
  2131. }
  2132. const startTime = await this.adjustStartTime_(
  2133. initialVariant, initialTime);
  2134. setupPlayhead(startTime);
  2135. }
  2136. this.switchVariant_(initialVariant, /* fromAdaptation= */ true,
  2137. /* clearBuffer= */ false, /* safeMargin= */ 0);
  2138. }
  2139. this.playhead_.ready();
  2140. // Decide if text should be shown automatically.
  2141. // similar to video/audio track, we would skip switch initial text track
  2142. // if user already pick text track (via selectTextTrack api)
  2143. const activeTextTrack = this.getTextTracks().find((t) => t.active);
  2144. if (!activeTextTrack) {
  2145. const initialTextStream = this.chooseTextStream_();
  2146. if (initialTextStream) {
  2147. this.addTextStreamToSwitchHistory_(
  2148. initialTextStream, /* fromAdaptation= */ true);
  2149. }
  2150. if (initialVariant) {
  2151. this.setInitialTextState_(initialVariant, initialTextStream);
  2152. }
  2153. // Don't initialize with a text stream unless we should be streaming
  2154. // text.
  2155. if (initialTextStream && this.shouldStreamText_()) {
  2156. this.streamingEngine_.switchTextStream(initialTextStream);
  2157. }
  2158. }
  2159. // Start streaming content. This will start the flow of content down to
  2160. // media source.
  2161. await this.streamingEngine_.start(segmentPrefetchById);
  2162. if (this.config_.abr.enabled) {
  2163. this.abrManager_.enable();
  2164. this.onAbrStatusChanged_();
  2165. }
  2166. // Dispatch a 'trackschanged' event now that all initial filtering is
  2167. // done.
  2168. this.onTracksChanged_();
  2169. // Now that we've filtered out variants that aren't compatible with the
  2170. // active one, update abr manager with filtered variants.
  2171. // NOTE: This may be unnecessary. We've already chosen one codec in
  2172. // chooseCodecsAndFilterManifest_ before we started streaming. But it
  2173. // doesn't hurt, and this will all change when we start using
  2174. // MediaCapabilities and codec switching.
  2175. // TODO(#1391): Re-evaluate with MediaCapabilities and codec switching.
  2176. this.updateAbrManagerVariants_();
  2177. const hasPrimary = this.manifest_.variants.some((v) => v.primary);
  2178. if (!this.config_.preferredAudioLanguage && !hasPrimary) {
  2179. shaka.log.warning('No preferred audio language set. ' +
  2180. 'We have chosen an arbitrary language initially');
  2181. }
  2182. const isLive = this.isLive();
  2183. if ((isLive && (this.config_.streaming.liveSync ||
  2184. this.manifest_.serviceDescription ||
  2185. this.config_.streaming.liveSyncPanicMode)) ||
  2186. this.config_.streaming.vodDynamicPlaybackRate) {
  2187. const onTimeUpdate = () => this.onTimeUpdate_();
  2188. this.loadEventManager_.listen(mediaElement, 'timeupdate', onTimeUpdate);
  2189. }
  2190. if (!isLive) {
  2191. const onVideoProgress = () => this.onVideoProgress_();
  2192. this.loadEventManager_.listen(
  2193. mediaElement, 'timeupdate', onVideoProgress);
  2194. this.onVideoProgress_();
  2195. if (this.manifest_.nextUrl) {
  2196. if (this.config_.streaming.preloadNextUrlWindow > 0) {
  2197. const onTimeUpdate = async () => {
  2198. const timeToEnd = this.video_.duration - this.video_.currentTime;
  2199. if (!isNaN(timeToEnd)) {
  2200. if (timeToEnd <= this.config_.streaming.preloadNextUrlWindow) {
  2201. this.loadEventManager_.unlisten(
  2202. mediaElement, 'timeupdate', onTimeUpdate);
  2203. goog.asserts.assert(this.manifest_.nextUrl,
  2204. 'this.manifest_.nextUrl should be valid.');
  2205. this.preloadNextUrl_ =
  2206. await this.preload(this.manifest_.nextUrl);
  2207. }
  2208. }
  2209. };
  2210. this.loadEventManager_.listen(
  2211. mediaElement, 'timeupdate', onTimeUpdate);
  2212. }
  2213. this.loadEventManager_.listen(mediaElement, 'ended', () => {
  2214. this.load(this.preloadNextUrl_ || this.manifest_.nextUrl);
  2215. });
  2216. }
  2217. }
  2218. if (this.adManager_) {
  2219. this.adManager_.onManifestUpdated(isLive);
  2220. }
  2221. this.fullyLoaded_ = true;
  2222. // Wait for the 'loadedmetadata' event to measure load() latency.
  2223. this.loadEventManager_.listenOnce(mediaElement, 'loadedmetadata', () => {
  2224. const now = Date.now() / 1000;
  2225. const delta = now - startTimeOfLoad;
  2226. this.stats_.setLoadLatency(delta);
  2227. });
  2228. }
  2229. /**
  2230. * Initializes the DRM engine for use by src equals.
  2231. *
  2232. * @param {string} mimeType
  2233. * @return {!Promise}
  2234. * @private
  2235. */
  2236. async initializeSrcEqualsDrmInner_(mimeType) {
  2237. const ContentType = shaka.util.ManifestParserUtils.ContentType;
  2238. goog.asserts.assert(
  2239. this.networkingEngine_,
  2240. '|onInitializeSrcEqualsDrm_| should never be called after |destroy|');
  2241. goog.asserts.assert(
  2242. this.config_,
  2243. '|onInitializeSrcEqualsDrm_| should never be called after |destroy|');
  2244. const startTime = Date.now() / 1000;
  2245. let firstEvent = true;
  2246. this.drmEngine_ = this.createDrmEngine({
  2247. netEngine: this.networkingEngine_,
  2248. onError: (e) => {
  2249. this.onError_(e);
  2250. },
  2251. onKeyStatus: (map) => {
  2252. // According to this.onKeyStatus_, we can't even use this information
  2253. // in src= mode, so this is just a no-op.
  2254. },
  2255. onExpirationUpdated: (id, expiration) => {
  2256. const event = shaka.Player.makeEvent_(
  2257. shaka.util.FakeEvent.EventName.ExpirationUpdated);
  2258. this.dispatchEvent(event);
  2259. },
  2260. onEvent: (e) => {
  2261. this.dispatchEvent(e);
  2262. if (e.type == shaka.util.FakeEvent.EventName.DrmSessionUpdate &&
  2263. firstEvent) {
  2264. firstEvent = false;
  2265. const now = Date.now() / 1000;
  2266. const delta = now - startTime;
  2267. this.stats_.setDrmTime(delta);
  2268. }
  2269. },
  2270. });
  2271. this.drmEngine_.configure(this.config_.drm);
  2272. // TODO: Instead of feeding DrmEngine with Variants, we should refactor
  2273. // DrmEngine so that it takes a minimal config derived from Variants. In
  2274. // cases like this one or in removal of stored content, the details are
  2275. // largely unimportant. We should have a saner way to initialize
  2276. // DrmEngine.
  2277. // That would also insulate DrmEngine from manifest changes in the future.
  2278. // For now, that is time-consuming and this synthetic Variant is easy, so
  2279. // I'm putting it off. Since this is only expected to be used for native
  2280. // HLS in Safari, this should be safe. -JCP
  2281. /** @type {shaka.extern.Variant} */
  2282. const variant = {
  2283. id: 0,
  2284. language: 'und',
  2285. disabledUntilTime: 0,
  2286. primary: false,
  2287. audio: null,
  2288. video: null,
  2289. bandwidth: 100,
  2290. allowedByApplication: true,
  2291. allowedByKeySystem: true,
  2292. decodingInfos: [],
  2293. };
  2294. const stream = {
  2295. id: 0,
  2296. originalId: null,
  2297. groupId: null,
  2298. createSegmentIndex: () => Promise.resolve(),
  2299. segmentIndex: null,
  2300. mimeType: mimeType ? shaka.util.MimeUtils.getBasicType(mimeType) : '',
  2301. codecs: mimeType ? shaka.util.MimeUtils.getCodecs(mimeType) : '',
  2302. encrypted: true,
  2303. drmInfos: [], // Filled in by DrmEngine config.
  2304. keyIds: new Set(),
  2305. language: 'und',
  2306. originalLanguage: null,
  2307. label: null,
  2308. type: ContentType.VIDEO,
  2309. primary: false,
  2310. trickModeVideo: null,
  2311. emsgSchemeIdUris: null,
  2312. roles: [],
  2313. forced: false,
  2314. channelsCount: null,
  2315. audioSamplingRate: null,
  2316. spatialAudio: false,
  2317. closedCaptions: null,
  2318. accessibilityPurpose: null,
  2319. external: false,
  2320. fastSwitching: false,
  2321. fullMimeTypes: new Set(),
  2322. };
  2323. stream.fullMimeTypes.add(shaka.util.MimeUtils.getFullType(
  2324. stream.mimeType, stream.codecs));
  2325. if (mimeType.startsWith('audio/')) {
  2326. stream.type = ContentType.AUDIO;
  2327. variant.audio = stream;
  2328. } else {
  2329. variant.video = stream;
  2330. }
  2331. this.drmEngine_.setSrcEquals(/* srcEquals= */ true);
  2332. await this.drmEngine_.initForPlayback(
  2333. [variant], /* offlineSessionIds= */ []);
  2334. await this.drmEngine_.attach(this.video_);
  2335. }
  2336. /**
  2337. * Passes the asset URI along to the media element, so it can be played src
  2338. * equals style.
  2339. *
  2340. * @param {number} startTimeOfLoad
  2341. * @param {string} mimeType
  2342. * @return {!Promise}
  2343. *
  2344. * @private
  2345. */
  2346. async srcEqualsInner_(startTimeOfLoad, mimeType) {
  2347. this.makeStateChangeEvent_('src-equals');
  2348. goog.asserts.assert(
  2349. this.video_, 'We should have a media element when loading.');
  2350. goog.asserts.assert(
  2351. this.assetUri_, 'We should have a valid uri when loading.');
  2352. const mediaElement = this.video_;
  2353. this.playhead_ = new shaka.media.SrcEqualsPlayhead(mediaElement);
  2354. // This flag is used below in the language preference setup to check if
  2355. // this load was canceled before the necessary awaits completed.
  2356. let unloaded = false;
  2357. this.cleanupOnUnload_.push(() => {
  2358. unloaded = true;
  2359. });
  2360. if (this.startTime_ != null) {
  2361. this.playhead_.setStartTime(this.startTime_);
  2362. }
  2363. this.playRateController_ = new shaka.media.PlayRateController({
  2364. getRate: () => mediaElement.playbackRate,
  2365. getDefaultRate: () => mediaElement.defaultPlaybackRate,
  2366. setRate: (rate) => { mediaElement.playbackRate = rate; },
  2367. movePlayhead: (delta) => { mediaElement.currentTime += delta; },
  2368. });
  2369. // We need to start the buffer management code near the end because it
  2370. // will set the initial buffering state and that depends on other
  2371. // components being initialized.
  2372. const rebufferThreshold = this.config_.streaming.rebufferingGoal;
  2373. this.startBufferManagement_(mediaElement, rebufferThreshold);
  2374. // Add all media element listeners.
  2375. const updateStateHistory = () => this.updateStateHistory_();
  2376. const onRateChange = () => this.onRateChange_();
  2377. this.loadEventManager_.listen(
  2378. mediaElement, 'playing', updateStateHistory);
  2379. this.loadEventManager_.listen(mediaElement, 'pause', updateStateHistory);
  2380. this.loadEventManager_.listen(mediaElement, 'ended', updateStateHistory);
  2381. this.loadEventManager_.listen(mediaElement, 'ratechange', onRateChange);
  2382. // Wait for the 'loadedmetadata' event to measure load() latency, but only
  2383. // if preload is set in a way that would result in this event firing
  2384. // automatically.
  2385. // See https://github.com/shaka-project/shaka-player/issues/2483
  2386. if (mediaElement.preload != 'none') {
  2387. this.loadEventManager_.listenOnce(
  2388. mediaElement, 'loadedmetadata', () => {
  2389. const now = Date.now() / 1000;
  2390. const delta = now - startTimeOfLoad;
  2391. this.stats_.setLoadLatency(delta);
  2392. });
  2393. }
  2394. // The audio tracks are only available on Safari at the moment, but this
  2395. // drives the tracks API for Safari's native HLS. So when they change,
  2396. // fire the corresponding Shaka Player event.
  2397. if (mediaElement.audioTracks) {
  2398. this.loadEventManager_.listen(mediaElement.audioTracks, 'addtrack',
  2399. () => this.onTracksChanged_());
  2400. this.loadEventManager_.listen(mediaElement.audioTracks, 'removetrack',
  2401. () => this.onTracksChanged_());
  2402. this.loadEventManager_.listen(mediaElement.audioTracks, 'change',
  2403. () => this.onTracksChanged_());
  2404. }
  2405. if (mediaElement.textTracks) {
  2406. this.loadEventManager_.listen(
  2407. mediaElement.textTracks, 'addtrack', (e) => {
  2408. const trackEvent = /** @type {!TrackEvent} */(e);
  2409. if (trackEvent.track) {
  2410. const track = trackEvent.track;
  2411. goog.asserts.assert(
  2412. track instanceof TextTrack, 'Wrong track type!');
  2413. switch (track.kind) {
  2414. case 'metadata':
  2415. this.processTimedMetadataSrcEqls_(track);
  2416. break;
  2417. case 'chapters':
  2418. this.activateChaptersTrack_(track);
  2419. break;
  2420. default:
  2421. this.onTracksChanged_();
  2422. break;
  2423. }
  2424. }
  2425. });
  2426. this.loadEventManager_.listen(
  2427. mediaElement.textTracks, 'removetrack',
  2428. () => this.onTracksChanged_());
  2429. this.loadEventManager_.listen(
  2430. mediaElement.textTracks, 'change',
  2431. () => this.onTracksChanged_());
  2432. }
  2433. // By setting |src| we are done "loading" with src=. We don't need to set
  2434. // the current time because |playhead| will do that for us.
  2435. mediaElement.src = this.cmcdManager_.appendSrcData(
  2436. this.assetUri_, mimeType);
  2437. // Tizen 3 / WebOS won't load anything unless you call load() explicitly,
  2438. // no matter the value of the preload attribute. This is harmful on some
  2439. // other platforms by triggering unbounded loading of media data, but is
  2440. // necessary here.
  2441. if (shaka.util.Platform.isTizen() || shaka.util.Platform.isWebOS()) {
  2442. mediaElement.load();
  2443. }
  2444. // In Safari using HLS won't load anything unless you call load()
  2445. // explicitly, no matter the value of the preload attribute.
  2446. // Note: this only happens when there are not autoplay.
  2447. if (mediaElement.preload != 'none' && !mediaElement.autoplay &&
  2448. shaka.util.MimeUtils.isHlsType(mimeType) &&
  2449. shaka.util.Platform.safariVersion()) {
  2450. mediaElement.load();
  2451. }
  2452. // Set the load mode last so that we know that all our components are
  2453. // initialized.
  2454. this.loadMode_ = shaka.Player.LoadMode.SRC_EQUALS;
  2455. // The event doesn't mean as much for src= playback, since we don't
  2456. // control streaming. But we should fire it in this path anyway since
  2457. // some applications may be expecting it as a life-cycle event.
  2458. this.dispatchEvent(shaka.Player.makeEvent_(
  2459. shaka.util.FakeEvent.EventName.Streaming));
  2460. // The "load" Promise is resolved when we have loaded the metadata. If we
  2461. // wait for the full data, that won't happen on Safari until the play
  2462. // button is hit.
  2463. const fullyLoaded = new shaka.util.PublicPromise();
  2464. shaka.util.MediaReadyState.waitForReadyState(mediaElement,
  2465. HTMLMediaElement.HAVE_METADATA,
  2466. this.loadEventManager_,
  2467. () => {
  2468. this.playhead_.ready();
  2469. fullyLoaded.resolve();
  2470. });
  2471. // We can't switch to preferred languages, though, until the data is
  2472. // loaded.
  2473. shaka.util.MediaReadyState.waitForReadyState(mediaElement,
  2474. HTMLMediaElement.HAVE_CURRENT_DATA,
  2475. this.loadEventManager_,
  2476. async () => {
  2477. this.setupPreferredAudioOnSrc_();
  2478. // Applying the text preference too soon can result in it being
  2479. // reverted. Wait for native HLS to pick something first.
  2480. const textTracks = this.getFilteredTextTracks_();
  2481. if (!textTracks.find((t) => t.mode != 'disabled')) {
  2482. await new Promise((resolve) => {
  2483. this.loadEventManager_.listenOnce(
  2484. mediaElement.textTracks, 'change', resolve);
  2485. // We expect the event to fire because it does on Safari.
  2486. // But in case it doesn't on some other platform or future
  2487. // version, move on in 1 second no matter what. This keeps the
  2488. // language settings from being completely ignored if something
  2489. // goes wrong.
  2490. new shaka.util.Timer(resolve).tickAfter(1);
  2491. });
  2492. } else if (textTracks.length > 0) {
  2493. this.isTextVisible_ = true;
  2494. }
  2495. // If we have moved on to another piece of content while waiting for
  2496. // the above event/timer, we should not change tracks here.
  2497. if (unloaded) {
  2498. return;
  2499. }
  2500. this.setupPreferredTextOnSrc_();
  2501. });
  2502. if (mediaElement.error) {
  2503. // Already failed!
  2504. fullyLoaded.reject(this.videoErrorToShakaError_());
  2505. } else if (mediaElement.preload == 'none') {
  2506. shaka.log.alwaysWarn(
  2507. 'With <video preload="none">, the browser will not load anything ' +
  2508. 'until play() is called. We are unable to measure load latency ' +
  2509. 'in a meaningful way, and we cannot provide track info yet. ' +
  2510. 'Please do not use preload="none" with Shaka Player.');
  2511. // We can't wait for an event load loadedmetadata, since that will be
  2512. // blocked until a user interaction. So resolve the Promise now.
  2513. fullyLoaded.resolve();
  2514. }
  2515. this.loadEventManager_.listenOnce(mediaElement, 'error', () => {
  2516. fullyLoaded.reject(this.videoErrorToShakaError_());
  2517. });
  2518. const timeout = new Promise((resolve, reject) => {
  2519. const timer = new shaka.util.Timer(reject);
  2520. timer.tickAfter(this.config_.streaming.loadTimeout);
  2521. });
  2522. await Promise.race([
  2523. fullyLoaded,
  2524. timeout,
  2525. ]);
  2526. const isLive = this.isLive();
  2527. if ((isLive && (this.config_.streaming.liveSync ||
  2528. this.config_.streaming.liveSyncPanicMode)) ||
  2529. this.config_.streaming.vodDynamicPlaybackRate) {
  2530. const onTimeUpdate = () => this.onTimeUpdate_();
  2531. this.loadEventManager_.listen(mediaElement, 'timeupdate', onTimeUpdate);
  2532. }
  2533. if (!isLive) {
  2534. const onVideoProgress = () => this.onVideoProgress_();
  2535. this.loadEventManager_.listen(
  2536. mediaElement, 'timeupdate', onVideoProgress);
  2537. this.onVideoProgress_();
  2538. }
  2539. if (this.adManager_) {
  2540. this.adManager_.onManifestUpdated(isLive);
  2541. // There is no good way to detect when the manifest has been updated,
  2542. // so we use seekRange().end so we can tell when it has been updated.
  2543. if (isLive) {
  2544. let prevSeekRangeEnd = this.seekRange().end;
  2545. this.loadEventManager_.listen(mediaElement, 'progress', () => {
  2546. const newSeekRangeEnd = this.seekRange().end;
  2547. if (prevSeekRangeEnd != newSeekRangeEnd) {
  2548. this.adManager_.onManifestUpdated(this.isLive());
  2549. prevSeekRangeEnd = newSeekRangeEnd;
  2550. }
  2551. });
  2552. }
  2553. }
  2554. this.fullyLoaded_ = true;
  2555. }
  2556. /**
  2557. * This method setup the preferred audio using src=..
  2558. *
  2559. * @private
  2560. */
  2561. setupPreferredAudioOnSrc_() {
  2562. const preferredAudioLanguage = this.config_.preferredAudioLanguage;
  2563. // If the user has not selected a preference, the browser preference is
  2564. // left.
  2565. if (preferredAudioLanguage == '') {
  2566. return;
  2567. }
  2568. const preferredVariantRole = this.config_.preferredVariantRole;
  2569. this.selectAudioLanguage(preferredAudioLanguage, preferredVariantRole);
  2570. }
  2571. /**
  2572. * This method setup the preferred text using src=.
  2573. *
  2574. * @private
  2575. */
  2576. setupPreferredTextOnSrc_() {
  2577. const preferredTextLanguage = this.config_.preferredTextLanguage;
  2578. // If the user has not selected a preference, the browser preference is
  2579. // left.
  2580. if (preferredTextLanguage == '') {
  2581. return;
  2582. }
  2583. const preferForcedSubs = this.config_.preferForcedSubs;
  2584. const preferredTextRole = this.config_.preferredTextRole;
  2585. this.selectTextLanguage(preferredTextLanguage, preferredTextRole,
  2586. preferForcedSubs);
  2587. }
  2588. /**
  2589. * We're looking for metadata tracks to process id3 tags. One of the uses is
  2590. * for ad info on LIVE streams
  2591. *
  2592. * @param {!TextTrack} track
  2593. * @private
  2594. */
  2595. processTimedMetadataSrcEqls_(track) {
  2596. if (track.kind != 'metadata') {
  2597. return;
  2598. }
  2599. // Hidden mode is required for the cuechange event to launch correctly
  2600. track.mode = 'hidden';
  2601. this.loadEventManager_.listen(track, 'cuechange', () => {
  2602. if (!track.activeCues) {
  2603. return;
  2604. }
  2605. for (const cue of track.activeCues) {
  2606. this.dispatchMetadataEvent_(cue.startTime, cue.endTime,
  2607. cue.type, cue.value);
  2608. if (this.adManager_) {
  2609. this.adManager_.onCueMetadataChange(cue.value);
  2610. }
  2611. }
  2612. });
  2613. // In Safari the initial assignment does not always work, so we schedule
  2614. // this process to be repeated several times to ensure that it has been put
  2615. // in the correct mode.
  2616. const timer = new shaka.util.Timer(() => {
  2617. const textTracks = this.getMetadataTracks_();
  2618. for (const textTrack of textTracks) {
  2619. textTrack.mode = 'hidden';
  2620. }
  2621. }).tickNow().tickAfter(0.5);
  2622. this.cleanupOnUnload_.push(() => {
  2623. timer.stop();
  2624. });
  2625. }
  2626. /**
  2627. * @param {!Array.<shaka.extern.ID3Metadata>} metadata
  2628. * @param {number} offset
  2629. * @param {?number} segmentEndTime
  2630. * @private
  2631. */
  2632. processTimedMetadataMediaSrc_(metadata, offset, segmentEndTime) {
  2633. for (const sample of metadata) {
  2634. if (sample.data && sample.cueTime && sample.frames) {
  2635. const start = sample.cueTime + offset;
  2636. let end = segmentEndTime;
  2637. // This can happen when the ID3 info arrives in a previous segment.
  2638. if (end && start > end) {
  2639. end = start;
  2640. }
  2641. const metadataType = 'org.id3';
  2642. for (const frame of sample.frames) {
  2643. const payload = frame;
  2644. this.dispatchMetadataEvent_(start, end, metadataType, payload);
  2645. }
  2646. if (this.adManager_) {
  2647. this.adManager_.onHlsTimedMetadata(sample, start);
  2648. }
  2649. }
  2650. }
  2651. }
  2652. /**
  2653. * Construct and fire a Player.Metadata event
  2654. *
  2655. * @param {number} startTime
  2656. * @param {?number} endTime
  2657. * @param {string} metadataType
  2658. * @param {shaka.extern.MetadataFrame} payload
  2659. * @private
  2660. */
  2661. dispatchMetadataEvent_(startTime, endTime, metadataType, payload) {
  2662. goog.asserts.assert(!endTime || startTime <= endTime,
  2663. 'Metadata start time should be less or equal to the end time!');
  2664. const eventName = shaka.util.FakeEvent.EventName.Metadata;
  2665. const data = new Map()
  2666. .set('startTime', startTime)
  2667. .set('endTime', endTime)
  2668. .set('metadataType', metadataType)
  2669. .set('payload', payload);
  2670. this.dispatchEvent(shaka.Player.makeEvent_(eventName, data));
  2671. }
  2672. /**
  2673. * Set the mode on a chapters track so that it loads.
  2674. *
  2675. * @param {?TextTrack} track
  2676. * @private
  2677. */
  2678. activateChaptersTrack_(track) {
  2679. if (!track || track.kind != 'chapters') {
  2680. return;
  2681. }
  2682. // Hidden mode is required for the cuechange event to launch correctly and
  2683. // get the cues and the activeCues
  2684. track.mode = 'hidden';
  2685. // In Safari the initial assignment does not always work, so we schedule
  2686. // this process to be repeated several times to ensure that it has been put
  2687. // in the correct mode.
  2688. const timer = new shaka.util.Timer(() => {
  2689. track.mode = 'hidden';
  2690. }).tickNow().tickAfter(0.5);
  2691. this.cleanupOnUnload_.push(() => {
  2692. timer.stop();
  2693. });
  2694. }
  2695. /**
  2696. * Releases all of the mutexes of the player. Meant for use by the tests.
  2697. * @export
  2698. */
  2699. releaseAllMutexes() {
  2700. this.mutex_.releaseAll();
  2701. }
  2702. /**
  2703. * Create a new DrmEngine instance. This may be replaced by tests to create
  2704. * fake instances. Configuration and initialization will be handled after
  2705. * |createDrmEngine|.
  2706. *
  2707. * @param {shaka.media.DrmEngine.PlayerInterface} playerInterface
  2708. * @return {!shaka.media.DrmEngine}
  2709. */
  2710. createDrmEngine(playerInterface) {
  2711. return new shaka.media.DrmEngine(playerInterface);
  2712. }
  2713. /**
  2714. * Creates a new instance of NetworkingEngine. This can be replaced by tests
  2715. * to create fake instances instead.
  2716. *
  2717. * @param {(function():?shaka.media.PreloadManager)=} getPreloadManager
  2718. * @return {!shaka.net.NetworkingEngine}
  2719. */
  2720. createNetworkingEngine(getPreloadManager) {
  2721. if (!getPreloadManager) {
  2722. getPreloadManager = () => null;
  2723. }
  2724. const getAbrManager = () => {
  2725. if (getPreloadManager()) {
  2726. return getPreloadManager().getAbrManager();
  2727. } else {
  2728. return this.abrManager_;
  2729. }
  2730. };
  2731. const getParser = () => {
  2732. if (getPreloadManager()) {
  2733. return getPreloadManager().getParser();
  2734. } else {
  2735. return this.parser_;
  2736. }
  2737. };
  2738. const lateQueue = (fn) => {
  2739. if (getPreloadManager()) {
  2740. getPreloadManager().addQueuedOperation(true, fn);
  2741. } else {
  2742. fn();
  2743. }
  2744. };
  2745. const dispatchEvent = (event) => {
  2746. if (getPreloadManager()) {
  2747. getPreloadManager().dispatchEvent(event);
  2748. } else {
  2749. this.dispatchEvent(event);
  2750. }
  2751. };
  2752. const getStats = () => {
  2753. if (getPreloadManager()) {
  2754. return getPreloadManager().getStats();
  2755. } else {
  2756. return this.stats_;
  2757. }
  2758. };
  2759. /** @type {shaka.net.NetworkingEngine.onProgressUpdated} */
  2760. const onProgressUpdated_ = (deltaTimeMs,
  2761. bytesDownloaded, allowSwitch, request) => {
  2762. // In some situations, such as during offline storage, the abr manager
  2763. // might not yet exist. Therefore, we need to check if abr manager has
  2764. // been initialized before using it.
  2765. const abrManager = getAbrManager();
  2766. if (abrManager) {
  2767. abrManager.segmentDownloaded(deltaTimeMs, bytesDownloaded,
  2768. allowSwitch, request);
  2769. }
  2770. };
  2771. /** @type {shaka.net.NetworkingEngine.OnHeadersReceived} */
  2772. const onHeadersReceived_ = (headers, request, requestType) => {
  2773. // Release a 'downloadheadersreceived' event.
  2774. const name = shaka.util.FakeEvent.EventName.DownloadHeadersReceived;
  2775. const data = new Map()
  2776. .set('headers', headers)
  2777. .set('request', request)
  2778. .set('requestType', requestType);
  2779. dispatchEvent(shaka.Player.makeEvent_(name, data));
  2780. lateQueue(() => {
  2781. if (this.cmsdManager_) {
  2782. this.cmsdManager_.processHeaders(headers);
  2783. }
  2784. });
  2785. };
  2786. /** @type {shaka.net.NetworkingEngine.OnDownloadFailed} */
  2787. const onDownloadFailed_ = (request, error, httpResponseCode, aborted) => {
  2788. // Release a 'downloadfailed' event.
  2789. const name = shaka.util.FakeEvent.EventName.DownloadFailed;
  2790. const data = new Map()
  2791. .set('request', request)
  2792. .set('error', error)
  2793. .set('httpResponseCode', httpResponseCode)
  2794. .set('aborted', aborted);
  2795. dispatchEvent(shaka.Player.makeEvent_(name, data));
  2796. };
  2797. /** @type {shaka.net.NetworkingEngine.OnRequest} */
  2798. const onRequest_ = (type, request, context) => {
  2799. lateQueue(() => {
  2800. this.cmcdManager_.applyData(type, request, context);
  2801. });
  2802. };
  2803. /** @type {shaka.net.NetworkingEngine.OnRetry} */
  2804. const onRetry_ = (type, context, newUrl, oldUrl) => {
  2805. const parser = getParser();
  2806. if (parser && parser.banLocation) {
  2807. parser.banLocation(oldUrl);
  2808. }
  2809. };
  2810. /** @type {shaka.net.NetworkingEngine.OnResponse} */
  2811. const onResponse_ = (type, response, context) => {
  2812. if (response.data) {
  2813. const bytesDownloaded = response.data.byteLength;
  2814. const stats = getStats();
  2815. if (stats) {
  2816. stats.addBytesDownloaded(bytesDownloaded);
  2817. }
  2818. }
  2819. };
  2820. return new shaka.net.NetworkingEngine(
  2821. onProgressUpdated_, onHeadersReceived_, onDownloadFailed_, onRequest_,
  2822. onRetry_, onResponse_);
  2823. }
  2824. /**
  2825. * Creates a new instance of Playhead. This can be replaced by tests to
  2826. * create fake instances instead.
  2827. *
  2828. * @param {?number} startTime
  2829. * @return {!shaka.media.Playhead}
  2830. */
  2831. createPlayhead(startTime) {
  2832. goog.asserts.assert(this.manifest_, 'Must have manifest');
  2833. goog.asserts.assert(this.video_, 'Must have video');
  2834. return new shaka.media.MediaSourcePlayhead(
  2835. this.video_,
  2836. this.manifest_,
  2837. this.config_.streaming,
  2838. startTime,
  2839. () => this.onSeek_(),
  2840. (event) => this.dispatchEvent(event));
  2841. }
  2842. /**
  2843. * Create the observers for MSE playback. These observers are responsible for
  2844. * notifying the app and player of specific events during MSE playback.
  2845. *
  2846. * @param {number} startTime
  2847. * @return {!shaka.media.PlayheadObserverManager}
  2848. * @private
  2849. */
  2850. createPlayheadObserversForMSE_(startTime) {
  2851. goog.asserts.assert(this.manifest_, 'Must have manifest');
  2852. goog.asserts.assert(this.regionTimeline_, 'Must have region timeline');
  2853. goog.asserts.assert(this.video_, 'Must have video element');
  2854. const startsPastZero = this.isLive() || startTime > 0;
  2855. // Create the region observer. This will allow us to notify the app when we
  2856. // move in and out of timeline regions.
  2857. const regionObserver = new shaka.media.RegionObserver(
  2858. this.regionTimeline_, startsPastZero);
  2859. regionObserver.addEventListener('enter', (event) => {
  2860. /** @type {shaka.extern.TimelineRegionInfo} */
  2861. const region = event['region'];
  2862. this.onRegionEvent_(
  2863. shaka.util.FakeEvent.EventName.TimelineRegionEnter, region);
  2864. });
  2865. regionObserver.addEventListener('exit', (event) => {
  2866. /** @type {shaka.extern.TimelineRegionInfo} */
  2867. const region = event['region'];
  2868. this.onRegionEvent_(
  2869. shaka.util.FakeEvent.EventName.TimelineRegionExit, region);
  2870. });
  2871. regionObserver.addEventListener('skip', (event) => {
  2872. /** @type {shaka.extern.TimelineRegionInfo} */
  2873. const region = event['region'];
  2874. /** @type {boolean} */
  2875. const seeking = event['seeking'];
  2876. // If we are seeking, we don't want to surface the enter/exit events since
  2877. // they didn't play through them.
  2878. if (!seeking) {
  2879. this.onRegionEvent_(
  2880. shaka.util.FakeEvent.EventName.TimelineRegionEnter, region);
  2881. this.onRegionEvent_(
  2882. shaka.util.FakeEvent.EventName.TimelineRegionExit, region);
  2883. }
  2884. });
  2885. // Now that we have all our observers, create a manager for them.
  2886. const manager = new shaka.media.PlayheadObserverManager(this.video_);
  2887. manager.manage(regionObserver);
  2888. if (this.qualityObserver_) {
  2889. manager.manage(this.qualityObserver_);
  2890. }
  2891. return manager;
  2892. }
  2893. /**
  2894. * Initialize and start the buffering system (observer and timer) so that we
  2895. * can monitor our buffer lead during playback.
  2896. *
  2897. * @param {!HTMLMediaElement} mediaElement
  2898. * @param {number} rebufferingGoal
  2899. * @private
  2900. */
  2901. startBufferManagement_(mediaElement, rebufferingGoal) {
  2902. goog.asserts.assert(
  2903. !this.bufferObserver_,
  2904. 'No buffering observer should exist before initialization.');
  2905. goog.asserts.assert(
  2906. !this.bufferPoller_,
  2907. 'No buffer timer should exist before initialization.');
  2908. // Give dummy values, will be updated below.
  2909. this.bufferObserver_ = new shaka.media.BufferingObserver(1, 2);
  2910. // Force us back to a buffering state. This ensure everything is starting in
  2911. // the same state.
  2912. this.bufferObserver_.setState(shaka.media.BufferingObserver.State.STARVING);
  2913. this.updateBufferingSettings_(rebufferingGoal);
  2914. this.updateBufferState_();
  2915. this.bufferPoller_ = new shaka.util.Timer(() => {
  2916. this.pollBufferState_();
  2917. }).tickEvery(/* seconds= */ 0.25);
  2918. this.loadEventManager_.listen(mediaElement, 'waiting',
  2919. (e) => this.pollBufferState_());
  2920. this.loadEventManager_.listen(mediaElement, 'stalled',
  2921. (e) => this.pollBufferState_());
  2922. this.loadEventManager_.listen(mediaElement, 'canplaythrough',
  2923. (e) => this.pollBufferState_());
  2924. this.loadEventManager_.listen(mediaElement, 'progress',
  2925. (e) => this.pollBufferState_());
  2926. }
  2927. /**
  2928. * Updates the buffering thresholds based on the new rebuffering goal.
  2929. *
  2930. * @param {number} rebufferingGoal
  2931. * @private
  2932. */
  2933. updateBufferingSettings_(rebufferingGoal) {
  2934. // The threshold to transition back to satisfied when starving.
  2935. const starvingThreshold = rebufferingGoal;
  2936. // The threshold to transition into starving when satisfied.
  2937. // We use a "typical" threshold, unless the rebufferingGoal is unusually
  2938. // low.
  2939. // Then we force the value down to half the rebufferingGoal, since
  2940. // starvingThreshold must be strictly larger than satisfiedThreshold for the
  2941. // logic in BufferingObserver to work correctly.
  2942. const satisfiedThreshold = Math.min(
  2943. shaka.Player.TYPICAL_BUFFERING_THRESHOLD_, rebufferingGoal / 2);
  2944. this.bufferObserver_.setThresholds(starvingThreshold, satisfiedThreshold);
  2945. }
  2946. /**
  2947. * This method is called periodically to check what the buffering observer
  2948. * says so that we can update the rest of the buffering behaviours.
  2949. *
  2950. * @private
  2951. */
  2952. pollBufferState_() {
  2953. goog.asserts.assert(
  2954. this.video_,
  2955. 'Need a media element to update the buffering observer');
  2956. goog.asserts.assert(
  2957. this.bufferObserver_,
  2958. 'Need a buffering observer to update');
  2959. let bufferedToEnd;
  2960. switch (this.loadMode_) {
  2961. case shaka.Player.LoadMode.SRC_EQUALS:
  2962. bufferedToEnd = this.isBufferedToEndSrc_();
  2963. break;
  2964. case shaka.Player.LoadMode.MEDIA_SOURCE:
  2965. bufferedToEnd = this.isBufferedToEndMS_();
  2966. break;
  2967. default:
  2968. bufferedToEnd = false;
  2969. break;
  2970. }
  2971. const bufferLead = shaka.media.TimeRangesUtils.bufferedAheadOf(
  2972. this.video_.buffered,
  2973. this.video_.currentTime);
  2974. const stateChanged = this.bufferObserver_.update(bufferLead, bufferedToEnd);
  2975. // If the state changed, we need to surface the event.
  2976. if (stateChanged) {
  2977. this.updateBufferState_();
  2978. }
  2979. }
  2980. /**
  2981. * Create a new media source engine. This will ONLY be replaced by tests as a
  2982. * way to inject fake media source engine instances.
  2983. *
  2984. * @param {!HTMLMediaElement} mediaElement
  2985. * @param {!shaka.extern.TextDisplayer} textDisplayer
  2986. * @param {!shaka.media.MediaSourceEngine.PlayerInterface} playerInterface
  2987. * @param {shaka.lcevc.Dec} lcevcDec
  2988. *
  2989. * @return {!shaka.media.MediaSourceEngine}
  2990. */
  2991. createMediaSourceEngine(mediaElement, textDisplayer, playerInterface,
  2992. lcevcDec) {
  2993. return new shaka.media.MediaSourceEngine(
  2994. mediaElement,
  2995. textDisplayer,
  2996. playerInterface,
  2997. lcevcDec);
  2998. }
  2999. /**
  3000. * Create a new CMCD manager.
  3001. *
  3002. * @private
  3003. */
  3004. createCmcd_() {
  3005. /** @type {shaka.util.CmcdManager.PlayerInterface} */
  3006. const playerInterface = {
  3007. getBandwidthEstimate: () => this.abrManager_ ?
  3008. this.abrManager_.getBandwidthEstimate() : NaN,
  3009. getBufferedInfo: () => this.getBufferedInfo(),
  3010. getCurrentTime: () => this.video_ ? this.video_.currentTime : 0,
  3011. getPlaybackRate: () => this.getPlaybackRate(),
  3012. getNetworkingEngine: () => this.getNetworkingEngine(),
  3013. getVariantTracks: () => this.getVariantTracks(),
  3014. isLive: () => this.isLive(),
  3015. };
  3016. return new shaka.util.CmcdManager(playerInterface, this.config_.cmcd);
  3017. }
  3018. /**
  3019. * Create a new CMSD manager.
  3020. *
  3021. * @private
  3022. */
  3023. createCmsd_() {
  3024. return new shaka.util.CmsdManager(this.config_.cmsd);
  3025. }
  3026. /**
  3027. * Creates a new instance of StreamingEngine. This can be replaced by tests
  3028. * to create fake instances instead.
  3029. *
  3030. * @return {!shaka.media.StreamingEngine}
  3031. */
  3032. createStreamingEngine() {
  3033. goog.asserts.assert(
  3034. this.abrManager_ && this.mediaSourceEngine_ && this.manifest_,
  3035. 'Must not be destroyed');
  3036. /** @type {shaka.media.StreamingEngine.PlayerInterface} */
  3037. const playerInterface = {
  3038. getPresentationTime: () => this.playhead_ ? this.playhead_.getTime() : 0,
  3039. getBandwidthEstimate: () => this.abrManager_.getBandwidthEstimate(),
  3040. getPlaybackRate: () => this.getPlaybackRate(),
  3041. mediaSourceEngine: this.mediaSourceEngine_,
  3042. netEngine: this.networkingEngine_,
  3043. onError: (error) => this.onError_(error),
  3044. onEvent: (event) => this.dispatchEvent(event),
  3045. onManifestUpdate: () => this.onManifestUpdate_(),
  3046. onSegmentAppended: (reference, stream) => {
  3047. this.onSegmentAppended_(
  3048. reference.startTime, reference.endTime, stream.type);
  3049. if (this.abrManager_ && stream.fastSwitching &&
  3050. reference.isPartial() && reference.isLastPartial()) {
  3051. this.abrManager_.trySuggestStreams();
  3052. }
  3053. },
  3054. onInitSegmentAppended: (position, initSegment) => {
  3055. const mediaQuality = initSegment.getMediaQuality();
  3056. if (mediaQuality && this.qualityObserver_) {
  3057. this.qualityObserver_.addMediaQualityChange(mediaQuality, position);
  3058. }
  3059. },
  3060. beforeAppendSegment: (contentType, segment) => {
  3061. return this.drmEngine_.parseInbandPssh(contentType, segment);
  3062. },
  3063. onMetadata: (metadata, offset, endTime) => {
  3064. this.processTimedMetadataMediaSrc_(metadata, offset, endTime);
  3065. },
  3066. disableStream: (stream, time) => this.disableStream(stream, time),
  3067. };
  3068. return new shaka.media.StreamingEngine(this.manifest_, playerInterface);
  3069. }
  3070. /**
  3071. * Changes configuration settings on the Player. This checks the names of
  3072. * keys and the types of values to avoid coding errors. If there are errors,
  3073. * this logs them to the console and returns false. Correct fields are still
  3074. * applied even if there are other errors. You can pass an explicit
  3075. * <code>undefined</code> value to restore the default value. This has two
  3076. * modes of operation:
  3077. *
  3078. * <p>
  3079. * First, this can be passed a single "plain" object. This object should
  3080. * follow the {@link shaka.extern.PlayerConfiguration} object. Not all fields
  3081. * need to be set; unset fields retain their old values.
  3082. *
  3083. * <p>
  3084. * Second, this can be passed two arguments. The first is the name of the key
  3085. * to set. This should be a '.' separated path to the key. For example,
  3086. * <code>'streaming.alwaysStreamText'</code>. The second argument is the
  3087. * value to set.
  3088. *
  3089. * @param {string|!Object} config This should either be a field name or an
  3090. * object.
  3091. * @param {*=} value In the second mode, this is the value to set.
  3092. * @return {boolean} True if the passed config object was valid, false if
  3093. * there were invalid entries.
  3094. * @export
  3095. */
  3096. configure(config, value) {
  3097. goog.asserts.assert(this.config_, 'Config must not be null!');
  3098. goog.asserts.assert(typeof(config) == 'object' || arguments.length == 2,
  3099. 'String configs should have values!');
  3100. // ('fieldName', value) format
  3101. if (arguments.length == 2 && typeof(config) == 'string') {
  3102. config = shaka.util.ConfigUtils.convertToConfigObject(config, value);
  3103. }
  3104. goog.asserts.assert(typeof(config) == 'object', 'Should be an object!');
  3105. // Deprecate 'streaming.forceTransmuxTS' configuration.
  3106. if (config['streaming'] && 'forceTransmuxTS' in config['streaming']) {
  3107. shaka.Deprecate.deprecateFeature(5,
  3108. 'streaming.forceTransmuxTS configuration',
  3109. 'Please Use mediaSource.forceTransmux instead.');
  3110. config['mediaSource']['mediaSource'] =
  3111. config['streaming']['forceTransmuxTS'];
  3112. delete config['streaming']['forceTransmuxTS'];
  3113. }
  3114. // Deprecate 'streaming.forceTransmux' configuration.
  3115. if (config['streaming'] && 'forceTransmux' in config['streaming']) {
  3116. shaka.Deprecate.deprecateFeature(5,
  3117. 'streaming.forceTransmux configuration',
  3118. 'Please Use mediaSource.forceTransmux instead.');
  3119. config['mediaSource']['mediaSource'] =
  3120. config['streaming']['forceTransmux'];
  3121. delete config['streaming']['forceTransmux'];
  3122. }
  3123. // Deprecate 'streaming.useNativeHlsOnSafari' configuration.
  3124. if (config['streaming'] && 'useNativeHlsOnSafari' in config['streaming']) {
  3125. shaka.Deprecate.deprecateFeature(5,
  3126. 'streaming.useNativeHlsOnSafari configuration',
  3127. 'Please Use streaming.useNativeHlsForFairPlay or ' +
  3128. 'streaming.preferNativeHls instead.');
  3129. }
  3130. // Deprecate 'mediaSource.sourceBufferExtraFeatures' configuration.
  3131. if (config['mediaSource'] &&
  3132. 'sourceBufferExtraFeatures' in config['mediaSource']) {
  3133. shaka.Deprecate.deprecateFeature(5,
  3134. 'mediaSource.sourceBufferExtraFeatures configuration',
  3135. 'Please Use mediaSource.addExtraFeaturesToSourceBuffer() instead.');
  3136. const sourceBufferExtraFeatures =
  3137. config['mediaSource']['sourceBufferExtraFeatures'];
  3138. config['mediaSource']['addExtraFeaturesToSourceBuffer'] = () => {
  3139. return sourceBufferExtraFeatures;
  3140. };
  3141. delete config['mediaSource']['sourceBufferExtraFeatures'];
  3142. }
  3143. // If lowLatencyMode is enabled, and inaccurateManifestTolerance and
  3144. // rebufferingGoal and segmentPrefetchLimit and baseDelay and
  3145. // autoCorrectDrift and maxDisabledTime are not specified, set
  3146. // inaccurateManifestTolerance to 0 and rebufferingGoal to 0.01 and
  3147. // segmentPrefetchLimit to 2 and updateIntervalSeconds to 0.1 and and
  3148. // baseDelay to 100 and autoCorrectDrift to false and maxDisabledTime
  3149. // to 1 by default for low latency streaming.
  3150. if (config['streaming'] && config['streaming']['lowLatencyMode']) {
  3151. if (config['streaming']['inaccurateManifestTolerance'] == undefined) {
  3152. config['streaming']['inaccurateManifestTolerance'] = 0;
  3153. }
  3154. if (config['streaming']['rebufferingGoal'] == undefined) {
  3155. config['streaming']['rebufferingGoal'] = 0.01;
  3156. }
  3157. if (config['streaming']['segmentPrefetchLimit'] == undefined) {
  3158. config['streaming']['segmentPrefetchLimit'] = 2;
  3159. }
  3160. if (config['streaming']['updateIntervalSeconds'] == undefined) {
  3161. config['streaming']['updateIntervalSeconds'] = 0.1;
  3162. }
  3163. if (config['streaming']['maxDisabledTime'] == undefined) {
  3164. config['streaming']['maxDisabledTime'] = 1;
  3165. }
  3166. if (config['streaming']['retryParameters'] == undefined) {
  3167. config['streaming']['retryParameters'] = {};
  3168. }
  3169. if (config['streaming']['retryParameters']['baseDelay'] == undefined) {
  3170. config['streaming']['retryParameters']['baseDelay'] = 100;
  3171. }
  3172. if (config['manifest'] == undefined) {
  3173. config['manifest'] = {};
  3174. }
  3175. if (config['manifest']['dash'] == undefined) {
  3176. config['manifest']['dash'] = {};
  3177. }
  3178. if (config['manifest']['dash']['autoCorrectDrift'] == undefined) {
  3179. config['manifest']['dash']['autoCorrectDrift'] = false;
  3180. }
  3181. if (config['manifest']['retryParameters'] == undefined) {
  3182. config['manifest']['retryParameters'] = {};
  3183. }
  3184. if (config['manifest']['retryParameters']['baseDelay'] == undefined) {
  3185. config['manifest']['retryParameters']['baseDelay'] = 100;
  3186. }
  3187. if (config['drm'] == undefined) {
  3188. config['drm'] = {};
  3189. }
  3190. if (config['drm']['retryParameters'] == undefined) {
  3191. config['drm']['retryParameters'] = {};
  3192. }
  3193. if (config['drm']['retryParameters']['baseDelay'] == undefined) {
  3194. config['drm']['retryParameters']['baseDelay'] = 100;
  3195. }
  3196. }
  3197. const ret = shaka.util.PlayerConfiguration.mergeConfigObjects(
  3198. this.config_, config, this.defaultConfig_());
  3199. this.applyConfig_();
  3200. return ret;
  3201. }
  3202. /**
  3203. * Apply config changes.
  3204. * @private
  3205. */
  3206. applyConfig_() {
  3207. this.manifestFilterer_ = new shaka.media.ManifestFilterer(
  3208. this.config_, this.maxHwRes_, this.drmEngine_);
  3209. if (this.parser_) {
  3210. const manifestConfig =
  3211. shaka.util.ObjectUtils.cloneObject(this.config_.manifest);
  3212. // Don't read video segments if the player is attached to an audio element
  3213. if (this.video_ && this.video_.nodeName === 'AUDIO') {
  3214. manifestConfig.disableVideo = true;
  3215. }
  3216. this.parser_.configure(manifestConfig);
  3217. }
  3218. if (this.drmEngine_) {
  3219. this.drmEngine_.configure(this.config_.drm);
  3220. }
  3221. if (this.streamingEngine_) {
  3222. this.streamingEngine_.configure(this.config_.streaming);
  3223. // Need to apply the restrictions.
  3224. // this.filterManifestWithRestrictions_() may throw.
  3225. try {
  3226. if (this.loadMode_ != shaka.Player.LoadMode.DESTROYED) {
  3227. if (this.manifestFilterer_.filterManifestWithRestrictions(
  3228. this.manifest_)) {
  3229. this.onTracksChanged_();
  3230. }
  3231. }
  3232. } catch (error) {
  3233. this.onError_(error);
  3234. }
  3235. if (this.abrManager_) {
  3236. // Update AbrManager variants to match these new settings.
  3237. this.updateAbrManagerVariants_();
  3238. }
  3239. // If the streams we are playing are restricted, we need to switch.
  3240. const activeVariant = this.streamingEngine_.getCurrentVariant();
  3241. if (activeVariant) {
  3242. if (!activeVariant.allowedByApplication ||
  3243. !activeVariant.allowedByKeySystem) {
  3244. shaka.log.debug('Choosing new variant after changing configuration');
  3245. this.chooseVariantAndSwitch_();
  3246. }
  3247. }
  3248. }
  3249. if (this.networkingEngine_) {
  3250. this.networkingEngine_.setForceHTTP(this.config_.streaming.forceHTTP);
  3251. this.networkingEngine_.setForceHTTPS(this.config_.streaming.forceHTTPS);
  3252. }
  3253. if (this.mediaSourceEngine_) {
  3254. this.mediaSourceEngine_.configure(this.config_.mediaSource);
  3255. const {segmentRelativeVttTiming} = this.config_.manifest;
  3256. this.mediaSourceEngine_.setSegmentRelativeVttTiming(
  3257. segmentRelativeVttTiming);
  3258. const textDisplayerFactory = this.config_.textDisplayFactory;
  3259. if (this.lastTextFactory_ != textDisplayerFactory) {
  3260. const displayer = textDisplayerFactory();
  3261. if (displayer.configure) {
  3262. displayer.configure(this.config_.textDisplayer);
  3263. } else {
  3264. shaka.Deprecate.deprecateFeature(5,
  3265. 'Text displayer w/ configure',
  3266. 'Text displayer should have a "configure" method!');
  3267. }
  3268. this.mediaSourceEngine_.setTextDisplayer(displayer);
  3269. this.lastTextFactory_ = textDisplayerFactory;
  3270. if (this.streamingEngine_) {
  3271. // Reload the text stream, so the cues will load again.
  3272. this.streamingEngine_.reloadTextStream();
  3273. }
  3274. } else {
  3275. const displayer = this.mediaSourceEngine_.getTextDisplayer();
  3276. if (displayer.configure) {
  3277. displayer.configure(this.config_.textDisplayer);
  3278. }
  3279. }
  3280. }
  3281. if (this.abrManager_) {
  3282. this.abrManager_.configure(this.config_.abr);
  3283. // Simply enable/disable ABR with each call, since multiple calls to these
  3284. // methods have no effect.
  3285. if (this.config_.abr.enabled) {
  3286. this.abrManager_.enable();
  3287. } else {
  3288. this.abrManager_.disable();
  3289. }
  3290. this.onAbrStatusChanged_();
  3291. }
  3292. if (this.bufferObserver_) {
  3293. let rebufferThreshold = this.config_.streaming.rebufferingGoal;
  3294. if (this.manifest_) {
  3295. rebufferThreshold =
  3296. Math.max(rebufferThreshold, this.manifest_.minBufferTime);
  3297. }
  3298. this.updateBufferingSettings_(rebufferThreshold);
  3299. }
  3300. if (this.manifest_) {
  3301. shaka.Player.applyPlayRange_(this.manifest_.presentationTimeline,
  3302. this.config_.playRangeStart,
  3303. this.config_.playRangeEnd);
  3304. }
  3305. if (this.adManager_) {
  3306. this.adManager_.configure(this.config_.ads);
  3307. }
  3308. if (this.cmcdManager_) {
  3309. this.cmcdManager_.configure(this.config_.cmcd);
  3310. }
  3311. if (this.cmsdManager_) {
  3312. this.cmsdManager_.configure(this.config_.cmsd);
  3313. }
  3314. }
  3315. /**
  3316. * Return a copy of the current configuration. Modifications of the returned
  3317. * value will not affect the Player's active configuration. You must call
  3318. * <code>player.configure()</code> to make changes.
  3319. *
  3320. * @return {shaka.extern.PlayerConfiguration}
  3321. * @export
  3322. */
  3323. getConfiguration() {
  3324. goog.asserts.assert(this.config_, 'Config must not be null!');
  3325. const ret = this.defaultConfig_();
  3326. shaka.util.PlayerConfiguration.mergeConfigObjects(
  3327. ret, this.config_, this.defaultConfig_());
  3328. return ret;
  3329. }
  3330. /**
  3331. * Return a copy of the current non default configuration. Modifications of
  3332. * the returned value will not affect the Player's active configuration.
  3333. * You must call <code>player.configure()</code> to make changes.
  3334. *
  3335. * @return {!Object}
  3336. * @export
  3337. */
  3338. getNonDefaultConfiguration() {
  3339. goog.asserts.assert(this.config_, 'Config must not be null!');
  3340. const ret = this.defaultConfig_();
  3341. shaka.util.PlayerConfiguration.mergeConfigObjects(
  3342. ret, this.config_, this.defaultConfig_());
  3343. return shaka.util.ConfigUtils.getDifferenceFromConfigObjects(
  3344. this.config_, this.defaultConfig_());
  3345. }
  3346. /**
  3347. * Return a reference to the current configuration. Modifications to the
  3348. * returned value will affect the Player's active configuration. This method
  3349. * is not exported as sharing configuration with external objects is not
  3350. * supported.
  3351. *
  3352. * @return {shaka.extern.PlayerConfiguration}
  3353. */
  3354. getSharedConfiguration() {
  3355. goog.asserts.assert(
  3356. this.config_, 'Cannot call getSharedConfiguration after call destroy!');
  3357. return this.config_;
  3358. }
  3359. /**
  3360. * Returns the ratio of video length buffered compared to buffering Goal
  3361. * @return {number}
  3362. * @export
  3363. */
  3364. getBufferFullness() {
  3365. if (this.video_) {
  3366. const bufferedLength = this.video_.buffered.length;
  3367. const bufferedEnd =
  3368. bufferedLength ? this.video_.buffered.end(bufferedLength - 1) : 0;
  3369. const bufferingGoal = this.getConfiguration().streaming.bufferingGoal;
  3370. const lengthToBeBuffered = Math.min(this.video_.currentTime +
  3371. bufferingGoal, this.seekRange().end);
  3372. if (bufferedEnd >= lengthToBeBuffered) {
  3373. return 1;
  3374. } else if (bufferedEnd <= this.video_.currentTime) {
  3375. return 0;
  3376. } else if (bufferedEnd < lengthToBeBuffered) {
  3377. return ((bufferedEnd - this.video_.currentTime) /
  3378. (lengthToBeBuffered - this.video_.currentTime));
  3379. }
  3380. }
  3381. return 0;
  3382. }
  3383. /**
  3384. * Reset configuration to default.
  3385. * @export
  3386. */
  3387. resetConfiguration() {
  3388. goog.asserts.assert(this.config_, 'Cannot be destroyed');
  3389. // Remove the old keys so we remove open-ended dictionaries like drm.servers
  3390. // but keeps the same object reference.
  3391. for (const key in this.config_) {
  3392. delete this.config_[key];
  3393. }
  3394. shaka.util.PlayerConfiguration.mergeConfigObjects(
  3395. this.config_, this.defaultConfig_(), this.defaultConfig_());
  3396. this.applyConfig_();
  3397. }
  3398. /**
  3399. * Get the current load mode.
  3400. *
  3401. * @return {shaka.Player.LoadMode}
  3402. * @export
  3403. */
  3404. getLoadMode() {
  3405. return this.loadMode_;
  3406. }
  3407. /**
  3408. * Get the current manifest type.
  3409. *
  3410. * @return {?string}
  3411. * @export
  3412. */
  3413. getManifestType() {
  3414. if (!this.manifest_) {
  3415. return null;
  3416. }
  3417. return this.manifest_.type;
  3418. }
  3419. /**
  3420. * Get the media element that the player is currently using to play loaded
  3421. * content. If the player has not loaded content, this will return
  3422. * <code>null</code>.
  3423. *
  3424. * @return {HTMLMediaElement}
  3425. * @export
  3426. */
  3427. getMediaElement() {
  3428. return this.video_;
  3429. }
  3430. /**
  3431. * @return {shaka.net.NetworkingEngine} A reference to the Player's networking
  3432. * engine. Applications may use this to make requests through Shaka's
  3433. * networking plugins.
  3434. * @export
  3435. */
  3436. getNetworkingEngine() {
  3437. return this.networkingEngine_;
  3438. }
  3439. /**
  3440. * Get the uri to the asset that the player has loaded. If the player has not
  3441. * loaded content, this will return <code>null</code>.
  3442. *
  3443. * @return {?string}
  3444. * @export
  3445. */
  3446. getAssetUri() {
  3447. return this.assetUri_;
  3448. }
  3449. /**
  3450. * Returns a shaka.ads.AdManager instance, responsible for Dynamic
  3451. * Ad Insertion functionality.
  3452. *
  3453. * @return {shaka.extern.IAdManager}
  3454. * @export
  3455. */
  3456. getAdManager() {
  3457. // NOTE: this clause is redundant, but it keeps the compiler from
  3458. // inlining this function. Inlining leads to setting the adManager
  3459. // not taking effect in the compiled build.
  3460. // Closure has a @noinline flag, but apparently not all cases are
  3461. // supported by it, and ours isn't.
  3462. // If they expand support, we might be able to get rid of this
  3463. // clause.
  3464. if (!this.adManager_) {
  3465. return null;
  3466. }
  3467. return this.adManager_;
  3468. }
  3469. /**
  3470. * Get if the player is playing live content. If the player has not loaded
  3471. * content, this will return <code>false</code>.
  3472. *
  3473. * @return {boolean}
  3474. * @export
  3475. */
  3476. isLive() {
  3477. if (this.manifest_) {
  3478. return this.manifest_.presentationTimeline.isLive();
  3479. }
  3480. // For native HLS, the duration for live streams seems to be Infinity.
  3481. if (this.video_ && this.video_.src) {
  3482. return this.video_.duration == Infinity;
  3483. }
  3484. return false;
  3485. }
  3486. /**
  3487. * Get if the player is playing in-progress content. If the player has not
  3488. * loaded content, this will return <code>false</code>.
  3489. *
  3490. * @return {boolean}
  3491. * @export
  3492. */
  3493. isInProgress() {
  3494. return this.manifest_ ?
  3495. this.manifest_.presentationTimeline.isInProgress() :
  3496. false;
  3497. }
  3498. /**
  3499. * Check if the manifest contains only audio-only content. If the player has
  3500. * not loaded content, this will return <code>false</code>.
  3501. *
  3502. * <p>
  3503. * The player does not support content that contain more than one type of
  3504. * variants (i.e. mixing audio-only, video-only, audio-video). Content will be
  3505. * filtered to only contain one type of variant.
  3506. *
  3507. * @return {boolean}
  3508. * @export
  3509. */
  3510. isAudioOnly() {
  3511. if (this.manifest_) {
  3512. const variants = this.manifest_.variants;
  3513. if (!variants.length) {
  3514. return false;
  3515. }
  3516. // Note that if there are some audio-only variants and some audio-video
  3517. // variants, the audio-only variants are removed during filtering.
  3518. // Therefore if the first variant has no video, that's sufficient to say
  3519. // it is audio-only content.
  3520. return !variants[0].video;
  3521. } else if (this.video_ && this.video_.src) {
  3522. // If we have video track info, use that. It will be the least
  3523. // error-prone way with native HLS. In contrast, videoHeight might be
  3524. // unset until the first frame is loaded. Since isAudioOnly is queried
  3525. // by the UI on the 'trackschanged' event, the videoTracks info should be
  3526. // up-to-date.
  3527. if (this.video_.videoTracks) {
  3528. return this.video_.videoTracks.length == 0;
  3529. }
  3530. // We cast to the more specific HTMLVideoElement to access videoHeight.
  3531. // This might be an audio element, though, in which case videoHeight will
  3532. // be undefined at runtime. For audio elements, this will always return
  3533. // true.
  3534. const video = /** @type {HTMLVideoElement} */(this.video_);
  3535. return video.videoHeight == 0;
  3536. } else {
  3537. return false;
  3538. }
  3539. }
  3540. /**
  3541. * Get the range of time (in seconds) that seeking is allowed. If the player
  3542. * has not loaded content and the manifest is HLS, this will return a range
  3543. * from 0 to 0.
  3544. *
  3545. * @return {{start: number, end: number}}
  3546. * @export
  3547. */
  3548. seekRange() {
  3549. if (this.manifest_) {
  3550. // With HLS lazy-loading, there were some situations where the manifest
  3551. // had partially loaded, enough to move onto further load stages, but no
  3552. // segments had been loaded, so the timeline is still unknown.
  3553. // See: https://github.com/shaka-project/shaka-player/pull/4590
  3554. if (!this.fullyLoaded_ &&
  3555. this.manifest_.type == shaka.media.ManifestParser.HLS) {
  3556. return {'start': 0, 'end': 0};
  3557. }
  3558. const timeline = this.manifest_.presentationTimeline;
  3559. return {
  3560. 'start': timeline.getSeekRangeStart(),
  3561. 'end': timeline.getSeekRangeEnd(),
  3562. };
  3563. }
  3564. // If we have loaded content with src=, we ask the video element for its
  3565. // seekable range. This covers both plain mp4s and native HLS playbacks.
  3566. if (this.video_ && this.video_.src) {
  3567. const seekable = this.video_.seekable;
  3568. if (seekable.length) {
  3569. return {
  3570. 'start': seekable.start(0),
  3571. 'end': seekable.end(seekable.length - 1),
  3572. };
  3573. }
  3574. }
  3575. return {'start': 0, 'end': 0};
  3576. }
  3577. /**
  3578. * Go to live in a live stream.
  3579. *
  3580. * @export
  3581. */
  3582. goToLive() {
  3583. if (this.isLive()) {
  3584. this.video_.currentTime = this.seekRange().end;
  3585. } else {
  3586. shaka.log.warning('goToLive is for live streams!');
  3587. }
  3588. }
  3589. /**
  3590. * Get the key system currently used by EME. If EME is not being used, this
  3591. * will return an empty string. If the player has not loaded content, this
  3592. * will return an empty string.
  3593. *
  3594. * @return {string}
  3595. * @export
  3596. */
  3597. keySystem() {
  3598. return shaka.media.DrmEngine.keySystem(this.drmInfo());
  3599. }
  3600. /**
  3601. * Get the drm info used to initialize EME. If EME is not being used, this
  3602. * will return <code>null</code>. If the player is idle or has not initialized
  3603. * EME yet, this will return <code>null</code>.
  3604. *
  3605. * @return {?shaka.extern.DrmInfo}
  3606. * @export
  3607. */
  3608. drmInfo() {
  3609. return this.drmEngine_ ? this.drmEngine_.getDrmInfo() : null;
  3610. }
  3611. /**
  3612. * Get the drm engine.
  3613. * This method should only be used for testing. Applications SHOULD NOT
  3614. * use this in production.
  3615. *
  3616. * @return {?shaka.media.DrmEngine}
  3617. */
  3618. getDrmEngine() {
  3619. return this.drmEngine_;
  3620. }
  3621. /**
  3622. * Get the next known expiration time for any EME session. If the session
  3623. * never expires, this will return <code>Infinity</code>. If there are no EME
  3624. * sessions, this will return <code>Infinity</code>. If the player has not
  3625. * loaded content, this will return <code>Infinity</code>.
  3626. *
  3627. * @return {number}
  3628. * @export
  3629. */
  3630. getExpiration() {
  3631. return this.drmEngine_ ? this.drmEngine_.getExpiration() : Infinity;
  3632. }
  3633. /**
  3634. * Returns the active sessions metadata
  3635. *
  3636. * @return {!Array.<shaka.extern.DrmSessionMetadata>}
  3637. * @export
  3638. */
  3639. getActiveSessionsMetadata() {
  3640. return this.drmEngine_ ? this.drmEngine_.getActiveSessionsMetadata() : [];
  3641. }
  3642. /**
  3643. * Gets a map of EME key ID to the current key status.
  3644. *
  3645. * @return {!Object<string, string>}
  3646. * @export
  3647. */
  3648. getKeyStatuses() {
  3649. return this.drmEngine_ ? this.drmEngine_.getKeyStatuses() : {};
  3650. }
  3651. /**
  3652. * Check if the player is currently in a buffering state (has too little
  3653. * content to play smoothly). If the player has not loaded content, this will
  3654. * return <code>false</code>.
  3655. *
  3656. * @return {boolean}
  3657. * @export
  3658. */
  3659. isBuffering() {
  3660. const State = shaka.media.BufferingObserver.State;
  3661. return this.bufferObserver_ ?
  3662. this.bufferObserver_.getState() == State.STARVING :
  3663. false;
  3664. }
  3665. /**
  3666. * Get the playback rate of what is playing right now. If we are using trick
  3667. * play, this will return the trick play rate.
  3668. * If no content is playing, this will return 0.
  3669. * If content is buffering, this will return the expected playback rate once
  3670. * the video starts playing.
  3671. *
  3672. * <p>
  3673. * If the player has not loaded content, this will return a playback rate of
  3674. * 0.
  3675. *
  3676. * @return {number}
  3677. * @export
  3678. */
  3679. getPlaybackRate() {
  3680. if (!this.video_) {
  3681. return 0;
  3682. }
  3683. return this.playRateController_ ?
  3684. this.playRateController_.getRealRate() :
  3685. 1;
  3686. }
  3687. /**
  3688. * Enable trick play to skip through content without playing by repeatedly
  3689. * seeking. For example, a rate of 2.5 would result in 2.5 seconds of content
  3690. * being skipped every second. A negative rate will result in moving
  3691. * backwards.
  3692. *
  3693. * <p>
  3694. * If the player has not loaded content or is still loading content this will
  3695. * be a no-op. Wait until <code>load</code> has completed before calling.
  3696. *
  3697. * <p>
  3698. * Trick play will be canceled automatically if the playhead hits the
  3699. * beginning or end of the seekable range for the content.
  3700. *
  3701. * @param {number} rate
  3702. * @export
  3703. */
  3704. trickPlay(rate) {
  3705. // A playbackRate of 0 is used internally when we are in a buffering state,
  3706. // and doesn't make sense for trick play. If you set a rate of 0 for trick
  3707. // play, we will reject it and issue a warning. If it happens during a
  3708. // test, we will fail the test through this assertion.
  3709. goog.asserts.assert(rate != 0, 'Should never set a trick play rate of 0!');
  3710. if (rate == 0) {
  3711. shaka.log.alwaysWarn('A trick play rate of 0 is unsupported!');
  3712. return;
  3713. }
  3714. this.trickPlayEventManager_.removeAll();
  3715. if (this.video_.paused) {
  3716. // Our fast forward is implemented with playbackRate and needs the video
  3717. // to be playing (to not be paused) to take immediate effect.
  3718. // If the video is paused, "unpause" it.
  3719. this.video_.play();
  3720. }
  3721. this.playRateController_.set(rate);
  3722. if (this.loadMode_ == shaka.Player.LoadMode.MEDIA_SOURCE) {
  3723. this.abrManager_.playbackRateChanged(rate);
  3724. this.streamingEngine_.setTrickPlay(Math.abs(rate) > 1);
  3725. }
  3726. if (this.isLive()) {
  3727. this.trickPlayEventManager_.listen(this.video_, 'timeupdate', () => {
  3728. const currentTime = this.video_.currentTime;
  3729. const seekRange = this.seekRange();
  3730. const safeSeekOffset = this.config_.streaming.safeSeekOffset;
  3731. // Cancel trick play if we hit the beginning or end of the seekable
  3732. // (Sub-second accuracy not required here)
  3733. if (rate > 0) {
  3734. if (Math.floor(currentTime) >= Math.floor(seekRange.end)) {
  3735. this.cancelTrickPlay();
  3736. }
  3737. } else {
  3738. if (Math.floor(currentTime) <=
  3739. Math.floor(seekRange.start + safeSeekOffset)) {
  3740. this.cancelTrickPlay();
  3741. }
  3742. }
  3743. });
  3744. }
  3745. }
  3746. /**
  3747. * Cancel trick-play. If the player has not loaded content or is still loading
  3748. * content this will be a no-op.
  3749. *
  3750. * @export
  3751. */
  3752. cancelTrickPlay() {
  3753. const defaultPlaybackRate = this.playRateController_.getDefaultRate();
  3754. if (this.loadMode_ == shaka.Player.LoadMode.SRC_EQUALS) {
  3755. this.playRateController_.set(defaultPlaybackRate);
  3756. }
  3757. if (this.loadMode_ == shaka.Player.LoadMode.MEDIA_SOURCE) {
  3758. this.playRateController_.set(defaultPlaybackRate);
  3759. this.abrManager_.playbackRateChanged(defaultPlaybackRate);
  3760. this.streamingEngine_.setTrickPlay(false);
  3761. }
  3762. this.trickPlayEventManager_.removeAll();
  3763. }
  3764. /**
  3765. * Return a list of variant tracks that can be switched to.
  3766. *
  3767. * <p>
  3768. * If the player has not loaded content, this will return an empty list.
  3769. *
  3770. * @return {!Array.<shaka.extern.Track>}
  3771. * @export
  3772. */
  3773. getVariantTracks() {
  3774. if (this.manifest_) {
  3775. const currentVariant = this.streamingEngine_ ?
  3776. this.streamingEngine_.getCurrentVariant() : null;
  3777. const tracks = [];
  3778. let activeTracks = 0;
  3779. // Convert each variant to a track.
  3780. for (const variant of this.manifest_.variants) {
  3781. if (!shaka.util.StreamUtils.isPlayable(variant)) {
  3782. continue;
  3783. }
  3784. const track = shaka.util.StreamUtils.variantToTrack(variant);
  3785. track.active = variant == currentVariant;
  3786. if (!track.active && activeTracks != 1 && currentVariant != null &&
  3787. variant.video == currentVariant.video &&
  3788. variant.audio == currentVariant.audio) {
  3789. track.active = true;
  3790. }
  3791. if (track.active) {
  3792. activeTracks++;
  3793. }
  3794. tracks.push(track);
  3795. }
  3796. goog.asserts.assert(activeTracks <= 1,
  3797. 'It should only have one active track');
  3798. return tracks;
  3799. } else if (this.video_ && this.video_.audioTracks) {
  3800. // Safari's native HLS always shows a single element in videoTracks.
  3801. // You can't use that API to change resolutions. But we can use
  3802. // audioTracks to generate a variant list that is usable for changing
  3803. // languages.
  3804. const audioTracks = Array.from(this.video_.audioTracks);
  3805. return audioTracks.map((audio) =>
  3806. shaka.util.StreamUtils.html5AudioTrackToTrack(audio));
  3807. } else {
  3808. return [];
  3809. }
  3810. }
  3811. /**
  3812. * Return a list of text tracks that can be switched to.
  3813. *
  3814. * <p>
  3815. * If the player has not loaded content, this will return an empty list.
  3816. *
  3817. * @return {!Array.<shaka.extern.Track>}
  3818. * @export
  3819. */
  3820. getTextTracks() {
  3821. if (this.manifest_) {
  3822. const currentTextStream = this.streamingEngine_ ?
  3823. this.streamingEngine_.getCurrentTextStream() : null;
  3824. const tracks = [];
  3825. // Convert all selectable text streams to tracks.
  3826. for (const text of this.manifest_.textStreams) {
  3827. const track = shaka.util.StreamUtils.textStreamToTrack(text);
  3828. track.active = text == currentTextStream;
  3829. tracks.push(track);
  3830. }
  3831. return tracks;
  3832. } else if (this.video_ && this.video_.src && this.video_.textTracks) {
  3833. const textTracks = this.getFilteredTextTracks_();
  3834. const StreamUtils = shaka.util.StreamUtils;
  3835. return textTracks.map((text) => StreamUtils.html5TextTrackToTrack(text));
  3836. } else {
  3837. return [];
  3838. }
  3839. }
  3840. /**
  3841. * Return a list of image tracks that can be switched to.
  3842. *
  3843. * If the player has not loaded content, this will return an empty list.
  3844. *
  3845. * @return {!Array.<shaka.extern.Track>}
  3846. * @export
  3847. */
  3848. getImageTracks() {
  3849. const StreamUtils = shaka.util.StreamUtils;
  3850. let imageStreams = this.externalSrcEqualsThumbnailsStreams_;
  3851. if (this.manifest_) {
  3852. imageStreams = this.manifest_.imageStreams;
  3853. }
  3854. return imageStreams.map((image) => StreamUtils.imageStreamToTrack(image));
  3855. }
  3856. /**
  3857. * Returns Thumbnail objects for each thumbnail for a given image track ID.
  3858. *
  3859. * If the player has not loaded content, this will return a null.
  3860. *
  3861. * @param {number} trackId
  3862. * @return {!Promise.<?Array<!shaka.extern.Thumbnail>>}
  3863. * @export
  3864. */
  3865. async getAllThumbnails(trackId) {
  3866. if (this.loadMode_ != shaka.Player.LoadMode.MEDIA_SOURCE &&
  3867. this.loadMode_ != shaka.Player.LoadMode.SRC_EQUALS) {
  3868. return null;
  3869. }
  3870. let imageStreams = this.externalSrcEqualsThumbnailsStreams_;
  3871. if (this.manifest_) {
  3872. imageStreams = this.manifest_.imageStreams;
  3873. }
  3874. const imageStream = imageStreams.find(
  3875. (stream) => stream.id == trackId);
  3876. if (!imageStream) {
  3877. return null;
  3878. }
  3879. if (!imageStream.segmentIndex) {
  3880. await imageStream.createSegmentIndex();
  3881. }
  3882. const promises = [];
  3883. imageStream.segmentIndex.forEachTopLevelReference((reference) => {
  3884. const dimensions = this.parseTilesLayout_(
  3885. reference.getTilesLayout() || imageStream.tilesLayout);
  3886. if (dimensions) {
  3887. const numThumbnails = dimensions.rows * dimensions.columns;
  3888. const duration = reference.trueEndTime - reference.startTime;
  3889. for (let i = 0; i < numThumbnails; i++) {
  3890. const sampleTime = reference.startTime + duration * i / numThumbnails;
  3891. promises.push(this.getThumbnails(trackId, sampleTime));
  3892. }
  3893. }
  3894. });
  3895. const thumbnails = await Promise.all(promises);
  3896. return thumbnails.filter((t) => t);
  3897. }
  3898. /**
  3899. * Parses a tiles layout.
  3900. *
  3901. * @param {string|undefined} tilesLayout
  3902. * @return {?{
  3903. * columns: number,
  3904. * rows: number
  3905. * }}
  3906. * @private
  3907. */
  3908. parseTilesLayout_(tilesLayout) {
  3909. if (!tilesLayout) {
  3910. return null;
  3911. }
  3912. // This expression is used to detect one or more numbers (0-9) followed
  3913. // by an x and after one or more numbers (0-9)
  3914. const match = /(\d+)x(\d+)/.exec(tilesLayout);
  3915. if (!match) {
  3916. shaka.log.warning('Tiles layout does not contain a valid format ' +
  3917. ' (columns x rows)');
  3918. return null;
  3919. }
  3920. const columns = parseInt(match[1], 10);
  3921. const rows = parseInt(match[2], 10);
  3922. return {columns, rows};
  3923. }
  3924. /**
  3925. * Return a Thumbnail object from a image track Id and time.
  3926. *
  3927. * If the player has not loaded content, this will return a null.
  3928. *
  3929. * @param {number} trackId
  3930. * @param {number} time
  3931. * @return {!Promise.<?shaka.extern.Thumbnail>}
  3932. * @export
  3933. */
  3934. async getThumbnails(trackId, time) {
  3935. if (this.loadMode_ != shaka.Player.LoadMode.MEDIA_SOURCE &&
  3936. this.loadMode_ != shaka.Player.LoadMode.SRC_EQUALS) {
  3937. return null;
  3938. }
  3939. let imageStreams = this.externalSrcEqualsThumbnailsStreams_;
  3940. if (this.manifest_) {
  3941. imageStreams = this.manifest_.imageStreams;
  3942. }
  3943. const imageStream = imageStreams.find(
  3944. (stream) => stream.id == trackId);
  3945. if (!imageStream) {
  3946. return null;
  3947. }
  3948. if (!imageStream.segmentIndex) {
  3949. await imageStream.createSegmentIndex();
  3950. }
  3951. const referencePosition = imageStream.segmentIndex.find(time);
  3952. if (referencePosition == null) {
  3953. return null;
  3954. }
  3955. const reference = imageStream.segmentIndex.get(referencePosition);
  3956. const dimensions = this.parseTilesLayout_(
  3957. reference.getTilesLayout() || imageStream.tilesLayout);
  3958. if (!dimensions) {
  3959. return null;
  3960. }
  3961. const fullImageWidth = imageStream.width || 0;
  3962. const fullImageHeight = imageStream.height || 0;
  3963. let width = fullImageWidth / dimensions.columns;
  3964. let height = fullImageHeight / dimensions.rows;
  3965. const totalImages = dimensions.columns * dimensions.rows;
  3966. const segmentDuration = reference.trueEndTime - reference.startTime;
  3967. const thumbnailDuration =
  3968. reference.getTileDuration() || (segmentDuration / totalImages);
  3969. let thumbnailTime = reference.startTime;
  3970. let positionX = 0;
  3971. let positionY = 0;
  3972. // If the number of images in the segment is greater than 1, we have to
  3973. // find the correct image. For that we will return to the app the
  3974. // coordinates of the position of the correct image.
  3975. // Image search is always from left to right and top to bottom.
  3976. // Note: The time between images within the segment is always
  3977. // equidistant.
  3978. //
  3979. // Eg: Total images 5, tileLayout 5x1, segmentDuration 5, thumbnailTime 2
  3980. // positionX = 0.4 * fullImageWidth
  3981. // positionY = 0
  3982. if (totalImages > 1) {
  3983. const thumbnailPosition =
  3984. Math.floor((time - reference.startTime) / thumbnailDuration);
  3985. thumbnailTime = reference.startTime +
  3986. (thumbnailPosition * thumbnailDuration);
  3987. positionX = (thumbnailPosition % dimensions.columns) * width;
  3988. positionY = Math.floor(thumbnailPosition / dimensions.columns) * height;
  3989. }
  3990. let sprite = false;
  3991. const thumbnailSprite = reference.getThumbnailSprite();
  3992. if (thumbnailSprite) {
  3993. sprite = true;
  3994. height = thumbnailSprite.height;
  3995. positionX = thumbnailSprite.positionX;
  3996. positionY = thumbnailSprite.positionY;
  3997. width = thumbnailSprite.width;
  3998. }
  3999. return {
  4000. segment: reference,
  4001. imageHeight: fullImageHeight,
  4002. imageWidth: fullImageWidth,
  4003. height: height,
  4004. positionX: positionX,
  4005. positionY: positionY,
  4006. startTime: thumbnailTime,
  4007. duration: thumbnailDuration,
  4008. uris: reference.getUris(),
  4009. width: width,
  4010. sprite: sprite,
  4011. };
  4012. }
  4013. /**
  4014. * Select a specific text track. <code>track</code> should come from a call to
  4015. * <code>getTextTracks</code>. If the track is not found, this will be a
  4016. * no-op. If the player has not loaded content, this will be a no-op.
  4017. *
  4018. * <p>
  4019. * Note that <code>AdaptationEvents</code> are not fired for manual track
  4020. * selections.
  4021. *
  4022. * @param {shaka.extern.Track} track
  4023. * @export
  4024. */
  4025. selectTextTrack(track) {
  4026. if (this.manifest_ && this.streamingEngine_) {
  4027. const stream = this.manifest_.textStreams.find(
  4028. (stream) => stream.id == track.id);
  4029. if (!stream) {
  4030. shaka.log.error('No stream with id', track.id);
  4031. return;
  4032. }
  4033. if (stream == this.streamingEngine_.getCurrentTextStream()) {
  4034. shaka.log.debug('Text track already selected.');
  4035. return;
  4036. }
  4037. // Add entries to the history.
  4038. this.addTextStreamToSwitchHistory_(stream, /* fromAdaptation= */ false);
  4039. this.streamingEngine_.switchTextStream(stream);
  4040. this.onTextChanged_();
  4041. // Workaround for
  4042. // https://github.com/shaka-project/shaka-player/issues/1299
  4043. // When track is selected, back-propagate the language to
  4044. // currentTextLanguage_.
  4045. this.currentTextLanguage_ = stream.language;
  4046. } else if (this.video_ && this.video_.src && this.video_.textTracks) {
  4047. const textTracks = this.getFilteredTextTracks_();
  4048. for (const textTrack of textTracks) {
  4049. if (shaka.util.StreamUtils.html5TrackId(textTrack) == track.id) {
  4050. // Leave the track in 'hidden' if it's selected but not showing.
  4051. textTrack.mode = this.isTextVisible_ ? 'showing' : 'hidden';
  4052. } else {
  4053. // Safari allows multiple text tracks to have mode == 'showing', so be
  4054. // explicit in resetting the others.
  4055. textTrack.mode = 'disabled';
  4056. }
  4057. }
  4058. this.onTextChanged_();
  4059. }
  4060. }
  4061. /**
  4062. * Select a specific variant track to play. <code>track</code> should come
  4063. * from a call to <code>getVariantTracks</code>. If <code>track</code> cannot
  4064. * be found, this will be a no-op. If the player has not loaded content, this
  4065. * will be a no-op.
  4066. *
  4067. * <p>
  4068. * Changing variants will take effect once the currently buffered content has
  4069. * been played. To force the change to happen sooner, use
  4070. * <code>clearBuffer</code> with <code>safeMargin</code>. Setting
  4071. * <code>clearBuffer</code> to <code>true</code> will clear all buffered
  4072. * content after <code>safeMargin</code>, allowing the new variant to start
  4073. * playing sooner.
  4074. *
  4075. * <p>
  4076. * Note that <code>AdaptationEvents</code> are not fired for manual track
  4077. * selections.
  4078. *
  4079. * @param {shaka.extern.Track} track
  4080. * @param {boolean=} clearBuffer
  4081. * @param {number=} safeMargin Optional amount of buffer (in seconds) to
  4082. * retain when clearing the buffer. Useful for switching variant quickly
  4083. * without causing a buffering event. Defaults to 0 if not provided. Ignored
  4084. * if clearBuffer is false. Can cause hiccups on some browsers if chosen too
  4085. * small, e.g. The amount of two segments is a fair minimum to consider as
  4086. * safeMargin value.
  4087. * @export
  4088. */
  4089. selectVariantTrack(track, clearBuffer = false, safeMargin = 0) {
  4090. if (this.manifest_ && this.streamingEngine_) {
  4091. if (this.config_.abr.enabled) {
  4092. shaka.log.alwaysWarn('Changing tracks while abr manager is enabled ' +
  4093. 'will likely result in the selected track ' +
  4094. 'being overriden. Consider disabling abr before ' +
  4095. 'calling selectVariantTrack().');
  4096. }
  4097. const variant = this.manifest_.variants.find(
  4098. (variant) => variant.id == track.id);
  4099. if (!variant) {
  4100. shaka.log.error('No variant with id', track.id);
  4101. return;
  4102. }
  4103. // Double check that the track is allowed to be played. The track list
  4104. // should only contain playable variants, but if restrictions change and
  4105. // |selectVariantTrack| is called before the track list is updated, we
  4106. // could get a now-restricted variant.
  4107. if (!shaka.util.StreamUtils.isPlayable(variant)) {
  4108. shaka.log.error('Unable to switch to restricted track', track.id);
  4109. return;
  4110. }
  4111. this.switchVariant_(
  4112. variant, /* fromAdaptation= */ false, clearBuffer, safeMargin);
  4113. // Workaround for
  4114. // https://github.com/shaka-project/shaka-player/issues/1299
  4115. // When track is selected, back-propagate the language to
  4116. // currentAudioLanguage_.
  4117. this.currentAdaptationSetCriteria_ = new shaka.media.ExampleBasedCriteria(
  4118. variant,
  4119. this.config_.mediaSource.codecSwitchingStrategy,
  4120. this.config_.manifest.dash.enableAudioGroups);
  4121. // Update AbrManager variants to match these new settings.
  4122. this.updateAbrManagerVariants_();
  4123. } else if (this.video_ && this.video_.audioTracks) {
  4124. // Safari's native HLS won't let you choose an explicit variant, though
  4125. // you can choose audio languages this way.
  4126. const audioTracks = Array.from(this.video_.audioTracks);
  4127. for (const audioTrack of audioTracks) {
  4128. if (shaka.util.StreamUtils.html5TrackId(audioTrack) == track.id) {
  4129. // This will reset the "enabled" of other tracks to false.
  4130. this.switchHtml5Track_(audioTrack);
  4131. return;
  4132. }
  4133. }
  4134. }
  4135. }
  4136. /**
  4137. * Return a list of audio language-role combinations available. If the
  4138. * player has not loaded any content, this will return an empty list.
  4139. *
  4140. * @return {!Array.<shaka.extern.LanguageRole>}
  4141. * @export
  4142. */
  4143. getAudioLanguagesAndRoles() {
  4144. return shaka.Player.getLanguageAndRolesFrom_(this.getVariantTracks());
  4145. }
  4146. /**
  4147. * Return a list of text language-role combinations available. If the player
  4148. * has not loaded any content, this will be return an empty list.
  4149. *
  4150. * @return {!Array.<shaka.extern.LanguageRole>}
  4151. * @export
  4152. */
  4153. getTextLanguagesAndRoles() {
  4154. return shaka.Player.getLanguageAndRolesFrom_(this.getTextTracks());
  4155. }
  4156. /**
  4157. * Return a list of audio languages available. If the player has not loaded
  4158. * any content, this will return an empty list.
  4159. *
  4160. * @return {!Array.<string>}
  4161. * @export
  4162. */
  4163. getAudioLanguages() {
  4164. return Array.from(shaka.Player.getLanguagesFrom_(this.getVariantTracks()));
  4165. }
  4166. /**
  4167. * Return a list of text languages available. If the player has not loaded
  4168. * any content, this will return an empty list.
  4169. *
  4170. * @return {!Array.<string>}
  4171. * @export
  4172. */
  4173. getTextLanguages() {
  4174. return Array.from(shaka.Player.getLanguagesFrom_(this.getTextTracks()));
  4175. }
  4176. /**
  4177. * Sets the current audio language and current variant role to the selected
  4178. * language, role and channel count, and chooses a new variant if need be.
  4179. * If the player has not loaded any content, this will be a no-op.
  4180. *
  4181. * @param {string} language
  4182. * @param {string=} role
  4183. * @param {number=} channelsCount
  4184. * @param {number=} safeMargin
  4185. * @export
  4186. */
  4187. selectAudioLanguage(language, role, channelsCount = 0, safeMargin = 0) {
  4188. if (this.manifest_ && this.playhead_) {
  4189. this.currentAdaptationSetCriteria_ =
  4190. new shaka.media.PreferenceBasedCriteria(
  4191. language,
  4192. role || '',
  4193. channelsCount,
  4194. /* hdrLevel= */ '',
  4195. /* spatialAudio= */ false,
  4196. /* videoLayout= */ '',
  4197. /* audioLabel= */ '',
  4198. /* videoLabel= */ '',
  4199. this.config_.mediaSource.codecSwitchingStrategy,
  4200. this.config_.manifest.dash.enableAudioGroups);
  4201. const diff = (a, b) => {
  4202. if (!a.video && !b.video) {
  4203. return 0;
  4204. } else if (!a.video || !b.video) {
  4205. return Infinity;
  4206. } else {
  4207. return Math.abs((a.video.height || 0) - (b.video.height || 0)) +
  4208. Math.abs((a.video.width || 0) - (b.video.width || 0));
  4209. }
  4210. };
  4211. // Find the variant whose size is closest to the active variant. This
  4212. // ensures we stay at about the same resolution when just changing the
  4213. // language/role.
  4214. const active = this.streamingEngine_.getCurrentVariant();
  4215. const set =
  4216. this.currentAdaptationSetCriteria_.create(this.manifest_.variants);
  4217. let bestVariant = null;
  4218. for (const curVariant of set.values()) {
  4219. if (!bestVariant ||
  4220. diff(bestVariant, active) > diff(curVariant, active)) {
  4221. bestVariant = curVariant;
  4222. }
  4223. }
  4224. if (bestVariant) {
  4225. const track = shaka.util.StreamUtils.variantToTrack(bestVariant);
  4226. this.selectVariantTrack(track, /* clearBuffer= */ true, safeMargin);
  4227. return;
  4228. }
  4229. // If we haven't switched yet, just use ABR to find a new track.
  4230. this.chooseVariantAndSwitch_();
  4231. } else if (this.video_ && this.video_.audioTracks) {
  4232. const track = shaka.util.StreamUtils.filterStreamsByLanguageAndRole(
  4233. this.getVariantTracks(), language, role || '', false)[0];
  4234. if (track) {
  4235. this.selectVariantTrack(track);
  4236. }
  4237. }
  4238. }
  4239. /**
  4240. * Sets the current text language and current text role to the selected
  4241. * language and role, and chooses a new variant if need be. If the player has
  4242. * not loaded any content, this will be a no-op.
  4243. *
  4244. * @param {string} language
  4245. * @param {string=} role
  4246. * @param {boolean=} forced
  4247. * @export
  4248. */
  4249. selectTextLanguage(language, role, forced = false) {
  4250. if (this.manifest_ && this.playhead_) {
  4251. this.currentTextLanguage_ = language;
  4252. this.currentTextRole_ = role || '';
  4253. this.currentTextForced_ = forced;
  4254. const chosenText = this.chooseTextStream_();
  4255. if (chosenText) {
  4256. if (chosenText == this.streamingEngine_.getCurrentTextStream()) {
  4257. shaka.log.debug('Text track already selected.');
  4258. return;
  4259. }
  4260. this.addTextStreamToSwitchHistory_(
  4261. chosenText, /* fromAdaptation= */ false);
  4262. if (this.shouldStreamText_()) {
  4263. this.streamingEngine_.switchTextStream(chosenText);
  4264. this.onTextChanged_();
  4265. }
  4266. }
  4267. } else {
  4268. const track = shaka.util.StreamUtils.filterStreamsByLanguageAndRole(
  4269. this.getTextTracks(), language, role || '', forced)[0];
  4270. if (track) {
  4271. this.selectTextTrack(track);
  4272. }
  4273. }
  4274. }
  4275. /**
  4276. * Select variant tracks that have a given label. This assumes the
  4277. * label uniquely identifies an audio stream, so all the variants
  4278. * are expected to have the same variant.audio.
  4279. *
  4280. * @param {string} label
  4281. * @param {boolean=} clearBuffer Optional clear buffer or not when
  4282. * switch to new variant
  4283. * Defaults to true if not provided
  4284. * @param {number=} safeMargin Optional amount of buffer (in seconds) to
  4285. * retain when clearing the buffer.
  4286. * Defaults to 0 if not provided. Ignored if clearBuffer is false.
  4287. * @export
  4288. */
  4289. selectVariantsByLabel(label, clearBuffer = true, safeMargin = 0) {
  4290. if (this.manifest_ && this.playhead_) {
  4291. let firstVariantWithLabel = null;
  4292. for (const variant of this.manifest_.variants) {
  4293. if (variant.audio.label == label) {
  4294. firstVariantWithLabel = variant;
  4295. break;
  4296. }
  4297. }
  4298. if (firstVariantWithLabel == null) {
  4299. shaka.log.warning('No variants were found with label: ' +
  4300. label + '. Ignoring the request to switch.');
  4301. return;
  4302. }
  4303. // Label is a unique identifier of a variant's audio stream.
  4304. // Because of that we assume that all the variants with the same
  4305. // label have the same language.
  4306. this.currentAdaptationSetCriteria_ =
  4307. new shaka.media.PreferenceBasedCriteria(
  4308. firstVariantWithLabel.language,
  4309. /* role= */ '',
  4310. /* channelCount= */ 0,
  4311. /* hdrLevel= */ '',
  4312. /* spatialAudio= */ false,
  4313. /* videoLayout= */ '',
  4314. label,
  4315. /* videoLabel= */ '',
  4316. this.config_.mediaSource.codecSwitchingStrategy,
  4317. this.config_.manifest.dash.enableAudioGroups);
  4318. this.chooseVariantAndSwitch_(clearBuffer, safeMargin);
  4319. } else if (this.video_ && this.video_.audioTracks) {
  4320. const audioTracks = Array.from(this.video_.audioTracks);
  4321. let trackMatch = null;
  4322. for (const audioTrack of audioTracks) {
  4323. if (audioTrack.label == label) {
  4324. trackMatch = audioTrack;
  4325. }
  4326. }
  4327. if (trackMatch) {
  4328. this.switchHtml5Track_(trackMatch);
  4329. }
  4330. }
  4331. }
  4332. /**
  4333. * Check if the text displayer is enabled.
  4334. *
  4335. * @return {boolean}
  4336. * @export
  4337. */
  4338. isTextTrackVisible() {
  4339. const expected = this.isTextVisible_;
  4340. if (this.mediaSourceEngine_ &&
  4341. this.loadMode_ == shaka.Player.LoadMode.MEDIA_SOURCE) {
  4342. // Make sure our values are still in-sync.
  4343. const actual = this.mediaSourceEngine_.getTextDisplayer().isTextVisible();
  4344. goog.asserts.assert(
  4345. actual == expected, 'text visibility has fallen out of sync');
  4346. // Always return the actual value so that the app has the most accurate
  4347. // information (in the case that the values come out of sync in prod).
  4348. return actual;
  4349. } else if (this.video_ && this.video_.src && this.video_.textTracks) {
  4350. const textTracks = this.getFilteredTextTracks_();
  4351. return textTracks.some((t) => t.mode == 'showing');
  4352. }
  4353. return expected;
  4354. }
  4355. /**
  4356. * Return a list of chapters tracks.
  4357. *
  4358. * @return {!Array.<shaka.extern.Track>}
  4359. * @export
  4360. */
  4361. getChaptersTracks() {
  4362. if (this.video_ && this.video_.src && this.video_.textTracks) {
  4363. const textTracks = this.getChaptersTracks_();
  4364. const StreamUtils = shaka.util.StreamUtils;
  4365. return textTracks.map((text) => StreamUtils.html5TextTrackToTrack(text));
  4366. } else {
  4367. return [];
  4368. }
  4369. }
  4370. /**
  4371. * This returns the list of chapters.
  4372. *
  4373. * @param {string} language
  4374. * @return {!Array.<shaka.extern.Chapter>}
  4375. * @export
  4376. */
  4377. getChapters(language) {
  4378. if (!this.video_ || !this.video_.src || !this.video_.textTracks) {
  4379. return [];
  4380. }
  4381. const LanguageUtils = shaka.util.LanguageUtils;
  4382. const inputlanguage = LanguageUtils.normalize(language);
  4383. const chaptersTracks = this.getChaptersTracks_();
  4384. const chaptersTracksWithLanguage = chaptersTracks
  4385. .filter((t) => LanguageUtils.normalize(t.language) == inputlanguage);
  4386. if (!chaptersTracksWithLanguage || !chaptersTracksWithLanguage.length) {
  4387. return [];
  4388. }
  4389. const chapters = [];
  4390. const uniqueChapters = new Set();
  4391. for (const chaptersTrack of chaptersTracksWithLanguage) {
  4392. if (chaptersTrack && chaptersTrack.cues) {
  4393. for (const cue of chaptersTrack.cues) {
  4394. let id = cue.id;
  4395. if (!id || id == '') {
  4396. id = cue.startTime + '-' + cue.endTime + '-' + cue.text;
  4397. }
  4398. /** @type {shaka.extern.Chapter} */
  4399. const chapter = {
  4400. id: id,
  4401. title: cue.text,
  4402. startTime: cue.startTime,
  4403. endTime: cue.endTime,
  4404. };
  4405. if (!uniqueChapters.has(id)) {
  4406. chapters.push(chapter);
  4407. uniqueChapters.add(id);
  4408. }
  4409. }
  4410. }
  4411. }
  4412. return chapters;
  4413. }
  4414. /**
  4415. * Ignore the TextTracks with the 'metadata' or 'chapters' kind, or the one
  4416. * generated by the SimpleTextDisplayer.
  4417. *
  4418. * @return {!Array.<TextTrack>}
  4419. * @private
  4420. */
  4421. getFilteredTextTracks_() {
  4422. goog.asserts.assert(this.video_.textTracks,
  4423. 'TextTracks should be valid.');
  4424. return Array.from(this.video_.textTracks)
  4425. .filter((t) => t.kind != 'metadata' && t.kind != 'chapters' &&
  4426. t.label != shaka.Player.TextTrackLabel);
  4427. }
  4428. /**
  4429. * Get the TextTracks with the 'metadata' kind.
  4430. *
  4431. * @return {!Array.<TextTrack>}
  4432. * @private
  4433. */
  4434. getMetadataTracks_() {
  4435. goog.asserts.assert(this.video_.textTracks,
  4436. 'TextTracks should be valid.');
  4437. return Array.from(this.video_.textTracks)
  4438. .filter((t) => t.kind == 'metadata');
  4439. }
  4440. /**
  4441. * Get the TextTracks with the 'chapters' kind.
  4442. *
  4443. * @return {!Array.<TextTrack>}
  4444. * @private
  4445. */
  4446. getChaptersTracks_() {
  4447. goog.asserts.assert(this.video_.textTracks,
  4448. 'TextTracks should be valid.');
  4449. return Array.from(this.video_.textTracks)
  4450. .filter((t) => t.kind == 'chapters');
  4451. }
  4452. /**
  4453. * Enable or disable the text displayer. If the player is in an unloaded
  4454. * state, the request will be applied next time content is loaded.
  4455. *
  4456. * @param {boolean} isVisible
  4457. * @export
  4458. */
  4459. setTextTrackVisibility(isVisible) {
  4460. const oldVisibilty = this.isTextVisible_;
  4461. // Convert to boolean in case apps pass 0/1 instead false/true.
  4462. const newVisibility = !!isVisible;
  4463. if (oldVisibilty == newVisibility) {
  4464. return;
  4465. }
  4466. this.isTextVisible_ = newVisibility;
  4467. // Hold of on setting the text visibility until we have all the components
  4468. // we need. This ensures that they stay in-sync.
  4469. if (this.loadMode_ == shaka.Player.LoadMode.MEDIA_SOURCE) {
  4470. this.mediaSourceEngine_.getTextDisplayer()
  4471. .setTextVisibility(newVisibility);
  4472. // When the user wants to see captions, we stream captions. When the user
  4473. // doesn't want to see captions, we don't stream captions. This is to
  4474. // avoid bandwidth consumption by an unused resource. The app developer
  4475. // can override this and configure us to always stream captions.
  4476. if (!this.config_.streaming.alwaysStreamText) {
  4477. if (newVisibility) {
  4478. if (this.streamingEngine_.getCurrentTextStream()) {
  4479. // We already have a selected text stream.
  4480. } else {
  4481. // Find the text stream that best matches the user's preferences.
  4482. const streams =
  4483. shaka.util.StreamUtils.filterStreamsByLanguageAndRole(
  4484. this.manifest_.textStreams,
  4485. this.currentTextLanguage_,
  4486. this.currentTextRole_,
  4487. this.currentTextForced_);
  4488. // It is possible that there are no streams to play.
  4489. if (streams.length > 0) {
  4490. this.streamingEngine_.switchTextStream(streams[0]);
  4491. this.onTextChanged_();
  4492. }
  4493. }
  4494. } else {
  4495. this.streamingEngine_.unloadTextStream();
  4496. }
  4497. }
  4498. } else if (this.video_ && this.video_.src && this.video_.textTracks) {
  4499. const textTracks = this.getFilteredTextTracks_();
  4500. // Find the active track by looking for one which is not disabled. This
  4501. // is the only way to identify the track which is currently displayed.
  4502. // Set it to 'showing' or 'hidden' based on newVisibility.
  4503. for (const textTrack of textTracks) {
  4504. if (textTrack.mode != 'disabled') {
  4505. textTrack.mode = newVisibility ? 'showing' : 'hidden';
  4506. }
  4507. }
  4508. }
  4509. // We need to fire the event after we have updated everything so that
  4510. // everything will be in a stable state when the app responds to the
  4511. // event.
  4512. this.onTextTrackVisibility_();
  4513. }
  4514. /**
  4515. * Get the current playhead position as a date.
  4516. *
  4517. * @return {Date}
  4518. * @export
  4519. */
  4520. getPlayheadTimeAsDate() {
  4521. let presentationTime = 0;
  4522. if (this.playhead_) {
  4523. presentationTime = this.playhead_.getTime();
  4524. } else if (this.startTime_ == null) {
  4525. // A live stream with no requested start time and no playhead yet. We
  4526. // would start at the live edge, but we don't have that yet, so return
  4527. // the current date & time.
  4528. return new Date();
  4529. } else {
  4530. // A specific start time has been requested. This is what Playhead will
  4531. // use once it is created.
  4532. presentationTime = this.startTime_;
  4533. }
  4534. if (this.manifest_) {
  4535. const timeline = this.manifest_.presentationTimeline;
  4536. const startTime = timeline.getInitialProgramDateTime() ||
  4537. timeline.getPresentationStartTime();
  4538. return new Date(/* ms= */ (startTime + presentationTime) * 1000);
  4539. } else if (this.video_ && this.video_.getStartDate) {
  4540. // Apple's native HLS gives us getStartDate(), which is only available if
  4541. // EXT-X-PROGRAM-DATETIME is in the playlist.
  4542. const startDate = this.video_.getStartDate();
  4543. if (isNaN(startDate.getTime())) {
  4544. shaka.log.warning(
  4545. 'EXT-X-PROGRAM-DATETIME required to get playhead time as Date!');
  4546. return null;
  4547. }
  4548. return new Date(startDate.getTime() + (presentationTime * 1000));
  4549. } else {
  4550. shaka.log.warning('No way to get playhead time as Date!');
  4551. return null;
  4552. }
  4553. }
  4554. /**
  4555. * Get the presentation start time as a date.
  4556. *
  4557. * @return {Date}
  4558. * @export
  4559. */
  4560. getPresentationStartTimeAsDate() {
  4561. if (this.manifest_) {
  4562. const timeline = this.manifest_.presentationTimeline;
  4563. const startTime = timeline.getInitialProgramDateTime() ||
  4564. timeline.getPresentationStartTime();
  4565. goog.asserts.assert(startTime != null,
  4566. 'Presentation start time should not be null!');
  4567. return new Date(/* ms= */ startTime * 1000);
  4568. } else if (this.video_ && this.video_.getStartDate) {
  4569. // Apple's native HLS gives us getStartDate(), which is only available if
  4570. // EXT-X-PROGRAM-DATETIME is in the playlist.
  4571. const startDate = this.video_.getStartDate();
  4572. if (isNaN(startDate.getTime())) {
  4573. shaka.log.warning(
  4574. 'EXT-X-PROGRAM-DATETIME required to get presentation start time ' +
  4575. 'as Date!');
  4576. return null;
  4577. }
  4578. return startDate;
  4579. } else {
  4580. shaka.log.warning('No way to get presentation start time as Date!');
  4581. return null;
  4582. }
  4583. }
  4584. /**
  4585. * Get the presentation segment availability duration. This should only be
  4586. * called when the player has loaded a live stream. If the player has not
  4587. * loaded a live stream, this will return <code>null</code>.
  4588. *
  4589. * @return {?number}
  4590. * @export
  4591. */
  4592. getSegmentAvailabilityDuration() {
  4593. if (!this.isLive()) {
  4594. shaka.log.warning('getSegmentAvailabilityDuration is for live streams!');
  4595. return null;
  4596. }
  4597. if (this.manifest_) {
  4598. const timeline = this.manifest_.presentationTimeline;
  4599. return timeline.getSegmentAvailabilityDuration();
  4600. } else {
  4601. shaka.log.warning('No way to get segment segment availability duration!');
  4602. return null;
  4603. }
  4604. }
  4605. /**
  4606. * Get information about what the player has buffered. If the player has not
  4607. * loaded content or is currently loading content, the buffered content will
  4608. * be empty.
  4609. *
  4610. * @return {shaka.extern.BufferedInfo}
  4611. * @export
  4612. */
  4613. getBufferedInfo() {
  4614. if (this.loadMode_ == shaka.Player.LoadMode.MEDIA_SOURCE) {
  4615. return this.mediaSourceEngine_.getBufferedInfo();
  4616. }
  4617. const info = {
  4618. total: [],
  4619. audio: [],
  4620. video: [],
  4621. text: [],
  4622. };
  4623. if (this.loadMode_ == shaka.Player.LoadMode.SRC_EQUALS) {
  4624. const TimeRangesUtils = shaka.media.TimeRangesUtils;
  4625. info.total = TimeRangesUtils.getBufferedInfo(this.video_.buffered);
  4626. }
  4627. return info;
  4628. }
  4629. /**
  4630. * Get statistics for the current playback session. If the player is not
  4631. * playing content, this will return an empty stats object.
  4632. *
  4633. * @return {shaka.extern.Stats}
  4634. * @export
  4635. */
  4636. getStats() {
  4637. // If the Player is not in a fully-loaded state, then return an empty stats
  4638. // blob so that this call will never fail.
  4639. const loaded = this.loadMode_ == shaka.Player.LoadMode.MEDIA_SOURCE ||
  4640. this.loadMode_ == shaka.Player.LoadMode.SRC_EQUALS;
  4641. if (!loaded) {
  4642. return shaka.util.Stats.getEmptyBlob();
  4643. }
  4644. this.updateStateHistory_();
  4645. goog.asserts.assert(this.video_, 'If we have stats, we should have video_');
  4646. const element = /** @type {!HTMLVideoElement} */ (this.video_);
  4647. const completionRatio = element.currentTime / element.duration;
  4648. if (!isNaN(completionRatio)) {
  4649. this.stats_.setCompletionPercent(Math.round(100 * completionRatio));
  4650. }
  4651. if (this.playhead_) {
  4652. this.stats_.setGapsJumped(this.playhead_.getGapsJumped());
  4653. this.stats_.setStallsDetected(this.playhead_.getStallsDetected());
  4654. }
  4655. if (element.getVideoPlaybackQuality) {
  4656. const info = element.getVideoPlaybackQuality();
  4657. this.stats_.setDroppedFrames(
  4658. Number(info.droppedVideoFrames),
  4659. Number(info.totalVideoFrames));
  4660. this.stats_.setCorruptedFrames(Number(info.corruptedVideoFrames));
  4661. }
  4662. const licenseSeconds =
  4663. this.drmEngine_ ? this.drmEngine_.getLicenseTime() : NaN;
  4664. this.stats_.setLicenseTime(licenseSeconds);
  4665. if (this.loadMode_ == shaka.Player.LoadMode.MEDIA_SOURCE) {
  4666. // Event through we are loaded, it is still possible that we don't have a
  4667. // variant yet because we set the load mode before we select the first
  4668. // variant to stream.
  4669. const variant = this.streamingEngine_.getCurrentVariant();
  4670. const textStream = this.streamingEngine_.getCurrentTextStream();
  4671. if (variant) {
  4672. const rate = this.playRateController_ ?
  4673. this.playRateController_.getRealRate() : 1;
  4674. const variantBandwidth = rate * variant.bandwidth;
  4675. let currentStreamBandwidth = variantBandwidth;
  4676. if (textStream && textStream.bandwidth) {
  4677. currentStreamBandwidth += (rate * textStream.bandwidth);
  4678. }
  4679. this.stats_.setCurrentStreamBandwidth(currentStreamBandwidth);
  4680. }
  4681. if (variant && variant.video) {
  4682. this.stats_.setResolution(
  4683. /* width= */ variant.video.width || NaN,
  4684. /* height= */ variant.video.height || NaN);
  4685. }
  4686. if (this.isLive()) {
  4687. const now = this.getPresentationStartTimeAsDate().valueOf() +
  4688. element.currentTime * 1000;
  4689. const latency = (Date.now() - now) / 1000;
  4690. this.stats_.setLiveLatency(latency);
  4691. }
  4692. if (this.manifest_ && this.manifest_.presentationTimeline) {
  4693. const maxSegmentDuration =
  4694. this.manifest_.presentationTimeline.getMaxSegmentDuration();
  4695. this.stats_.setMaxSegmentDuration(maxSegmentDuration);
  4696. }
  4697. const estimate = this.abrManager_.getBandwidthEstimate();
  4698. this.stats_.setBandwidthEstimate(estimate);
  4699. }
  4700. if (this.loadMode_ == shaka.Player.LoadMode.SRC_EQUALS) {
  4701. this.stats_.setResolution(
  4702. /* width= */ element.videoWidth || NaN,
  4703. /* height= */ element.videoHeight || NaN);
  4704. }
  4705. return this.stats_.getBlob();
  4706. }
  4707. /**
  4708. * Adds the given text track to the loaded manifest. <code>load()</code> must
  4709. * resolve before calling. The presentation must have a duration.
  4710. *
  4711. * This returns the created track, which can immediately be selected by the
  4712. * application. The track will not be automatically selected.
  4713. *
  4714. * @param {string} uri
  4715. * @param {string} language
  4716. * @param {string} kind
  4717. * @param {string=} mimeType
  4718. * @param {string=} codec
  4719. * @param {string=} label
  4720. * @param {boolean=} forced
  4721. * @return {!Promise.<shaka.extern.Track>}
  4722. * @export
  4723. */
  4724. async addTextTrackAsync(uri, language, kind, mimeType, codec, label,
  4725. forced = false) {
  4726. if (this.loadMode_ != shaka.Player.LoadMode.MEDIA_SOURCE &&
  4727. this.loadMode_ != shaka.Player.LoadMode.SRC_EQUALS) {
  4728. shaka.log.error(
  4729. 'Must call load() and wait for it to resolve before adding text ' +
  4730. 'tracks.');
  4731. throw new shaka.util.Error(
  4732. shaka.util.Error.Severity.RECOVERABLE,
  4733. shaka.util.Error.Category.PLAYER,
  4734. shaka.util.Error.Code.CONTENT_NOT_LOADED);
  4735. }
  4736. if (kind != 'subtitles' && kind != 'captions') {
  4737. shaka.log.alwaysWarn(
  4738. 'Using a kind value different of `subtitles` or `captions` can ' +
  4739. 'cause unwanted issues.');
  4740. }
  4741. if (!mimeType) {
  4742. mimeType = await this.getTextMimetype_(uri);
  4743. }
  4744. let adCuePoints = [];
  4745. if (this.adManager_) {
  4746. adCuePoints = this.adManager_.getCuePoints();
  4747. }
  4748. if (this.loadMode_ == shaka.Player.LoadMode.SRC_EQUALS) {
  4749. if (forced) {
  4750. // See: https://github.com/whatwg/html/issues/4472
  4751. kind = 'forced';
  4752. }
  4753. await this.addSrcTrackElement_(uri, language, kind, mimeType, label || '',
  4754. adCuePoints);
  4755. const LanguageUtils = shaka.util.LanguageUtils;
  4756. const languageNormalized = LanguageUtils.normalize(language);
  4757. const textTracks = this.getTextTracks();
  4758. const srcTrack = textTracks.find((t) => {
  4759. return LanguageUtils.normalize(t.language) == languageNormalized &&
  4760. t.label == (label || '') &&
  4761. t.kind == kind;
  4762. });
  4763. if (srcTrack) {
  4764. this.onTracksChanged_();
  4765. return srcTrack;
  4766. }
  4767. // This should not happen, but there are browser implementations that may
  4768. // not support the Track element.
  4769. shaka.log.error('Cannot add this text when loaded with src=');
  4770. throw new shaka.util.Error(
  4771. shaka.util.Error.Severity.RECOVERABLE,
  4772. shaka.util.Error.Category.TEXT,
  4773. shaka.util.Error.Code.CANNOT_ADD_EXTERNAL_TEXT_TO_SRC_EQUALS);
  4774. }
  4775. const ContentType = shaka.util.ManifestParserUtils.ContentType;
  4776. let duration = this.video_.duration;
  4777. if (this.manifest_) {
  4778. duration = this.manifest_.presentationTimeline.getDuration();
  4779. }
  4780. if (duration == Infinity) {
  4781. throw new shaka.util.Error(
  4782. shaka.util.Error.Severity.RECOVERABLE,
  4783. shaka.util.Error.Category.MANIFEST,
  4784. shaka.util.Error.Code.CANNOT_ADD_EXTERNAL_TEXT_TO_LIVE_STREAM);
  4785. }
  4786. if (adCuePoints.length) {
  4787. goog.asserts.assert(
  4788. this.networkingEngine_, 'Need networking engine.');
  4789. const data = await this.getTextData_(uri,
  4790. this.networkingEngine_,
  4791. this.config_.streaming.retryParameters);
  4792. const vvtText = this.convertToWebVTT_(data, mimeType, adCuePoints);
  4793. const blob = new Blob([vvtText], {type: 'text/vtt'});
  4794. uri = shaka.media.MediaSourceEngine.createObjectURL(blob);
  4795. mimeType = 'text/vtt';
  4796. }
  4797. /** @type {shaka.extern.Stream} */
  4798. const stream = {
  4799. id: this.nextExternalStreamId_++,
  4800. originalId: null,
  4801. groupId: null,
  4802. createSegmentIndex: () => Promise.resolve(),
  4803. segmentIndex: shaka.media.SegmentIndex.forSingleSegment(
  4804. /* startTime= */ 0,
  4805. /* duration= */ duration,
  4806. /* uris= */ [uri]),
  4807. mimeType: mimeType || '',
  4808. codecs: codec || '',
  4809. kind: kind,
  4810. encrypted: false,
  4811. drmInfos: [],
  4812. keyIds: new Set(),
  4813. language: language,
  4814. originalLanguage: language,
  4815. label: label || null,
  4816. type: ContentType.TEXT,
  4817. primary: false,
  4818. trickModeVideo: null,
  4819. emsgSchemeIdUris: null,
  4820. roles: [],
  4821. forced: !!forced,
  4822. channelsCount: null,
  4823. audioSamplingRate: null,
  4824. spatialAudio: false,
  4825. closedCaptions: null,
  4826. accessibilityPurpose: null,
  4827. external: true,
  4828. fastSwitching: false,
  4829. fullMimeTypes: new Set([shaka.util.MimeUtils.getFullType(
  4830. mimeType || '', codec || '')]),
  4831. };
  4832. const fullMimeType = shaka.util.MimeUtils.getFullType(
  4833. stream.mimeType, stream.codecs);
  4834. const supported = shaka.text.TextEngine.isTypeSupported(fullMimeType);
  4835. if (!supported) {
  4836. throw new shaka.util.Error(
  4837. shaka.util.Error.Severity.CRITICAL,
  4838. shaka.util.Error.Category.TEXT,
  4839. shaka.util.Error.Code.MISSING_TEXT_PLUGIN,
  4840. mimeType);
  4841. }
  4842. this.manifest_.textStreams.push(stream);
  4843. this.onTracksChanged_();
  4844. return shaka.util.StreamUtils.textStreamToTrack(stream);
  4845. }
  4846. /**
  4847. * Adds the given thumbnails track to the loaded manifest.
  4848. * <code>load()</code> must resolve before calling. The presentation must
  4849. * have a duration.
  4850. *
  4851. * This returns the created track, which can immediately be used by the
  4852. * application.
  4853. *
  4854. * @param {string} uri
  4855. * @param {string=} mimeType
  4856. * @return {!Promise.<shaka.extern.Track>}
  4857. * @export
  4858. */
  4859. async addThumbnailsTrack(uri, mimeType) {
  4860. if (this.loadMode_ != shaka.Player.LoadMode.MEDIA_SOURCE &&
  4861. this.loadMode_ != shaka.Player.LoadMode.SRC_EQUALS) {
  4862. shaka.log.error(
  4863. 'Must call load() and wait for it to resolve before adding image ' +
  4864. 'tracks.');
  4865. throw new shaka.util.Error(
  4866. shaka.util.Error.Severity.RECOVERABLE,
  4867. shaka.util.Error.Category.PLAYER,
  4868. shaka.util.Error.Code.CONTENT_NOT_LOADED);
  4869. }
  4870. if (!mimeType) {
  4871. mimeType = await this.getTextMimetype_(uri);
  4872. }
  4873. if (mimeType != 'text/vtt') {
  4874. throw new shaka.util.Error(
  4875. shaka.util.Error.Severity.RECOVERABLE,
  4876. shaka.util.Error.Category.TEXT,
  4877. shaka.util.Error.Code.UNSUPPORTED_EXTERNAL_THUMBNAILS_URI,
  4878. uri);
  4879. }
  4880. const ContentType = shaka.util.ManifestParserUtils.ContentType;
  4881. let duration = this.video_.duration;
  4882. if (this.manifest_) {
  4883. duration = this.manifest_.presentationTimeline.getDuration();
  4884. }
  4885. if (duration == Infinity) {
  4886. throw new shaka.util.Error(
  4887. shaka.util.Error.Severity.RECOVERABLE,
  4888. shaka.util.Error.Category.MANIFEST,
  4889. shaka.util.Error.Code.CANNOT_ADD_EXTERNAL_THUMBNAILS_TO_LIVE_STREAM);
  4890. }
  4891. goog.asserts.assert(
  4892. this.networkingEngine_, 'Need networking engine.');
  4893. const buffer = await this.getTextData_(uri,
  4894. this.networkingEngine_,
  4895. this.config_.streaming.retryParameters);
  4896. const factory = shaka.text.TextEngine.findParser(mimeType);
  4897. if (!factory) {
  4898. throw new shaka.util.Error(
  4899. shaka.util.Error.Severity.CRITICAL,
  4900. shaka.util.Error.Category.TEXT,
  4901. shaka.util.Error.Code.MISSING_TEXT_PLUGIN,
  4902. mimeType);
  4903. }
  4904. const TextParser = factory();
  4905. const time = {
  4906. periodStart: 0,
  4907. segmentStart: 0,
  4908. segmentEnd: duration,
  4909. vttOffset: 0,
  4910. };
  4911. const data = shaka.util.BufferUtils.toUint8(buffer);
  4912. const cues = TextParser.parseMedia(data, time, uri);
  4913. const references = [];
  4914. for (const cue of cues) {
  4915. let uris = null;
  4916. const getUris = () => {
  4917. if (uris == null) {
  4918. uris = shaka.util.ManifestParserUtils.resolveUris(
  4919. [uri], [cue.payload]);
  4920. }
  4921. return uris || [];
  4922. };
  4923. const reference = new shaka.media.SegmentReference(
  4924. cue.startTime,
  4925. cue.endTime,
  4926. getUris,
  4927. /* startByte= */ 0,
  4928. /* endByte= */ null,
  4929. /* initSegmentReference= */ null,
  4930. /* timestampOffset= */ 0,
  4931. /* appendWindowStart= */ 0,
  4932. /* appendWindowEnd= */ Infinity,
  4933. );
  4934. if (cue.payload.includes('#xywh')) {
  4935. const spriteInfo = cue.payload.split('#xywh=')[1].split(',');
  4936. if (spriteInfo.length === 4) {
  4937. reference.setThumbnailSprite({
  4938. height: parseInt(spriteInfo[3], 10),
  4939. positionX: parseInt(spriteInfo[0], 10),
  4940. positionY: parseInt(spriteInfo[1], 10),
  4941. width: parseInt(spriteInfo[2], 10),
  4942. });
  4943. }
  4944. }
  4945. references.push(reference);
  4946. }
  4947. /** @type {shaka.extern.Stream} */
  4948. const stream = {
  4949. id: this.nextExternalStreamId_++,
  4950. originalId: null,
  4951. groupId: null,
  4952. createSegmentIndex: () => Promise.resolve(),
  4953. segmentIndex: new shaka.media.SegmentIndex(references),
  4954. mimeType: mimeType || '',
  4955. codecs: '',
  4956. kind: '',
  4957. encrypted: false,
  4958. drmInfos: [],
  4959. keyIds: new Set(),
  4960. language: 'und',
  4961. originalLanguage: null,
  4962. label: null,
  4963. type: ContentType.IMAGE,
  4964. primary: false,
  4965. trickModeVideo: null,
  4966. emsgSchemeIdUris: null,
  4967. roles: [],
  4968. forced: false,
  4969. channelsCount: null,
  4970. audioSamplingRate: null,
  4971. spatialAudio: false,
  4972. closedCaptions: null,
  4973. tilesLayout: '1x1',
  4974. accessibilityPurpose: null,
  4975. external: true,
  4976. fastSwitching: false,
  4977. fullMimeTypes: new Set([shaka.util.MimeUtils.getFullType(
  4978. mimeType || '', '')]),
  4979. };
  4980. if (this.loadMode_ == shaka.Player.LoadMode.SRC_EQUALS) {
  4981. this.externalSrcEqualsThumbnailsStreams_.push(stream);
  4982. } else {
  4983. this.manifest_.imageStreams.push(stream);
  4984. }
  4985. this.onTracksChanged_();
  4986. return shaka.util.StreamUtils.imageStreamToTrack(stream);
  4987. }
  4988. /**
  4989. * Adds the given chapters track to the loaded manifest. <code>load()</code>
  4990. * must resolve before calling. The presentation must have a duration.
  4991. *
  4992. * This returns the created track.
  4993. *
  4994. * @param {string} uri
  4995. * @param {string} language
  4996. * @param {string=} mimeType
  4997. * @return {!Promise.<shaka.extern.Track>}
  4998. * @export
  4999. */
  5000. async addChaptersTrack(uri, language, mimeType) {
  5001. if (this.loadMode_ != shaka.Player.LoadMode.MEDIA_SOURCE &&
  5002. this.loadMode_ != shaka.Player.LoadMode.SRC_EQUALS) {
  5003. shaka.log.error(
  5004. 'Must call load() and wait for it to resolve before adding ' +
  5005. 'chapters tracks.');
  5006. throw new shaka.util.Error(
  5007. shaka.util.Error.Severity.RECOVERABLE,
  5008. shaka.util.Error.Category.PLAYER,
  5009. shaka.util.Error.Code.CONTENT_NOT_LOADED);
  5010. }
  5011. if (!mimeType) {
  5012. mimeType = await this.getTextMimetype_(uri);
  5013. }
  5014. let adCuePoints = [];
  5015. if (this.adManager_) {
  5016. adCuePoints = this.adManager_.getCuePoints();
  5017. }
  5018. /** @type {!HTMLTrackElement} */
  5019. const trackElement = await this.addSrcTrackElement_(
  5020. uri, language, /* kind= */ 'chapters', mimeType, /* label= */ '',
  5021. adCuePoints);
  5022. const chaptersTracks = this.getChaptersTracks();
  5023. const chaptersTrack = chaptersTracks.find((t) => {
  5024. return t.language == language;
  5025. });
  5026. if (chaptersTrack) {
  5027. await new Promise((resolve, reject) => {
  5028. // The chapter data isn't available until the 'load' event fires, and
  5029. // that won't happen until the chapters track is activated by the
  5030. // activateChaptersTrack_ method.
  5031. this.loadEventManager_.listenOnce(trackElement, 'load', resolve);
  5032. this.loadEventManager_.listenOnce(trackElement, 'error', (event) => {
  5033. reject(new shaka.util.Error(
  5034. shaka.util.Error.Severity.RECOVERABLE,
  5035. shaka.util.Error.Category.TEXT,
  5036. shaka.util.Error.Code.CHAPTERS_TRACK_FAILED));
  5037. });
  5038. });
  5039. this.onTracksChanged_();
  5040. return chaptersTrack;
  5041. }
  5042. // This should not happen, but there are browser implementations that may
  5043. // not support the Track element.
  5044. shaka.log.error('Cannot add this text when loaded with src=');
  5045. throw new shaka.util.Error(
  5046. shaka.util.Error.Severity.RECOVERABLE,
  5047. shaka.util.Error.Category.TEXT,
  5048. shaka.util.Error.Code.CANNOT_ADD_EXTERNAL_TEXT_TO_SRC_EQUALS);
  5049. }
  5050. /**
  5051. * @param {string} uri
  5052. * @return {!Promise.<string>}
  5053. * @private
  5054. */
  5055. async getTextMimetype_(uri) {
  5056. let mimeType;
  5057. try {
  5058. goog.asserts.assert(
  5059. this.networkingEngine_, 'Need networking engine.');
  5060. // eslint-disable-next-line require-atomic-updates
  5061. mimeType = await shaka.net.NetworkingUtils.getMimeType(uri,
  5062. this.networkingEngine_,
  5063. this.config_.streaming.retryParameters);
  5064. } catch (error) {}
  5065. if (mimeType) {
  5066. return mimeType;
  5067. }
  5068. shaka.log.error(
  5069. 'The mimeType has not been provided and it could not be deduced ' +
  5070. 'from its uri.');
  5071. throw new shaka.util.Error(
  5072. shaka.util.Error.Severity.RECOVERABLE,
  5073. shaka.util.Error.Category.TEXT,
  5074. shaka.util.Error.Code.TEXT_COULD_NOT_GUESS_MIME_TYPE,
  5075. uri);
  5076. }
  5077. /**
  5078. * @param {string} uri
  5079. * @param {string} language
  5080. * @param {string} kind
  5081. * @param {string} mimeType
  5082. * @param {string} label
  5083. * @param {!Array.<!shaka.extern.AdCuePoint>} adCuePoints
  5084. * @return {!Promise.<!HTMLTrackElement>}
  5085. * @private
  5086. */
  5087. async addSrcTrackElement_(uri, language, kind, mimeType, label,
  5088. adCuePoints) {
  5089. if (mimeType != 'text/vtt' || adCuePoints.length) {
  5090. goog.asserts.assert(
  5091. this.networkingEngine_, 'Need networking engine.');
  5092. const data = await this.getTextData_(uri,
  5093. this.networkingEngine_,
  5094. this.config_.streaming.retryParameters);
  5095. const vvtText = this.convertToWebVTT_(data, mimeType, adCuePoints);
  5096. const blob = new Blob([vvtText], {type: 'text/vtt'});
  5097. uri = shaka.media.MediaSourceEngine.createObjectURL(blob);
  5098. mimeType = 'text/vtt';
  5099. }
  5100. const trackElement =
  5101. /** @type {!HTMLTrackElement} */(document.createElement('track'));
  5102. trackElement.src = this.cmcdManager_.appendTextTrackData(uri);
  5103. trackElement.label = label;
  5104. trackElement.kind = kind;
  5105. trackElement.srclang = language;
  5106. // Because we're pulling in the text track file via Javascript, the
  5107. // same-origin policy applies. If you'd like to have a player served
  5108. // from one domain, but the text track served from another, you'll
  5109. // need to enable CORS in order to do so. In addition to enabling CORS
  5110. // on the server serving the text tracks, you will need to add the
  5111. // crossorigin attribute to the video element itself.
  5112. if (!this.video_.getAttribute('crossorigin')) {
  5113. this.video_.setAttribute('crossorigin', 'anonymous');
  5114. }
  5115. this.video_.appendChild(trackElement);
  5116. return trackElement;
  5117. }
  5118. /**
  5119. * @param {string} uri
  5120. * @param {!shaka.net.NetworkingEngine} netEngine
  5121. * @param {shaka.extern.RetryParameters} retryParams
  5122. * @return {!Promise.<BufferSource>}
  5123. * @private
  5124. */
  5125. async getTextData_(uri, netEngine, retryParams) {
  5126. const type = shaka.net.NetworkingEngine.RequestType.SEGMENT;
  5127. const request = shaka.net.NetworkingEngine.makeRequest([uri], retryParams);
  5128. request.method = 'GET';
  5129. this.cmcdManager_.applyTextData(request);
  5130. const response = await netEngine.request(type, request).promise;
  5131. return response.data;
  5132. }
  5133. /**
  5134. * Converts an input string to a WebVTT format string.
  5135. *
  5136. * @param {BufferSource} buffer
  5137. * @param {string} mimeType
  5138. * @param {!Array.<!shaka.extern.AdCuePoint>} adCuePoints
  5139. * @return {string}
  5140. * @private
  5141. */
  5142. convertToWebVTT_(buffer, mimeType, adCuePoints) {
  5143. const factory = shaka.text.TextEngine.findParser(mimeType);
  5144. if (factory) {
  5145. const obj = factory();
  5146. const time = {
  5147. periodStart: 0,
  5148. segmentStart: 0,
  5149. segmentEnd: this.video_.duration,
  5150. vttOffset: 0,
  5151. };
  5152. const data = shaka.util.BufferUtils.toUint8(buffer);
  5153. const cues = obj.parseMedia(data, time, /* uri= */ null);
  5154. return shaka.text.WebVttGenerator.convert(cues, adCuePoints);
  5155. }
  5156. throw new shaka.util.Error(
  5157. shaka.util.Error.Severity.CRITICAL,
  5158. shaka.util.Error.Category.TEXT,
  5159. shaka.util.Error.Code.MISSING_TEXT_PLUGIN,
  5160. mimeType);
  5161. }
  5162. /**
  5163. * Set the maximum resolution that the platform's hardware can handle.
  5164. *
  5165. * @param {number} width
  5166. * @param {number} height
  5167. * @export
  5168. */
  5169. setMaxHardwareResolution(width, height) {
  5170. this.maxHwRes_.width = width;
  5171. this.maxHwRes_.height = height;
  5172. }
  5173. /**
  5174. * Retry streaming after a streaming failure has occurred. When the player has
  5175. * not loaded content or is loading content, this will be a no-op and will
  5176. * return <code>false</code>.
  5177. *
  5178. * <p>
  5179. * If the player has loaded content, and streaming has not seen an error, this
  5180. * will return <code>false</code>.
  5181. *
  5182. * <p>
  5183. * If the player has loaded content, and streaming seen an error, but the
  5184. * could not resume streaming, this will return <code>false</code>.
  5185. *
  5186. * @param {number=} retryDelaySeconds
  5187. * @return {boolean}
  5188. * @export
  5189. */
  5190. retryStreaming(retryDelaySeconds = 0.1) {
  5191. return this.loadMode_ == shaka.Player.LoadMode.MEDIA_SOURCE ?
  5192. this.streamingEngine_.retry(retryDelaySeconds) :
  5193. false;
  5194. }
  5195. /**
  5196. * Get the manifest that the player has loaded. If the player has not loaded
  5197. * any content, this will return <code>null</code>.
  5198. *
  5199. * NOTE: This structure is NOT covered by semantic versioning compatibility
  5200. * guarantees. It may change at any time!
  5201. *
  5202. * This is marked as deprecated to warn Closure Compiler users at compile-time
  5203. * to avoid using this method.
  5204. *
  5205. * @return {?shaka.extern.Manifest}
  5206. * @export
  5207. * @deprecated
  5208. */
  5209. getManifest() {
  5210. shaka.log.alwaysWarn(
  5211. 'Shaka Player\'s internal Manifest structure is NOT covered by ' +
  5212. 'semantic versioning compatibility guarantees. It may change at any ' +
  5213. 'time! Please consider filing a feature request for whatever you ' +
  5214. 'use getManifest() for.');
  5215. return this.manifest_;
  5216. }
  5217. /**
  5218. * Get the type of manifest parser that the player is using. If the player has
  5219. * not loaded any content, this will return <code>null</code>.
  5220. *
  5221. * @return {?shaka.extern.ManifestParser.Factory}
  5222. * @export
  5223. */
  5224. getManifestParserFactory() {
  5225. return this.parserFactory_;
  5226. }
  5227. /**
  5228. * @param {shaka.extern.Variant} variant
  5229. * @param {boolean} fromAdaptation
  5230. * @private
  5231. */
  5232. addVariantToSwitchHistory_(variant, fromAdaptation) {
  5233. const switchHistory = this.stats_.getSwitchHistory();
  5234. switchHistory.updateCurrentVariant(variant, fromAdaptation);
  5235. }
  5236. /**
  5237. * @param {shaka.extern.Stream} textStream
  5238. * @param {boolean} fromAdaptation
  5239. * @private
  5240. */
  5241. addTextStreamToSwitchHistory_(textStream, fromAdaptation) {
  5242. const switchHistory = this.stats_.getSwitchHistory();
  5243. switchHistory.updateCurrentText(textStream, fromAdaptation);
  5244. }
  5245. /**
  5246. * @return {shaka.extern.PlayerConfiguration}
  5247. * @private
  5248. */
  5249. defaultConfig_() {
  5250. const config = shaka.util.PlayerConfiguration.createDefault();
  5251. config.streaming.failureCallback = (error) => {
  5252. this.defaultStreamingFailureCallback_(error);
  5253. };
  5254. // Because this.video_ may not be set when the config is built, the default
  5255. // TextDisplay factory must capture a reference to "this".
  5256. config.textDisplayFactory = () => {
  5257. if (this.videoContainer_) {
  5258. const latestConfig = this.getConfiguration();
  5259. return new shaka.text.UITextDisplayer(
  5260. this.video_, this.videoContainer_, latestConfig.textDisplayer);
  5261. } else {
  5262. // eslint-disable-next-line no-restricted-syntax
  5263. if (HTMLMediaElement.prototype.addTextTrack) {
  5264. return new shaka.text.SimpleTextDisplayer(
  5265. this.video_, shaka.Player.TextTrackLabel);
  5266. } else {
  5267. shaka.log.warning('Text tracks are not supported by the ' +
  5268. 'browser, disabling.');
  5269. return new shaka.text.StubTextDisplayer();
  5270. }
  5271. }
  5272. };
  5273. return config;
  5274. }
  5275. /**
  5276. * Set the videoContainer to construct UITextDisplayer.
  5277. * @param {HTMLElement} videoContainer
  5278. * @export
  5279. */
  5280. setVideoContainer(videoContainer) {
  5281. this.videoContainer_ = videoContainer;
  5282. }
  5283. /**
  5284. * @param {!shaka.util.Error} error
  5285. * @private
  5286. */
  5287. defaultStreamingFailureCallback_(error) {
  5288. // For live streams, we retry streaming automatically for certain errors.
  5289. // For VOD streams, all streaming failures are fatal.
  5290. if (!this.isLive()) {
  5291. return;
  5292. }
  5293. let retryDelaySeconds = null;
  5294. if (error.code == shaka.util.Error.Code.BAD_HTTP_STATUS ||
  5295. error.code == shaka.util.Error.Code.HTTP_ERROR) {
  5296. // These errors can be near-instant, so delay a bit before retrying.
  5297. retryDelaySeconds = 1;
  5298. if (this.config_.streaming.lowLatencyMode) {
  5299. retryDelaySeconds = 0.1;
  5300. }
  5301. } else if (error.code == shaka.util.Error.Code.TIMEOUT) {
  5302. // We already waited for a timeout, so retry quickly.
  5303. retryDelaySeconds = 0.1;
  5304. }
  5305. if (retryDelaySeconds != null) {
  5306. error.severity = shaka.util.Error.Severity.RECOVERABLE;
  5307. shaka.log.warning('Live streaming error. Retrying automatically...');
  5308. this.retryStreaming(retryDelaySeconds);
  5309. }
  5310. }
  5311. /**
  5312. * For CEA closed captions embedded in the video streams, create dummy text
  5313. * stream. This can be safely called again on existing manifests, for
  5314. * manifest updates.
  5315. * @param {!shaka.extern.Manifest} manifest
  5316. * @private
  5317. */
  5318. makeTextStreamsForClosedCaptions_(manifest) {
  5319. const ContentType = shaka.util.ManifestParserUtils.ContentType;
  5320. const TextStreamKind = shaka.util.ManifestParserUtils.TextStreamKind;
  5321. const CEA608_MIME = shaka.util.MimeUtils.CEA608_CLOSED_CAPTION_MIMETYPE;
  5322. const CEA708_MIME = shaka.util.MimeUtils.CEA708_CLOSED_CAPTION_MIMETYPE;
  5323. // A set, to make sure we don't create two text streams for the same video.
  5324. const closedCaptionsSet = new Set();
  5325. for (const textStream of manifest.textStreams) {
  5326. if (textStream.mimeType == CEA608_MIME ||
  5327. textStream.mimeType == CEA708_MIME) {
  5328. // This function might be called on a manifest update, so don't make a
  5329. // new text stream for closed caption streams we have seen before.
  5330. closedCaptionsSet.add(textStream.originalId);
  5331. }
  5332. }
  5333. for (const variant of manifest.variants) {
  5334. const video = variant.video;
  5335. if (video && video.closedCaptions) {
  5336. for (const id of video.closedCaptions.keys()) {
  5337. if (!closedCaptionsSet.has(id)) {
  5338. const mimeType = id.startsWith('CC') ? CEA608_MIME : CEA708_MIME;
  5339. // Add an empty segmentIndex, for the benefit of the period combiner
  5340. // in our builtin DASH parser.
  5341. const segmentIndex = new shaka.media.MetaSegmentIndex();
  5342. const language = video.closedCaptions.get(id);
  5343. const textStream = {
  5344. id: this.nextExternalStreamId_++, // A globally unique ID.
  5345. originalId: id, // The CC ID string, like 'CC1', 'CC3', etc.
  5346. groupId: null,
  5347. createSegmentIndex: () => Promise.resolve(),
  5348. segmentIndex,
  5349. mimeType,
  5350. codecs: '',
  5351. kind: TextStreamKind.CLOSED_CAPTION,
  5352. encrypted: false,
  5353. drmInfos: [],
  5354. keyIds: new Set(),
  5355. language,
  5356. originalLanguage: language,
  5357. label: null,
  5358. type: ContentType.TEXT,
  5359. primary: false,
  5360. trickModeVideo: null,
  5361. emsgSchemeIdUris: null,
  5362. roles: video.roles,
  5363. forced: false,
  5364. channelsCount: null,
  5365. audioSamplingRate: null,
  5366. spatialAudio: false,
  5367. closedCaptions: null,
  5368. accessibilityPurpose: null,
  5369. external: false,
  5370. fastSwitching: false,
  5371. fullMimeTypes: new Set([shaka.util.MimeUtils.getFullType(
  5372. mimeType, '')]),
  5373. };
  5374. manifest.textStreams.push(textStream);
  5375. closedCaptionsSet.add(id);
  5376. }
  5377. }
  5378. }
  5379. }
  5380. }
  5381. /**
  5382. * @param {shaka.extern.Variant} initialVariant
  5383. * @param {number} time
  5384. * @return {!Promise.<number>}
  5385. * @private
  5386. */
  5387. async adjustStartTime_(initialVariant, time) {
  5388. /** @type {?shaka.extern.Stream} */
  5389. const activeAudio = initialVariant.audio;
  5390. /** @type {?shaka.extern.Stream} */
  5391. const activeVideo = initialVariant.video;
  5392. /**
  5393. * @param {?shaka.extern.Stream} stream
  5394. * @param {number} time
  5395. * @return {!Promise.<?number>}
  5396. */
  5397. const getAdjustedTime = async (stream, time) => {
  5398. if (!stream) {
  5399. return null;
  5400. }
  5401. await stream.createSegmentIndex();
  5402. const iter = stream.segmentIndex.getIteratorForTime(time);
  5403. const ref = iter ? iter.next().value : null;
  5404. if (!ref) {
  5405. return null;
  5406. }
  5407. const refTime = ref.startTime;
  5408. goog.asserts.assert(refTime <= time,
  5409. 'Segment should start before target time!');
  5410. return refTime;
  5411. };
  5412. const audioStartTime = await getAdjustedTime(activeAudio, time);
  5413. const videoStartTime = await getAdjustedTime(activeVideo, time);
  5414. // If we have both video and audio times, pick the larger one. If we picked
  5415. // the smaller one, that one will download an entire segment to buffer the
  5416. // difference.
  5417. if (videoStartTime != null && audioStartTime != null) {
  5418. return Math.max(videoStartTime, audioStartTime);
  5419. } else if (videoStartTime != null) {
  5420. return videoStartTime;
  5421. } else if (audioStartTime != null) {
  5422. return audioStartTime;
  5423. } else {
  5424. return time;
  5425. }
  5426. }
  5427. /**
  5428. * Update the buffering state to be either "we are buffering" or "we are not
  5429. * buffering", firing events to the app as needed.
  5430. *
  5431. * @private
  5432. */
  5433. updateBufferState_() {
  5434. const isBuffering = this.isBuffering();
  5435. shaka.log.v2('Player changing buffering state to', isBuffering);
  5436. // Make sure we have all the components we need before we consider ourselves
  5437. // as being loaded.
  5438. // TODO: Make the check for "loaded" simpler.
  5439. const loaded = this.stats_ && this.bufferObserver_ && this.playhead_;
  5440. if (loaded) {
  5441. this.playRateController_.setBuffering(isBuffering);
  5442. if (this.cmcdManager_) {
  5443. this.cmcdManager_.setBuffering(isBuffering);
  5444. }
  5445. this.updateStateHistory_();
  5446. }
  5447. // Surface the buffering event so that the app knows if/when we are
  5448. // buffering.
  5449. const eventName = shaka.util.FakeEvent.EventName.Buffering;
  5450. const data = (new Map()).set('buffering', isBuffering);
  5451. this.dispatchEvent(shaka.Player.makeEvent_(eventName, data));
  5452. }
  5453. /**
  5454. * A callback for when the playback rate changes. We need to watch the
  5455. * playback rate so that if the playback rate on the media element changes
  5456. * (that was not caused by our play rate controller) we can notify the
  5457. * controller so that it can stay in-sync with the change.
  5458. *
  5459. * @private
  5460. */
  5461. onRateChange_() {
  5462. /** @type {number} */
  5463. const newRate = this.video_.playbackRate;
  5464. // On Edge, when someone seeks using the native controls, it will set the
  5465. // playback rate to zero until they finish seeking, after which it will
  5466. // return the playback rate.
  5467. //
  5468. // If the playback rate changes while seeking, Edge will cache the playback
  5469. // rate and use it after seeking.
  5470. //
  5471. // https://github.com/shaka-project/shaka-player/issues/951
  5472. if (newRate == 0) {
  5473. return;
  5474. }
  5475. if (this.playRateController_) {
  5476. // The playback rate has changed. This could be us or someone else.
  5477. // If this was us, setting the rate again will be a no-op.
  5478. this.playRateController_.set(newRate);
  5479. }
  5480. const event = shaka.Player.makeEvent_(
  5481. shaka.util.FakeEvent.EventName.RateChange);
  5482. this.dispatchEvent(event);
  5483. }
  5484. /**
  5485. * Try updating the state history. If the player has not finished
  5486. * initializing, this will be a no-op.
  5487. *
  5488. * @private
  5489. */
  5490. updateStateHistory_() {
  5491. // If we have not finish initializing, this will be a no-op.
  5492. if (!this.stats_) {
  5493. return;
  5494. }
  5495. if (!this.bufferObserver_) {
  5496. return;
  5497. }
  5498. const State = shaka.media.BufferingObserver.State;
  5499. const history = this.stats_.getStateHistory();
  5500. let updateState = 'playing';
  5501. if (this.bufferObserver_.getState() == State.STARVING) {
  5502. updateState = 'buffering';
  5503. } else if (this.video_.paused) {
  5504. updateState = 'paused';
  5505. } else if (this.video_.ended) {
  5506. updateState = 'ended';
  5507. }
  5508. const stateChanged = history.update(updateState);
  5509. if (stateChanged) {
  5510. const eventName = shaka.util.FakeEvent.EventName.StateChanged;
  5511. const data = (new Map()).set('newstate', updateState);
  5512. this.dispatchEvent(shaka.Player.makeEvent_(eventName, data));
  5513. }
  5514. }
  5515. /**
  5516. * Callback for liveSync and vodDynamicPlaybackRate
  5517. *
  5518. * @private
  5519. */
  5520. onTimeUpdate_() {
  5521. const playbackRate = this.video_.playbackRate;
  5522. const isLive = this.isLive();
  5523. if (this.config_.streaming.vodDynamicPlaybackRate && !isLive) {
  5524. const minPlaybackRate =
  5525. this.config_.streaming.vodDynamicPlaybackRateLowBufferRate;
  5526. const bufferFullness = this.getBufferFullness();
  5527. const bufferThreshold =
  5528. this.config_.streaming.vodDynamicPlaybackRateBufferRatio;
  5529. if (bufferFullness <= bufferThreshold) {
  5530. if (playbackRate != minPlaybackRate) {
  5531. shaka.log.debug('Buffer fullness ratio (' + bufferFullness + ') ' +
  5532. 'is less than the vodDynamicPlaybackRateBufferRatio (' +
  5533. bufferThreshold + '). Updating playbackRate to ' + minPlaybackRate);
  5534. this.trickPlay(minPlaybackRate);
  5535. }
  5536. } else if (bufferFullness == 1) {
  5537. if (playbackRate !== this.playRateController_.getDefaultRate()) {
  5538. shaka.log.debug('Buffer is full. Cancel trick play.');
  5539. this.cancelTrickPlay();
  5540. }
  5541. }
  5542. }
  5543. // If the live stream has reached its end, do not sync.
  5544. if (!isLive) {
  5545. return;
  5546. }
  5547. const seekRange = this.seekRange();
  5548. if (!Number.isFinite(seekRange.end)) {
  5549. return;
  5550. }
  5551. const currentTime = this.video_.currentTime;
  5552. if (currentTime < seekRange.start) {
  5553. // Bad stream?
  5554. return;
  5555. }
  5556. let liveSyncMaxLatency;
  5557. let liveSyncPlaybackRate;
  5558. if (this.config_.streaming.liveSync) {
  5559. liveSyncMaxLatency = this.config_.streaming.liveSyncMaxLatency;
  5560. liveSyncPlaybackRate = this.config_.streaming.liveSyncPlaybackRate;
  5561. } else {
  5562. // serviceDescription must override if it is defined in the MPD and
  5563. // liveSync configuration is not set.
  5564. if (this.manifest_ && this.manifest_.serviceDescription) {
  5565. liveSyncMaxLatency = this.config_.streaming.liveSyncMaxLatency;
  5566. if (this.manifest_.serviceDescription.targetLatency != null) {
  5567. liveSyncMaxLatency =
  5568. this.manifest_.serviceDescription.targetLatency +
  5569. this.config_.streaming.liveSyncTargetLatencyTolerance;
  5570. } else if (this.manifest_.serviceDescription.maxLatency != null) {
  5571. liveSyncMaxLatency = this.manifest_.serviceDescription.maxLatency;
  5572. }
  5573. liveSyncPlaybackRate =
  5574. this.manifest_.serviceDescription.maxPlaybackRate ||
  5575. this.config_.streaming.liveSyncPlaybackRate;
  5576. }
  5577. }
  5578. let liveSyncMinLatency;
  5579. let liveSyncMinPlaybackRate;
  5580. if (this.config_.streaming.liveSync) {
  5581. liveSyncMinLatency = this.config_.streaming.liveSyncMinLatency;
  5582. liveSyncMinPlaybackRate = this.config_.streaming.liveSyncMinPlaybackRate;
  5583. } else {
  5584. // serviceDescription must override if it is defined in the MPD and
  5585. // liveSync configuration is not set.
  5586. if (this.manifest_ && this.manifest_.serviceDescription) {
  5587. liveSyncMinLatency = this.config_.streaming.liveSyncMinLatency;
  5588. if (this.manifest_.serviceDescription.targetLatency != null) {
  5589. liveSyncMinLatency =
  5590. this.manifest_.serviceDescription.targetLatency -
  5591. this.config_.streaming.liveSyncTargetLatencyTolerance;
  5592. } else if (this.manifest_.serviceDescription.minLatency != null) {
  5593. liveSyncMinLatency = this.manifest_.serviceDescription.minLatency;
  5594. }
  5595. liveSyncMinPlaybackRate =
  5596. this.manifest_.serviceDescription.minPlaybackRate ||
  5597. this.config_.streaming.liveSyncMinPlaybackRate;
  5598. }
  5599. }
  5600. const latency = seekRange.end - this.video_.currentTime;
  5601. let offset = 0;
  5602. // In src= mode, the seek range isn't updated frequently enough, so we need
  5603. // to fudge the latency number with an offset. The playback rate is used
  5604. // as an offset, since that is the amount we catch up 1 second of
  5605. // accelerated playback.
  5606. if (this.loadMode_ == shaka.Player.LoadMode.SRC_EQUALS) {
  5607. const buffered = this.video_.buffered;
  5608. if (buffered.length > 0) {
  5609. const bufferedEnd = buffered.end(buffered.length - 1);
  5610. offset = Math.max(liveSyncPlaybackRate, bufferedEnd - seekRange.end);
  5611. }
  5612. }
  5613. const panicMode = this.config_.streaming.liveSyncPanicMode;
  5614. const panicThreshold = this.config_.streaming.liveSyncPanicThreshold * 1000;
  5615. const timeSinceLastRebuffer =
  5616. Date.now() - this.bufferObserver_.getLastRebufferTime();
  5617. if (panicMode && !liveSyncMinPlaybackRate) {
  5618. liveSyncMinPlaybackRate = this.config_.streaming.liveSyncMinPlaybackRate;
  5619. }
  5620. if (panicMode && liveSyncMinPlaybackRate &&
  5621. timeSinceLastRebuffer <= panicThreshold) {
  5622. if (playbackRate != liveSyncMinPlaybackRate) {
  5623. shaka.log.debug('Time since last rebuffer (' +
  5624. timeSinceLastRebuffer + 's) ' +
  5625. 'is less than the liveSyncPanicThreshold (' + panicThreshold +
  5626. 's). Updating playbackRate to ' + liveSyncMinPlaybackRate);
  5627. this.trickPlay(liveSyncMinPlaybackRate);
  5628. }
  5629. } else if (liveSyncMaxLatency && liveSyncPlaybackRate &&
  5630. (latency - offset) > liveSyncMaxLatency) {
  5631. if (playbackRate != liveSyncPlaybackRate) {
  5632. shaka.log.debug('Latency (' + latency + 's) ' +
  5633. 'is greater than liveSyncMaxLatency (' + liveSyncMaxLatency + 's). ' +
  5634. 'Updating playbackRate to ' + liveSyncPlaybackRate);
  5635. this.trickPlay(liveSyncPlaybackRate);
  5636. }
  5637. } else if (liveSyncMinLatency && liveSyncMinPlaybackRate &&
  5638. (latency - offset) < liveSyncMinLatency) {
  5639. if (playbackRate != liveSyncMinPlaybackRate) {
  5640. shaka.log.debug('Latency (' + latency + 's) ' +
  5641. 'is smaller than liveSyncMinLatency (' + liveSyncMinLatency + 's). ' +
  5642. 'Updating playbackRate to ' + liveSyncMinPlaybackRate);
  5643. this.trickPlay(liveSyncMinPlaybackRate);
  5644. }
  5645. } else if (playbackRate !== this.playRateController_.getDefaultRate()) {
  5646. this.cancelTrickPlay();
  5647. }
  5648. }
  5649. /**
  5650. * Callback for video progress events
  5651. *
  5652. * @private
  5653. */
  5654. onVideoProgress_() {
  5655. if (!this.video_) {
  5656. return;
  5657. }
  5658. let hasNewCompletionPercent = false;
  5659. const completionRatio = this.video_.currentTime / this.video_.duration;
  5660. if (!isNaN(completionRatio)) {
  5661. const percent = Math.round(100 * completionRatio);
  5662. if (isNaN(this.completionPercent_)) {
  5663. this.completionPercent_ = percent;
  5664. hasNewCompletionPercent = true;
  5665. } else {
  5666. const newCompletionPercent = Math.max(this.completionPercent_, percent);
  5667. if (this.completionPercent_ != newCompletionPercent) {
  5668. this.completionPercent_ = newCompletionPercent;
  5669. hasNewCompletionPercent = true;
  5670. }
  5671. }
  5672. }
  5673. if (hasNewCompletionPercent) {
  5674. let event;
  5675. if (this.completionPercent_ == 0) {
  5676. event = shaka.Player.makeEvent_(shaka.util.FakeEvent.EventName.Started);
  5677. } else if (this.completionPercent_ == 25) {
  5678. event = shaka.Player.makeEvent_(
  5679. shaka.util.FakeEvent.EventName.FirstQuartile);
  5680. } else if (this.completionPercent_ == 50) {
  5681. event = shaka.Player.makeEvent_(
  5682. shaka.util.FakeEvent.EventName.Midpoint);
  5683. } else if (this.completionPercent_ == 75) {
  5684. event = shaka.Player.makeEvent_(
  5685. shaka.util.FakeEvent.EventName.ThirdQuartile);
  5686. } else if (this.completionPercent_ == 100) {
  5687. event = shaka.Player.makeEvent_(
  5688. shaka.util.FakeEvent.EventName.Complete);
  5689. }
  5690. if (event) {
  5691. this.dispatchEvent(event);
  5692. }
  5693. }
  5694. }
  5695. /**
  5696. * Callback from Playhead.
  5697. *
  5698. * @private
  5699. */
  5700. onSeek_() {
  5701. if (this.playheadObservers_) {
  5702. this.playheadObservers_.notifyOfSeek();
  5703. }
  5704. if (this.streamingEngine_) {
  5705. this.streamingEngine_.seeked();
  5706. }
  5707. if (this.bufferObserver_) {
  5708. // If we seek into an unbuffered range, we should fire a 'buffering' event
  5709. // immediately. If StreamingEngine can buffer fast enough, we may not
  5710. // update our buffering tracking otherwise.
  5711. this.pollBufferState_();
  5712. }
  5713. }
  5714. /**
  5715. * Update AbrManager with variants while taking into account restrictions,
  5716. * preferences, and ABR.
  5717. *
  5718. * On error, this dispatches an error event and returns false.
  5719. *
  5720. * @return {boolean} True if successful.
  5721. * @private
  5722. */
  5723. updateAbrManagerVariants_() {
  5724. try {
  5725. goog.asserts.assert(this.manifest_, 'Manifest should exist by now!');
  5726. this.manifestFilterer_.checkRestrictedVariants(this.manifest_);
  5727. } catch (e) {
  5728. this.onError_(e);
  5729. return false;
  5730. }
  5731. const playableVariants = shaka.util.StreamUtils.getPlayableVariants(
  5732. this.manifest_.variants);
  5733. // Update the abr manager with newly filtered variants.
  5734. const adaptationSet = this.currentAdaptationSetCriteria_.create(
  5735. playableVariants);
  5736. this.abrManager_.setVariants(Array.from(adaptationSet.values()));
  5737. return true;
  5738. }
  5739. /**
  5740. * Chooses a variant from all possible variants while taking into account
  5741. * restrictions, preferences, and ABR.
  5742. *
  5743. * On error, this dispatches an error event and returns null.
  5744. *
  5745. * @param {boolean=} initialSelection
  5746. * @return {?shaka.extern.Variant}
  5747. * @private
  5748. */
  5749. chooseVariant_(initialSelection = false) {
  5750. if (this.updateAbrManagerVariants_()) {
  5751. return this.abrManager_.chooseVariant(initialSelection);
  5752. } else {
  5753. return null;
  5754. }
  5755. }
  5756. /**
  5757. * Checks to re-enable variants that were temporarily disabled due to network
  5758. * errors. If any variants are enabled this way, a new variant may be chosen
  5759. * for playback.
  5760. * @private
  5761. */
  5762. checkVariants_() {
  5763. goog.asserts.assert(this.manifest_, 'Should have manifest!');
  5764. const now = Date.now() / 1000;
  5765. let hasVariantUpdate = false;
  5766. /** @type {function(shaka.extern.Variant):string} */
  5767. const streamsAsString = (variant) => {
  5768. let str = '';
  5769. if (variant.video) {
  5770. str += 'video:' + variant.video.id;
  5771. }
  5772. if (variant.audio) {
  5773. str += str ? '&' : '';
  5774. str += 'audio:' + variant.audio.id;
  5775. }
  5776. return str;
  5777. };
  5778. for (const variant of this.manifest_.variants) {
  5779. if (variant.disabledUntilTime > 0 && variant.disabledUntilTime <= now) {
  5780. variant.disabledUntilTime = 0;
  5781. hasVariantUpdate = true;
  5782. shaka.log.v2('Re-enabled variant with ' + streamsAsString(variant));
  5783. }
  5784. }
  5785. const shouldStopTimer = this.manifest_.variants.every((variant) => {
  5786. goog.asserts.assert(
  5787. variant.disabledUntilTime >= 0,
  5788. '|variant.disableTimeUntilTime| must always be >= 0');
  5789. return variant.disabledUntilTime === 0;
  5790. });
  5791. if (shouldStopTimer) {
  5792. this.checkVariantsTimer_.stop();
  5793. }
  5794. if (hasVariantUpdate) {
  5795. // Reconsider re-enabled variant for ABR switching.
  5796. this.chooseVariantAndSwitch_(
  5797. /* clearBuffer= */ true, /* safeMargin= */ undefined,
  5798. /* force= */ false, /* fromAdaptation= */ false);
  5799. }
  5800. }
  5801. /**
  5802. * Choose a text stream from all possible text streams while taking into
  5803. * account user preference.
  5804. *
  5805. * @return {?shaka.extern.Stream}
  5806. * @private
  5807. */
  5808. chooseTextStream_() {
  5809. const subset = shaka.util.StreamUtils.filterStreamsByLanguageAndRole(
  5810. this.manifest_.textStreams,
  5811. this.currentTextLanguage_,
  5812. this.currentTextRole_,
  5813. this.currentTextForced_);
  5814. return subset[0] || null;
  5815. }
  5816. /**
  5817. * Chooses a new Variant. If the new variant differs from the old one, it
  5818. * adds the new one to the switch history and switches to it.
  5819. *
  5820. * Called after a config change, a key status event, or an explicit language
  5821. * change.
  5822. *
  5823. * @param {boolean=} clearBuffer Optional clear buffer or not when
  5824. * switch to new variant
  5825. * Defaults to true if not provided
  5826. * @param {number=} safeMargin Optional amount of buffer (in seconds) to
  5827. * retain when clearing the buffer.
  5828. * Defaults to 0 if not provided. Ignored if clearBuffer is false.
  5829. * @private
  5830. */
  5831. chooseVariantAndSwitch_(clearBuffer = true, safeMargin = 0, force = false,
  5832. fromAdaptation = true) {
  5833. goog.asserts.assert(this.config_, 'Must not be destroyed');
  5834. // Because we're running this after a config change (manual language
  5835. // change) or a key status event, it is always okay to clear the buffer
  5836. // here.
  5837. const chosenVariant = this.chooseVariant_();
  5838. if (chosenVariant) {
  5839. this.switchVariant_(chosenVariant, fromAdaptation,
  5840. clearBuffer, safeMargin, force);
  5841. }
  5842. }
  5843. /**
  5844. * @param {shaka.extern.Variant} variant
  5845. * @param {boolean} fromAdaptation
  5846. * @param {boolean} clearBuffer
  5847. * @param {number} safeMargin
  5848. * @param {boolean=} force
  5849. * @private
  5850. */
  5851. switchVariant_(variant, fromAdaptation, clearBuffer, safeMargin,
  5852. force = false) {
  5853. const currentVariant = this.streamingEngine_.getCurrentVariant();
  5854. if (variant == currentVariant) {
  5855. shaka.log.debug('Variant already selected.');
  5856. // If you want to clear the buffer, we force to reselect the same variant.
  5857. // We don't need to reset the timestampOffset since it's the same variant,
  5858. // so 'adaptation' isn't passed here.
  5859. if (clearBuffer) {
  5860. this.streamingEngine_.switchVariant(variant, clearBuffer, safeMargin,
  5861. /* force= */ true);
  5862. }
  5863. return;
  5864. }
  5865. // Add entries to the history.
  5866. this.addVariantToSwitchHistory_(variant, fromAdaptation);
  5867. this.streamingEngine_.switchVariant(
  5868. variant, clearBuffer, safeMargin, force,
  5869. /* adaptation= */ fromAdaptation);
  5870. let oldTrack = null;
  5871. if (currentVariant) {
  5872. oldTrack = shaka.util.StreamUtils.variantToTrack(currentVariant);
  5873. }
  5874. const newTrack = shaka.util.StreamUtils.variantToTrack(variant);
  5875. if (fromAdaptation) {
  5876. // Dispatch an 'adaptation' event
  5877. this.onAdaptation_(oldTrack, newTrack);
  5878. } else {
  5879. // Dispatch a 'variantchanged' event
  5880. this.onVariantChanged_(oldTrack, newTrack);
  5881. }
  5882. }
  5883. /**
  5884. * @param {AudioTrack} track
  5885. * @private
  5886. */
  5887. switchHtml5Track_(track) {
  5888. goog.asserts.assert(this.video_ && this.video_.audioTracks,
  5889. 'Video and video.audioTracks should not be null!');
  5890. const audioTracks = Array.from(this.video_.audioTracks);
  5891. const currentTrack = audioTracks.find((t) => t.enabled);
  5892. // This will reset the "enabled" of other tracks to false.
  5893. track.enabled = true;
  5894. if (!currentTrack) {
  5895. return;
  5896. }
  5897. // AirPlay does not reset the "enabled" of other tracks to false, so
  5898. // it must be changed by hand.
  5899. if (track.id !== currentTrack.id) {
  5900. currentTrack.enabled = false;
  5901. }
  5902. const oldTrack =
  5903. shaka.util.StreamUtils.html5AudioTrackToTrack(currentTrack);
  5904. const newTrack =
  5905. shaka.util.StreamUtils.html5AudioTrackToTrack(track);
  5906. this.onVariantChanged_(oldTrack, newTrack);
  5907. }
  5908. /**
  5909. * Decide during startup if text should be streamed/shown.
  5910. * @private
  5911. */
  5912. setInitialTextState_(initialVariant, initialTextStream) {
  5913. // Check if we should show text (based on difference between audio and text
  5914. // languages).
  5915. if (initialTextStream) {
  5916. if (initialVariant.audio && this.shouldInitiallyShowText_(
  5917. initialVariant.audio, initialTextStream)) {
  5918. this.isTextVisible_ = true;
  5919. }
  5920. if (this.isTextVisible_) {
  5921. // If the cached value says to show text, then update the text displayer
  5922. // since it defaults to not shown.
  5923. this.mediaSourceEngine_.getTextDisplayer().setTextVisibility(true);
  5924. goog.asserts.assert(this.shouldStreamText_(),
  5925. 'Should be streaming text');
  5926. }
  5927. this.onTextTrackVisibility_();
  5928. } else {
  5929. this.isTextVisible_ = false;
  5930. }
  5931. }
  5932. /**
  5933. * Check if we should show text on screen automatically.
  5934. *
  5935. * @param {shaka.extern.Stream} audioStream
  5936. * @param {shaka.extern.Stream} textStream
  5937. * @return {boolean}
  5938. * @private
  5939. */
  5940. shouldInitiallyShowText_(audioStream, textStream) {
  5941. const AutoShowText = shaka.config.AutoShowText;
  5942. if (this.config_.autoShowText == AutoShowText.NEVER) {
  5943. return false;
  5944. }
  5945. if (this.config_.autoShowText == AutoShowText.ALWAYS) {
  5946. return true;
  5947. }
  5948. const LanguageUtils = shaka.util.LanguageUtils;
  5949. /** @type {string} */
  5950. const preferredTextLocale =
  5951. LanguageUtils.normalize(this.config_.preferredTextLanguage);
  5952. /** @type {string} */
  5953. const textLocale = LanguageUtils.normalize(textStream.language);
  5954. if (this.config_.autoShowText == AutoShowText.IF_PREFERRED_TEXT_LANGUAGE) {
  5955. // Only the text language match matters.
  5956. return LanguageUtils.areLanguageCompatible(
  5957. textLocale,
  5958. preferredTextLocale);
  5959. }
  5960. if (this.config_.autoShowText == AutoShowText.IF_SUBTITLES_MAY_BE_NEEDED) {
  5961. /* The text should automatically be shown if the text is
  5962. * language-compatible with the user's text language preference, but not
  5963. * compatible with the audio. These are cases where we deduce that
  5964. * subtitles may be needed.
  5965. *
  5966. * For example:
  5967. * preferred | chosen | chosen |
  5968. * text | text | audio | show
  5969. * -----------------------------------
  5970. * en-CA | en | jp | true
  5971. * en | en-US | fr | true
  5972. * fr-CA | en-US | jp | false
  5973. * en-CA | en-US | en-US | false
  5974. *
  5975. */
  5976. /** @type {string} */
  5977. const audioLocale = LanguageUtils.normalize(audioStream.language);
  5978. return (
  5979. LanguageUtils.areLanguageCompatible(textLocale, preferredTextLocale) &&
  5980. !LanguageUtils.areLanguageCompatible(audioLocale, textLocale));
  5981. }
  5982. shaka.log.alwaysWarn('Invalid autoShowText setting!');
  5983. return false;
  5984. }
  5985. /**
  5986. * Callback from StreamingEngine.
  5987. *
  5988. * @private
  5989. */
  5990. onManifestUpdate_() {
  5991. if (this.parser_ && this.parser_.update) {
  5992. this.parser_.update();
  5993. }
  5994. }
  5995. /**
  5996. * Callback from StreamingEngine.
  5997. *
  5998. * @private
  5999. */
  6000. onSegmentAppended_(start, end, contentType) {
  6001. // When we append a segment to media source (via streaming engine) we are
  6002. // changing what data we have buffered, so notify the playhead of the
  6003. // change.
  6004. if (this.playhead_) {
  6005. this.playhead_.notifyOfBufferingChange();
  6006. // Skip the initial buffer gap
  6007. const startTime = this.mediaSourceEngine_.bufferStart(contentType);
  6008. if (
  6009. !this.isLive() &&
  6010. // If not paused then GapJumpingController will handle this gap.
  6011. this.video_.paused &&
  6012. startTime != null &&
  6013. startTime > 0 &&
  6014. this.playhead_.getTime() < startTime
  6015. ) {
  6016. this.playhead_.setStartTime(startTime);
  6017. }
  6018. }
  6019. this.pollBufferState_();
  6020. // Dispatch an event for users to consume, too.
  6021. const data = new Map()
  6022. .set('start', start)
  6023. .set('end', end)
  6024. .set('contentType', contentType);
  6025. this.dispatchEvent(shaka.Player.makeEvent_(
  6026. shaka.util.FakeEvent.EventName.SegmentAppended, data));
  6027. }
  6028. /**
  6029. * Callback from AbrManager.
  6030. *
  6031. * @param {shaka.extern.Variant} variant
  6032. * @param {boolean=} clearBuffer
  6033. * @param {number=} safeMargin Optional amount of buffer (in seconds) to
  6034. * retain when clearing the buffer.
  6035. * Defaults to 0 if not provided. Ignored if clearBuffer is false.
  6036. * @private
  6037. */
  6038. switch_(variant, clearBuffer = false, safeMargin = 0) {
  6039. shaka.log.debug('switch_');
  6040. goog.asserts.assert(this.config_.abr.enabled,
  6041. 'AbrManager should not call switch while disabled!');
  6042. if (!this.manifest_) {
  6043. // It could come from a preload manager operation.
  6044. return;
  6045. }
  6046. if (!this.streamingEngine_) {
  6047. // There's no way to change it.
  6048. return;
  6049. }
  6050. if (variant == this.streamingEngine_.getCurrentVariant()) {
  6051. // This isn't a change.
  6052. return;
  6053. }
  6054. this.switchVariant_(variant, /* fromAdaptation= */ true,
  6055. clearBuffer, safeMargin);
  6056. }
  6057. /**
  6058. * Dispatches an 'adaptation' event.
  6059. * @param {?shaka.extern.Track} from
  6060. * @param {shaka.extern.Track} to
  6061. * @private
  6062. */
  6063. onAdaptation_(from, to) {
  6064. // Delay the 'adaptation' event so that StreamingEngine has time to absorb
  6065. // the changes before the user tries to query it.
  6066. const data = new Map()
  6067. .set('oldTrack', from)
  6068. .set('newTrack', to);
  6069. if (this.lcevcDec_) {
  6070. this.lcevcDec_.updateVariant(to, this.getManifestType());
  6071. }
  6072. const event = shaka.Player.makeEvent_(
  6073. shaka.util.FakeEvent.EventName.Adaptation, data);
  6074. this.delayDispatchEvent_(event);
  6075. }
  6076. /**
  6077. * Dispatches a 'trackschanged' event.
  6078. * @private
  6079. */
  6080. onTracksChanged_() {
  6081. // Delay the 'trackschanged' event so StreamingEngine has time to absorb the
  6082. // changes before the user tries to query it.
  6083. const event = shaka.Player.makeEvent_(
  6084. shaka.util.FakeEvent.EventName.TracksChanged);
  6085. this.delayDispatchEvent_(event);
  6086. }
  6087. /**
  6088. * Dispatches a 'variantchanged' event.
  6089. * @param {?shaka.extern.Track} from
  6090. * @param {shaka.extern.Track} to
  6091. * @private
  6092. */
  6093. onVariantChanged_(from, to) {
  6094. // Delay the 'variantchanged' event so StreamingEngine has time to absorb
  6095. // the changes before the user tries to query it.
  6096. const data = new Map()
  6097. .set('oldTrack', from)
  6098. .set('newTrack', to);
  6099. if (this.lcevcDec_) {
  6100. this.lcevcDec_.updateVariant(to, this.getManifestType());
  6101. }
  6102. const event = shaka.Player.makeEvent_(
  6103. shaka.util.FakeEvent.EventName.VariantChanged, data);
  6104. this.delayDispatchEvent_(event);
  6105. }
  6106. /**
  6107. * Dispatches a 'textchanged' event.
  6108. * @private
  6109. */
  6110. onTextChanged_() {
  6111. // Delay the 'textchanged' event so StreamingEngine time to absorb the
  6112. // changes before the user tries to query it.
  6113. const event = shaka.Player.makeEvent_(
  6114. shaka.util.FakeEvent.EventName.TextChanged);
  6115. this.delayDispatchEvent_(event);
  6116. }
  6117. /** @private */
  6118. onTextTrackVisibility_() {
  6119. const event = shaka.Player.makeEvent_(
  6120. shaka.util.FakeEvent.EventName.TextTrackVisibility);
  6121. this.delayDispatchEvent_(event);
  6122. }
  6123. /** @private */
  6124. onAbrStatusChanged_() {
  6125. // Restore disabled variants if abr get disabled
  6126. if (!this.config_.abr.enabled) {
  6127. this.restoreDisabledVariants_();
  6128. }
  6129. const data = (new Map()).set('newStatus', this.config_.abr.enabled);
  6130. this.delayDispatchEvent_(shaka.Player.makeEvent_(
  6131. shaka.util.FakeEvent.EventName.AbrStatusChanged, data));
  6132. }
  6133. /**
  6134. * @param {boolean} updateAbrManager
  6135. * @private
  6136. */
  6137. restoreDisabledVariants_(updateAbrManager=true) {
  6138. if (this.loadMode_ != shaka.Player.LoadMode.MEDIA_SOURCE) {
  6139. return;
  6140. }
  6141. goog.asserts.assert(this.manifest_, 'Should have manifest!');
  6142. shaka.log.v2('Restoring all disabled streams...');
  6143. this.checkVariantsTimer_.stop();
  6144. for (const variant of this.manifest_.variants) {
  6145. variant.disabledUntilTime = 0;
  6146. }
  6147. if (updateAbrManager) {
  6148. this.updateAbrManagerVariants_();
  6149. }
  6150. }
  6151. /**
  6152. * Temporarily disable all variants containing |stream|
  6153. * @param {shaka.extern.Stream} stream
  6154. * @param {number} disableTime
  6155. * @return {boolean}
  6156. */
  6157. disableStream(stream, disableTime) {
  6158. if (!this.config_.abr.enabled ||
  6159. this.loadMode_ === shaka.Player.LoadMode.DESTROYED) {
  6160. return false;
  6161. }
  6162. if (!navigator.onLine) {
  6163. // Don't disable variants if we're completely offline, or else we end up
  6164. // rapidly restricting all of them.
  6165. return false;
  6166. }
  6167. // It only makes sense to disable a stream if we have an alternative else we
  6168. // end up disabling all variants.
  6169. const hasAltStream = this.manifest_.variants.some((variant) => {
  6170. const altStream = variant[stream.type];
  6171. if (altStream && altStream.id !== stream.id) {
  6172. if (shaka.util.StreamUtils.isAudio(stream)) {
  6173. return stream.language === altStream.language;
  6174. }
  6175. return true;
  6176. }
  6177. return false;
  6178. });
  6179. if (hasAltStream) {
  6180. let didDisableStream = false;
  6181. for (const variant of this.manifest_.variants) {
  6182. const candidate = variant[stream.type];
  6183. if (candidate && candidate.id === stream.id) {
  6184. variant.disabledUntilTime = (Date.now() / 1000) + disableTime;
  6185. didDisableStream = true;
  6186. shaka.log.v2(
  6187. 'Disabled stream ' + stream.type + ':' + stream.id +
  6188. ' for ' + disableTime + ' seconds...');
  6189. }
  6190. }
  6191. goog.asserts.assert(didDisableStream, 'Must have disabled stream');
  6192. this.checkVariantsTimer_.tickEvery(1);
  6193. // Get the safeMargin to ensure a seamless playback
  6194. const {video} = this.getBufferedInfo();
  6195. const safeMargin =
  6196. video.reduce((size, {start, end}) => size + end - start, 0);
  6197. // Update abr manager variants and switch to recover playback
  6198. this.chooseVariantAndSwitch_(
  6199. /* clearBuffer= */ true, /* safeMargin= */ safeMargin,
  6200. /* force= */ true, /* fromAdaptation= */ false);
  6201. return true;
  6202. }
  6203. shaka.log.warning(
  6204. 'No alternate stream found for active ' + stream.type + ' stream. ' +
  6205. 'Will ignore request to disable stream...');
  6206. return false;
  6207. }
  6208. /**
  6209. * @param {!shaka.util.Error} error
  6210. * @private
  6211. */
  6212. async onError_(error) {
  6213. goog.asserts.assert(error instanceof shaka.util.Error, 'Wrong error type!');
  6214. // Errors dispatched after |destroy| is called are not meaningful and should
  6215. // be safe to ignore.
  6216. if (this.loadMode_ == shaka.Player.LoadMode.DESTROYED) {
  6217. return;
  6218. }
  6219. let fireError = true;
  6220. if (this.fullyLoaded_ && this.manifest_ && this.streamingEngine_ &&
  6221. (error.code == shaka.util.Error.Code.VIDEO_ERROR ||
  6222. error.code == shaka.util.Error.Code.MEDIA_SOURCE_OPERATION_FAILED ||
  6223. error.code == shaka.util.Error.Code.MEDIA_SOURCE_OPERATION_THREW ||
  6224. error.code == shaka.util.Error.Code.TRANSMUXING_FAILED)) {
  6225. try {
  6226. const ret = await this.streamingEngine_.resetMediaSource();
  6227. fireError = !ret;
  6228. } catch (e) {
  6229. fireError = true;
  6230. }
  6231. }
  6232. if (!fireError) {
  6233. return;
  6234. }
  6235. // Restore disabled variant if the player experienced a critical error.
  6236. if (error.severity === shaka.util.Error.Severity.CRITICAL) {
  6237. this.restoreDisabledVariants_(/* updateAbrManager= */ false);
  6238. }
  6239. const eventName = shaka.util.FakeEvent.EventName.Error;
  6240. const event = shaka.Player.makeEvent_(
  6241. eventName, (new Map()).set('detail', error));
  6242. this.dispatchEvent(event);
  6243. if (event.defaultPrevented) {
  6244. error.handled = true;
  6245. }
  6246. }
  6247. /**
  6248. * When we fire region events, we need to copy the information out of the
  6249. * region to break the connection with the player's internal data. We do the
  6250. * copy here because this is the transition point between the player and the
  6251. * app.
  6252. *
  6253. * @param {!shaka.util.FakeEvent.EventName} eventName
  6254. * @param {shaka.extern.TimelineRegionInfo} region
  6255. * @param {shaka.util.FakeEventTarget=} eventTarget
  6256. *
  6257. * @private
  6258. */
  6259. onRegionEvent_(eventName, region, eventTarget = this) {
  6260. // Always make a copy to avoid exposing our internal data to the app.
  6261. const clone = {
  6262. schemeIdUri: region.schemeIdUri,
  6263. value: region.value,
  6264. startTime: region.startTime,
  6265. endTime: region.endTime,
  6266. id: region.id,
  6267. eventElement: region.eventElement,
  6268. eventNode: region.eventNode,
  6269. };
  6270. const data = (new Map()).set('detail', clone);
  6271. eventTarget.dispatchEvent(shaka.Player.makeEvent_(eventName, data));
  6272. }
  6273. /**
  6274. * When notified of a media quality change we need to emit a
  6275. * MediaQualityChange event to the app.
  6276. *
  6277. * @param {shaka.extern.MediaQualityInfo} mediaQuality
  6278. * @param {number} position
  6279. *
  6280. * @private
  6281. */
  6282. onMediaQualityChange_(mediaQuality, position) {
  6283. // Always make a copy to avoid exposing our internal data to the app.
  6284. const clone = {
  6285. bandwidth: mediaQuality.bandwidth,
  6286. audioSamplingRate: mediaQuality.audioSamplingRate,
  6287. codecs: mediaQuality.codecs,
  6288. contentType: mediaQuality.contentType,
  6289. frameRate: mediaQuality.frameRate,
  6290. height: mediaQuality.height,
  6291. mimeType: mediaQuality.mimeType,
  6292. channelsCount: mediaQuality.channelsCount,
  6293. pixelAspectRatio: mediaQuality.pixelAspectRatio,
  6294. width: mediaQuality.width,
  6295. };
  6296. const data = new Map()
  6297. .set('mediaQuality', clone)
  6298. .set('position', position);
  6299. this.dispatchEvent(shaka.Player.makeEvent_(
  6300. shaka.util.FakeEvent.EventName.MediaQualityChanged, data));
  6301. }
  6302. /**
  6303. * Turn the media element's error object into a Shaka Player error object.
  6304. *
  6305. * @return {shaka.util.Error}
  6306. * @private
  6307. */
  6308. videoErrorToShakaError_() {
  6309. goog.asserts.assert(this.video_.error,
  6310. 'Video error expected, but missing!');
  6311. if (!this.video_.error) {
  6312. return null;
  6313. }
  6314. const code = this.video_.error.code;
  6315. if (code == 1 /* MEDIA_ERR_ABORTED */) {
  6316. // Ignore this error code, which should only occur when navigating away or
  6317. // deliberately stopping playback of HTTP content.
  6318. return null;
  6319. }
  6320. // Extra error information from MS Edge:
  6321. let extended = this.video_.error.msExtendedCode;
  6322. if (extended) {
  6323. // Convert to unsigned:
  6324. if (extended < 0) {
  6325. extended += Math.pow(2, 32);
  6326. }
  6327. // Format as hex:
  6328. extended = extended.toString(16);
  6329. }
  6330. // Extra error information from Chrome:
  6331. const message = this.video_.error.message;
  6332. return new shaka.util.Error(
  6333. shaka.util.Error.Severity.CRITICAL,
  6334. shaka.util.Error.Category.MEDIA,
  6335. shaka.util.Error.Code.VIDEO_ERROR,
  6336. code, extended, message);
  6337. }
  6338. /**
  6339. * @param {!Event} event
  6340. * @private
  6341. */
  6342. onVideoError_(event) {
  6343. const error = this.videoErrorToShakaError_();
  6344. if (!error) {
  6345. return;
  6346. }
  6347. this.onError_(error);
  6348. }
  6349. /**
  6350. * @param {!Object.<string, string>} keyStatusMap A map of hex key IDs to
  6351. * statuses.
  6352. * @private
  6353. */
  6354. onKeyStatus_(keyStatusMap) {
  6355. goog.asserts.assert(this.streamingEngine_, 'Cannot be called in src= mode');
  6356. const event = shaka.Player.makeEvent_(
  6357. shaka.util.FakeEvent.EventName.KeyStatusChanged);
  6358. this.dispatchEvent(event);
  6359. let keyIds = Object.keys(keyStatusMap);
  6360. if (keyIds.length == 0) {
  6361. shaka.log.warning(
  6362. 'Got a key status event without any key statuses, so we don\'t ' +
  6363. 'know the real key statuses. If we don\'t have all the keys, ' +
  6364. 'you\'ll need to set restrictions so we don\'t select those tracks.');
  6365. }
  6366. // Non-standard version of global key status. Modify it to match standard
  6367. // behavior.
  6368. if (keyIds.length == 1 && keyIds[0] == '') {
  6369. keyIds = ['00'];
  6370. keyStatusMap = {'00': keyStatusMap['']};
  6371. }
  6372. // If EME is using a synthetic key ID, the only key ID is '00' (a single 0
  6373. // byte). In this case, it is only used to report global success/failure.
  6374. // See note about old platforms in: https://bit.ly/2tpez5Z
  6375. const isGlobalStatus = keyIds.length == 1 && keyIds[0] == '00';
  6376. if (isGlobalStatus) {
  6377. shaka.log.warning(
  6378. 'Got a synthetic key status event, so we don\'t know the real key ' +
  6379. 'statuses. If we don\'t have all the keys, you\'ll need to set ' +
  6380. 'restrictions so we don\'t select those tracks.');
  6381. }
  6382. const restrictedStatuses = shaka.media.ManifestFilterer.restrictedStatuses;
  6383. let tracksChanged = false;
  6384. goog.asserts.assert(this.drmEngine_, 'drmEngine should be non-null here.');
  6385. // Only filter tracks for keys if we have some key statuses to look at.
  6386. if (keyIds.length) {
  6387. for (const variant of this.manifest_.variants) {
  6388. const streams = shaka.util.StreamUtils.getVariantStreams(variant);
  6389. for (const stream of streams) {
  6390. const originalAllowed = variant.allowedByKeySystem;
  6391. // Only update if we have key IDs for the stream. If the keys aren't
  6392. // all present, then the track should be restricted.
  6393. if (stream.keyIds.size) {
  6394. variant.allowedByKeySystem = true;
  6395. for (const keyId of stream.keyIds) {
  6396. const keyStatus = keyStatusMap[isGlobalStatus ? '00' : keyId];
  6397. if (keyStatus || this.drmEngine_.hasManifestInitData()) {
  6398. variant.allowedByKeySystem = variant.allowedByKeySystem &&
  6399. !!keyStatus && !restrictedStatuses.includes(keyStatus);
  6400. }
  6401. }
  6402. }
  6403. if (originalAllowed != variant.allowedByKeySystem) {
  6404. tracksChanged = true;
  6405. }
  6406. } // for (const stream of streams)
  6407. } // for (const variant of this.manifest_.variants)
  6408. } // if (keyIds.size)
  6409. if (tracksChanged) {
  6410. this.onTracksChanged_();
  6411. const variantsUpdated = this.updateAbrManagerVariants_();
  6412. if (!variantsUpdated) {
  6413. return;
  6414. }
  6415. }
  6416. const currentVariant = this.streamingEngine_.getCurrentVariant();
  6417. if (currentVariant && !currentVariant.allowedByKeySystem) {
  6418. shaka.log.debug('Choosing new streams after key status changed');
  6419. this.chooseVariantAndSwitch_();
  6420. }
  6421. }
  6422. /**
  6423. * @return {boolean} true if we should stream text right now.
  6424. * @private
  6425. */
  6426. shouldStreamText_() {
  6427. return this.config_.streaming.alwaysStreamText || this.isTextTrackVisible();
  6428. }
  6429. /**
  6430. * Applies playRangeStart and playRangeEnd to the given timeline. This will
  6431. * only affect non-live content.
  6432. *
  6433. * @param {shaka.media.PresentationTimeline} timeline
  6434. * @param {number} playRangeStart
  6435. * @param {number} playRangeEnd
  6436. *
  6437. * @private
  6438. */
  6439. static applyPlayRange_(timeline, playRangeStart, playRangeEnd) {
  6440. if (playRangeStart > 0) {
  6441. if (timeline.isLive()) {
  6442. shaka.log.warning(
  6443. '|playRangeStart| has been configured for live content. ' +
  6444. 'Ignoring the setting.');
  6445. } else {
  6446. timeline.setUserSeekStart(playRangeStart);
  6447. }
  6448. }
  6449. // If the playback has been configured to end before the end of the
  6450. // presentation, update the duration unless it's live content.
  6451. const fullDuration = timeline.getDuration();
  6452. if (playRangeEnd < fullDuration) {
  6453. if (timeline.isLive()) {
  6454. shaka.log.warning(
  6455. '|playRangeEnd| has been configured for live content. ' +
  6456. 'Ignoring the setting.');
  6457. } else {
  6458. timeline.setDuration(playRangeEnd);
  6459. }
  6460. }
  6461. }
  6462. /**
  6463. * Fire an event, but wait a little bit so that the immediate execution can
  6464. * complete before the event is handled.
  6465. *
  6466. * @param {!shaka.util.FakeEvent} event
  6467. * @private
  6468. */
  6469. async delayDispatchEvent_(event) {
  6470. // Wait until the next interpreter cycle.
  6471. await Promise.resolve();
  6472. // Only dispatch the event if we are still alive.
  6473. if (this.loadMode_ != shaka.Player.LoadMode.DESTROYED) {
  6474. this.dispatchEvent(event);
  6475. }
  6476. }
  6477. /**
  6478. * Get the normalized languages for a group of tracks.
  6479. *
  6480. * @param {!Array.<?shaka.extern.Track>} tracks
  6481. * @return {!Set.<string>}
  6482. * @private
  6483. */
  6484. static getLanguagesFrom_(tracks) {
  6485. const languages = new Set();
  6486. for (const track of tracks) {
  6487. if (track.language) {
  6488. languages.add(shaka.util.LanguageUtils.normalize(track.language));
  6489. } else {
  6490. languages.add('und');
  6491. }
  6492. }
  6493. return languages;
  6494. }
  6495. /**
  6496. * Get all permutations of normalized languages and role for a group of
  6497. * tracks.
  6498. *
  6499. * @param {!Array.<?shaka.extern.Track>} tracks
  6500. * @return {!Array.<shaka.extern.LanguageRole>}
  6501. * @private
  6502. */
  6503. static getLanguageAndRolesFrom_(tracks) {
  6504. /** @type {!Map.<string, !Set>} */
  6505. const languageToRoles = new Map();
  6506. /** @type {!Map.<string, !Map.<string, string>>} */
  6507. const languageRoleToLabel = new Map();
  6508. for (const track of tracks) {
  6509. let language = 'und';
  6510. let roles = [];
  6511. if (track.language) {
  6512. language = shaka.util.LanguageUtils.normalize(track.language);
  6513. }
  6514. if (track.type == 'variant') {
  6515. roles = track.audioRoles;
  6516. } else {
  6517. roles = track.roles;
  6518. }
  6519. if (!roles || !roles.length) {
  6520. // We must have an empty role so that we will still get a language-role
  6521. // entry from our Map.
  6522. roles = [''];
  6523. }
  6524. if (!languageToRoles.has(language)) {
  6525. languageToRoles.set(language, new Set());
  6526. }
  6527. for (const role of roles) {
  6528. languageToRoles.get(language).add(role);
  6529. if (track.label) {
  6530. if (!languageRoleToLabel.has(language)) {
  6531. languageRoleToLabel.set(language, new Map());
  6532. }
  6533. languageRoleToLabel.get(language).set(role, track.label);
  6534. }
  6535. }
  6536. }
  6537. // Flatten our map to an array of language-role pairs.
  6538. const pairings = [];
  6539. languageToRoles.forEach((roles, language) => {
  6540. for (const role of roles) {
  6541. let label = null;
  6542. if (languageRoleToLabel.has(language) &&
  6543. languageRoleToLabel.get(language).has(role)) {
  6544. label = languageRoleToLabel.get(language).get(role);
  6545. }
  6546. pairings.push({language, role, label});
  6547. }
  6548. });
  6549. return pairings;
  6550. }
  6551. /**
  6552. * Assuming the player is playing content with media source, check if the
  6553. * player has buffered enough content to make it to the end of the
  6554. * presentation.
  6555. *
  6556. * @return {boolean}
  6557. * @private
  6558. */
  6559. isBufferedToEndMS_() {
  6560. goog.asserts.assert(
  6561. this.video_,
  6562. 'We need a video element to get buffering information');
  6563. goog.asserts.assert(
  6564. this.mediaSourceEngine_,
  6565. 'We need a media source engine to get buffering information');
  6566. goog.asserts.assert(
  6567. this.manifest_,
  6568. 'We need a manifest to get buffering information');
  6569. // This is a strong guarantee that we are buffered to the end, because it
  6570. // means the playhead is already at that end.
  6571. if (this.video_.ended) {
  6572. return true;
  6573. }
  6574. // This means that MediaSource has buffered the final segment in all
  6575. // SourceBuffers and is no longer accepting additional segments.
  6576. if (this.mediaSourceEngine_.ended()) {
  6577. return true;
  6578. }
  6579. // Live streams are "buffered to the end" when they have buffered to the
  6580. // live edge or beyond (into the region covered by the presentation delay).
  6581. if (this.manifest_.presentationTimeline.isLive()) {
  6582. const liveEdge =
  6583. this.manifest_.presentationTimeline.getSegmentAvailabilityEnd();
  6584. const bufferEnd =
  6585. shaka.media.TimeRangesUtils.bufferEnd(this.video_.buffered);
  6586. if (bufferEnd != null && bufferEnd >= liveEdge) {
  6587. return true;
  6588. }
  6589. }
  6590. return false;
  6591. }
  6592. /**
  6593. * Assuming the player is playing content with src=, check if the player has
  6594. * buffered enough content to make it to the end of the presentation.
  6595. *
  6596. * @return {boolean}
  6597. * @private
  6598. */
  6599. isBufferedToEndSrc_() {
  6600. goog.asserts.assert(
  6601. this.video_,
  6602. 'We need a video element to get buffering information');
  6603. // This is a strong guarantee that we are buffered to the end, because it
  6604. // means the playhead is already at that end.
  6605. if (this.video_.ended) {
  6606. return true;
  6607. }
  6608. // If we have buffered to the duration of the content, it means we will have
  6609. // enough content to buffer to the end of the presentation.
  6610. const bufferEnd =
  6611. shaka.media.TimeRangesUtils.bufferEnd(this.video_.buffered);
  6612. // Because Safari's native HLS reports slightly inaccurate values for
  6613. // bufferEnd here, we use a fudge factor. Without this, we can end up in a
  6614. // buffering state at the end of the stream. See issue #2117.
  6615. const fudge = 1; // 1000 ms
  6616. return bufferEnd != null && bufferEnd >= this.video_.duration - fudge;
  6617. }
  6618. /**
  6619. * Create an error for when we purposely interrupt a load operation.
  6620. *
  6621. * @return {!shaka.util.Error}
  6622. * @private
  6623. */
  6624. createAbortLoadError_() {
  6625. return new shaka.util.Error(
  6626. shaka.util.Error.Severity.CRITICAL,
  6627. shaka.util.Error.Category.PLAYER,
  6628. shaka.util.Error.Code.LOAD_INTERRUPTED);
  6629. }
  6630. };
  6631. /**
  6632. * In order to know what method of loading the player used for some content, we
  6633. * have this enum. It lets us know if content has not been loaded, loaded with
  6634. * media source, or loaded with src equals.
  6635. *
  6636. * This enum has a low resolution, because it is only meant to express the
  6637. * outer limits of the various states that the player is in. For example, when
  6638. * someone calls a public method on player, it should not matter if they have
  6639. * initialized drm engine, it should only matter if they finished loading
  6640. * content.
  6641. *
  6642. * @enum {number}
  6643. * @export
  6644. */
  6645. shaka.Player.LoadMode = {
  6646. 'DESTROYED': 0,
  6647. 'NOT_LOADED': 1,
  6648. 'MEDIA_SOURCE': 2,
  6649. 'SRC_EQUALS': 3,
  6650. };
  6651. /**
  6652. * The typical buffering threshold. When we have less than this buffered (in
  6653. * seconds), we enter a buffering state. This specific value is based on manual
  6654. * testing and evaluation across a variety of platforms.
  6655. *
  6656. * To make the buffering logic work in all cases, this "typical" threshold will
  6657. * be overridden if the rebufferingGoal configuration is too low.
  6658. *
  6659. * @const {number}
  6660. * @private
  6661. */
  6662. shaka.Player.TYPICAL_BUFFERING_THRESHOLD_ = 0.5;
  6663. /**
  6664. * @define {string} A version number taken from git at compile time.
  6665. * @export
  6666. */
  6667. // eslint-disable-next-line no-useless-concat
  6668. shaka.Player.version = 'v4.9.5' + '-uncompiled'; // x-release-please-version
  6669. // Initialize the deprecation system using the version string we just set
  6670. // on the player.
  6671. shaka.Deprecate.init(shaka.Player.version);
  6672. /** @private {!Object.<string, function():*>} */
  6673. shaka.Player.supportPlugins_ = {};
  6674. /** @private {?shaka.extern.IAdManager.Factory} */
  6675. shaka.Player.adManagerFactory_ = null;
  6676. /**
  6677. * @const {string}
  6678. */
  6679. shaka.Player.TextTrackLabel = 'Shaka Player TextTrack';