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