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. const generatedTrack = this.getGeneratedTextTrack_();
  2697. if (generatedTrack) {
  2698. generatedTrack.mode = 'hidden';
  2699. }
  2700. };
  2701. const setHiddenMode = () => {
  2702. const track = this.getFilteredTextTracks_()
  2703. .find((t) => t.mode !== 'disabled');
  2704. if (track) {
  2705. track.mode = 'hidden';
  2706. }
  2707. const generatedTrack = this.getGeneratedTextTrack_();
  2708. const isTextVisible = this.textDisplayer_.isTextVisible();
  2709. if (generatedTrack && isTextVisible) {
  2710. generatedTrack.mode = 'showing';
  2711. }
  2712. };
  2713. this.loadEventManager_.listen(mediaElement, 'enterpictureinpicture',
  2714. () => setShowingMode());
  2715. this.loadEventManager_.listen(mediaElement, 'leavepictureinpicture',
  2716. () => setHiddenMode());
  2717. if (mediaElement.remote) {
  2718. this.loadEventManager_.listen(mediaElement.remote, 'connect',
  2719. () => setHiddenMode());
  2720. this.loadEventManager_.listen(mediaElement.remote, 'connecting',
  2721. () => setHiddenMode());
  2722. this.loadEventManager_.listen(mediaElement.remote, 'disconnect',
  2723. () => setHiddenMode());
  2724. } else if ('webkitCurrentPlaybackTargetIsWireless' in mediaElement) {
  2725. this.loadEventManager_.listen(mediaElement,
  2726. 'webkitcurrentplaybacktargetiswirelesschanged',
  2727. () => setHiddenMode());
  2728. }
  2729. const video = /** @type {HTMLVideoElement} */(mediaElement);
  2730. if (video.webkitSupportsFullscreen) {
  2731. this.loadEventManager_.listen(video, 'webkitpresentationmodechanged',
  2732. () => {
  2733. if (video.webkitPresentationMode != 'inline') {
  2734. setShowingMode();
  2735. } else {
  2736. setHiddenMode();
  2737. }
  2738. });
  2739. }
  2740. }
  2741. // Add all media element listeners.
  2742. this.addBasicMediaListeners_(mediaElement, startTimeOfLoad);
  2743. // By setting |src| we are done "loading" with src=. We don't need to set
  2744. // the current time because |playhead| will do that for us.
  2745. let playbackUri = this.cmcdManager_.appendSrcData(this.assetUri_, mimeType);
  2746. // Apply temporal clipping using playRangeStart and playRangeEnd based
  2747. // in https://www.w3.org/TR/media-frags/
  2748. if (!playbackUri.includes('#t=') &&
  2749. (this.config_.playRangeStart > 0 ||
  2750. isFinite(this.config_.playRangeEnd))) {
  2751. playbackUri += '#t=';
  2752. if (this.config_.playRangeStart > 0) {
  2753. playbackUri += this.config_.playRangeStart;
  2754. }
  2755. if (isFinite(this.config_.playRangeEnd)) {
  2756. playbackUri += ',' + this.config_.playRangeEnd;
  2757. }
  2758. }
  2759. if (this.mediaSourceEngine_ ) {
  2760. await this.mediaSourceEngine_.destroy();
  2761. this.mediaSourceEngine_ = null;
  2762. }
  2763. shaka.util.Dom.removeAllChildren(mediaElement);
  2764. mediaElement.src = playbackUri;
  2765. // Tizen 3 / WebOS won't load anything unless you call load() explicitly,
  2766. // no matter the value of the preload attribute. This is harmful on some
  2767. // other platforms by triggering unbounded loading of media data, but is
  2768. // necessary here.
  2769. if (shaka.util.Platform.isTizen() || shaka.util.Platform.isWebOS()) {
  2770. mediaElement.load();
  2771. }
  2772. // In Safari using HLS won't load anything unless you call load()
  2773. // explicitly, no matter the value of the preload attribute.
  2774. // Note: this only happens when there are not autoplay.
  2775. if (mediaElement.preload != 'none' && !mediaElement.autoplay &&
  2776. shaka.util.MimeUtils.isHlsType(mimeType) &&
  2777. shaka.util.Platform.isApple()) {
  2778. mediaElement.load();
  2779. }
  2780. // Set the load mode last so that we know that all our components are
  2781. // initialized.
  2782. this.loadMode_ = shaka.Player.LoadMode.SRC_EQUALS;
  2783. // The event doesn't mean as much for src= playback, since we don't
  2784. // control streaming. But we should fire it in this path anyway since
  2785. // some applications may be expecting it as a life-cycle event.
  2786. this.dispatchEvent(shaka.Player.makeEvent_(
  2787. shaka.util.FakeEvent.EventName.Streaming));
  2788. // The "load" Promise is resolved when we have loaded the metadata. If we
  2789. // wait for the full data, that won't happen on Safari until the play
  2790. // button is hit.
  2791. const fullyLoaded = new shaka.util.PublicPromise();
  2792. shaka.util.MediaReadyState.waitForReadyState(mediaElement,
  2793. HTMLMediaElement.HAVE_METADATA,
  2794. this.loadEventManager_,
  2795. () => {
  2796. this.playhead_.ready();
  2797. fullyLoaded.resolve();
  2798. });
  2799. const waitForNativeTracks = () => {
  2800. return new Promise((resolve) => {
  2801. const GRACE_PERIOD = 0.5;
  2802. const timer = new shaka.util.Timer(resolve);
  2803. // Applying the text preference too soon can result in it being
  2804. // reverted. Wait for native HLS to pick something first.
  2805. this.loadEventManager_.listen(mediaElement.textTracks,
  2806. 'change', () => timer.tickAfter(GRACE_PERIOD));
  2807. timer.tickAfter(GRACE_PERIOD);
  2808. });
  2809. };
  2810. // We can't switch to preferred languages, though, until the data is
  2811. // loaded.
  2812. shaka.util.MediaReadyState.waitForReadyState(mediaElement,
  2813. HTMLMediaElement.HAVE_CURRENT_DATA,
  2814. this.loadEventManager_,
  2815. async () => {
  2816. await waitForNativeTracks();
  2817. // If we have moved on to another piece of content while waiting for
  2818. // the above event/timer, we should not change tracks here.
  2819. if (unloaded) {
  2820. return;
  2821. }
  2822. this.setupPreferredAudioOnSrc_();
  2823. const textTracks = this.getFilteredTextTracks_();
  2824. // If Safari native picked one for us, we'll set text visible.
  2825. if (textTracks.some((t) => t.mode === 'showing')) {
  2826. this.isTextVisible_ = true;
  2827. this.textDisplayer_.setTextVisibility(true);
  2828. }
  2829. if (textTracks.length) {
  2830. if (this.textDisplayer_.enableTextDisplayer) {
  2831. this.textDisplayer_.enableTextDisplayer();
  2832. } else {
  2833. shaka.Deprecate.deprecateFeature(5,
  2834. 'Text displayer w/ enableTextDisplayer',
  2835. 'Text displayer should have a "enableTextDisplayer" method!');
  2836. }
  2837. }
  2838. let enabledNativeTrack = false;
  2839. for (const track of textTracks) {
  2840. if (track.mode !== 'disabled') {
  2841. if (!enabledNativeTrack) {
  2842. this.enableNativeTrack_(track);
  2843. enabledNativeTrack = true;
  2844. } else {
  2845. track.mode = 'disabled';
  2846. shaka.log.alwaysWarn(
  2847. 'Found more than one enabled text track, disabling it',
  2848. track);
  2849. }
  2850. }
  2851. }
  2852. this.setupPreferredTextOnSrc_();
  2853. });
  2854. if (mediaElement.error) {
  2855. // Already failed!
  2856. fullyLoaded.reject(this.videoErrorToShakaError_());
  2857. } else if (mediaElement.preload == 'none') {
  2858. shaka.log.alwaysWarn(
  2859. 'With <video preload="none">, the browser will not load anything ' +
  2860. 'until play() is called. We are unable to measure load latency ' +
  2861. 'in a meaningful way, and we cannot provide track info yet. ' +
  2862. 'Please do not use preload="none" with Shaka Player.');
  2863. // We can't wait for an event load loadedmetadata, since that will be
  2864. // blocked until a user interaction. So resolve the Promise now.
  2865. fullyLoaded.resolve();
  2866. }
  2867. this.loadEventManager_.listenOnce(mediaElement, 'error', () => {
  2868. fullyLoaded.reject(this.videoErrorToShakaError_());
  2869. });
  2870. await shaka.util.Functional.promiseWithTimeout(
  2871. this.config_.streaming.loadTimeout, fullyLoaded);
  2872. const isLive = this.isLive();
  2873. if ((isLive && ((this.config_.streaming.liveSync &&
  2874. this.config_.streaming.liveSync.enabled) ||
  2875. this.config_.streaming.liveSync.panicMode)) ||
  2876. this.config_.streaming.vodDynamicPlaybackRate) {
  2877. const onTimeUpdate = () => this.onTimeUpdate_();
  2878. this.loadEventManager_.listen(mediaElement, 'timeupdate', onTimeUpdate);
  2879. }
  2880. if (!isLive) {
  2881. const onVideoProgress = () => this.onVideoProgress_();
  2882. this.loadEventManager_.listen(
  2883. mediaElement, 'timeupdate', onVideoProgress);
  2884. this.onVideoProgress_();
  2885. }
  2886. if (this.adManager_) {
  2887. this.adManager_.onManifestUpdated(isLive);
  2888. // There is no good way to detect when the manifest has been updated,
  2889. // so we use seekRange().end so we can tell when it has been updated.
  2890. if (isLive) {
  2891. let prevSeekRangeEnd = this.seekRange().end;
  2892. this.loadEventManager_.listen(mediaElement, 'progress', () => {
  2893. const newSeekRangeEnd = this.seekRange().end;
  2894. if (prevSeekRangeEnd != newSeekRangeEnd) {
  2895. this.adManager_.onManifestUpdated(this.isLive());
  2896. prevSeekRangeEnd = newSeekRangeEnd;
  2897. }
  2898. });
  2899. }
  2900. }
  2901. this.fullyLoaded_ = true;
  2902. }
  2903. /**
  2904. * This method setup the preferred audio using src=..
  2905. *
  2906. * @private
  2907. */
  2908. setupPreferredAudioOnSrc_() {
  2909. const preferredAudioLanguage = this.config_.preferredAudioLanguage;
  2910. // If the user has not selected a preference, the browser preference is
  2911. // left.
  2912. if (preferredAudioLanguage == '') {
  2913. return;
  2914. }
  2915. const preferredVariantRole = this.config_.preferredVariantRole;
  2916. this.selectAudioLanguage(preferredAudioLanguage, preferredVariantRole);
  2917. }
  2918. /**
  2919. * This method setup the preferred text using src=.
  2920. *
  2921. * @private
  2922. */
  2923. setupPreferredTextOnSrc_() {
  2924. const preferredTextLanguage = this.config_.preferredTextLanguage;
  2925. // If the user has not selected a preference, the browser preference is
  2926. // left.
  2927. if (preferredTextLanguage == '') {
  2928. return;
  2929. }
  2930. const preferForcedSubs = this.config_.preferForcedSubs;
  2931. const preferredTextRole = this.config_.preferredTextRole;
  2932. this.selectTextLanguage(preferredTextLanguage, preferredTextRole,
  2933. preferForcedSubs);
  2934. }
  2935. /**
  2936. * We're looking for metadata tracks to process id3 tags. One of the uses is
  2937. * for ad info on LIVE streams
  2938. *
  2939. * @param {!TextTrack} track
  2940. * @private
  2941. */
  2942. processTimedMetadataSrcEquals_(track) {
  2943. if (track.kind != 'metadata') {
  2944. return;
  2945. }
  2946. // Hidden mode is required for the cuechange event to launch correctly
  2947. track.mode = 'hidden';
  2948. this.loadEventManager_.listen(track, 'cuechange', () => {
  2949. if (track.activeCues) {
  2950. for (const cue of track.activeCues) {
  2951. this.addMetadataToRegionTimeline_(cue.startTime, cue.endTime,
  2952. cue.type, cue.value);
  2953. if (this.adManager_) {
  2954. this.adManager_.onCueMetadataChange(cue.value);
  2955. }
  2956. }
  2957. }
  2958. if (track.cues) {
  2959. /** @type {!Array<shaka.extern.HLSInterstitial>} */
  2960. const interstitials = [];
  2961. for (const cue of track.cues) {
  2962. if (cue.type == 'com.apple.quicktime.HLS' && cue.startTime != null) {
  2963. let interstitial = interstitials.find((i) => {
  2964. return i.startTime == cue.startTime && i.endTime == cue.endTime;
  2965. });
  2966. if (!interstitial) {
  2967. interstitial = /** @type {shaka.extern.HLSInterstitial} */ ({
  2968. startTime: cue.startTime,
  2969. endTime: cue.endTime,
  2970. values: [],
  2971. });
  2972. interstitials.push(interstitial);
  2973. }
  2974. interstitial.values.push(cue.value);
  2975. }
  2976. }
  2977. for (const interstitial of interstitials) {
  2978. const isValidInterstitial = interstitial.values.some((value) => {
  2979. return value.key == 'X-ASSET-URI' || value.key == 'X-ASSET-LIST';
  2980. });
  2981. if (!isValidInterstitial) {
  2982. continue;
  2983. }
  2984. if (this.adManager_) {
  2985. const isPreRoll = interstitial.startTime == 0 && !this.isLive();
  2986. // It seems that CUE is natively omitted, by default we use CUE=ONCE
  2987. // to avoid repeating them.
  2988. interstitial.values.push({
  2989. key: 'CUE',
  2990. description: '',
  2991. data: isPreRoll ? 'ONCE,PRE' : 'ONCE',
  2992. mimeType: null,
  2993. pictureType: null,
  2994. });
  2995. goog.asserts.assert(this.video_, 'Must have video');
  2996. this.adManager_.onHLSInterstitialMetadata(
  2997. this, this.video_, interstitial);
  2998. }
  2999. }
  3000. }
  3001. });
  3002. // In Safari the initial assignment does not always work, so we schedule
  3003. // this process to be repeated several times to ensure that it has been put
  3004. // in the correct mode.
  3005. const timer = new shaka.util.Timer(() => {
  3006. const textTracks = this.getMetadataTracks_();
  3007. for (const textTrack of textTracks) {
  3008. textTrack.mode = 'hidden';
  3009. }
  3010. }).tickNow().tickAfter(0.5);
  3011. this.cleanupOnUnload_.push(() => {
  3012. timer.stop();
  3013. });
  3014. }
  3015. /**
  3016. * @param {!Array<shaka.extern.ID3Metadata>} metadata
  3017. * @param {number} offset
  3018. * @param {?number} segmentEndTime
  3019. * @private
  3020. */
  3021. processTimedMetadataMediaSrc_(metadata, offset, segmentEndTime) {
  3022. for (const sample of metadata) {
  3023. if (sample.data && typeof(sample.cueTime) == 'number' && sample.frames) {
  3024. const start = sample.cueTime + offset;
  3025. let end = segmentEndTime;
  3026. // This can happen when the ID3 info arrives in a previous segment.
  3027. if (end && start > end) {
  3028. end = start;
  3029. }
  3030. const metadataType = 'org.id3';
  3031. for (const frame of sample.frames) {
  3032. const payload = frame;
  3033. this.addMetadataToRegionTimeline_(start, end, metadataType, payload);
  3034. }
  3035. if (this.adManager_) {
  3036. this.adManager_.onHlsTimedMetadata(sample, start);
  3037. }
  3038. }
  3039. }
  3040. }
  3041. /**
  3042. * Construct and fire a Player.Metadata event
  3043. *
  3044. * @param {shaka.extern.MetadataTimelineRegionInfo} region
  3045. * @private
  3046. */
  3047. dispatchMetadataEvent_(region) {
  3048. const eventName = shaka.util.FakeEvent.EventName.Metadata;
  3049. const data = new Map()
  3050. .set('startTime', region.startTime)
  3051. .set('endTime', region.endTime)
  3052. .set('metadataType', region.schemeIdUri)
  3053. .set('payload', region.payload);
  3054. this.dispatchEvent(shaka.Player.makeEvent_(eventName, data));
  3055. }
  3056. /**
  3057. * Add metadata to region timeline
  3058. *
  3059. * @param {number} startTime
  3060. * @param {?number} endTime
  3061. * @param {string} metadataType
  3062. * @param {shaka.extern.MetadataFrame} payload
  3063. * @private
  3064. */
  3065. addMetadataToRegionTimeline_(startTime, endTime, metadataType, payload) {
  3066. if (!this.metadataRegionTimeline_) {
  3067. return;
  3068. }
  3069. goog.asserts.assert(!endTime || startTime <= endTime,
  3070. 'Metadata start time should be less or equal to the end time!');
  3071. /** @type {shaka.extern.MetadataTimelineRegionInfo} */
  3072. const region = {
  3073. schemeIdUri: metadataType,
  3074. startTime,
  3075. endTime: endTime || Infinity,
  3076. id: '',
  3077. payload,
  3078. };
  3079. // JSON stringify produces a good ID in this case.
  3080. region.id = JSON.stringify(region);
  3081. this.metadataRegionTimeline_.addRegion(region);
  3082. }
  3083. /**
  3084. * Construct and fire a Player.EMSG event
  3085. *
  3086. * @param {shaka.extern.EmsgTimelineRegionInfo} region
  3087. * @private
  3088. */
  3089. dispatchEmsgEvent_(region) {
  3090. const eventName = shaka.util.FakeEvent.EventName.Emsg;
  3091. const emsg = region.emsg;
  3092. const data = new Map().set('detail', emsg);
  3093. this.dispatchEvent(shaka.Player.makeEvent_(eventName, data));
  3094. }
  3095. /**
  3096. * Add EMSG to region timeline
  3097. *
  3098. * @param {!shaka.extern.EmsgInfo} emsg
  3099. * @private
  3100. */
  3101. addEmsgToRegionTimeline_(emsg) {
  3102. if (!this.emsgRegionTimeline_) {
  3103. return;
  3104. }
  3105. /** @type {shaka.extern.EmsgTimelineRegionInfo} */
  3106. const region = {
  3107. schemeIdUri: emsg.schemeIdUri,
  3108. startTime: emsg.startTime,
  3109. endTime: emsg.endTime,
  3110. id: String(emsg.id),
  3111. emsg,
  3112. };
  3113. this.emsgRegionTimeline_.addRegion(region);
  3114. }
  3115. /**
  3116. * Set the mode on a chapters track so that it loads.
  3117. *
  3118. * @param {?TextTrack} track
  3119. * @private
  3120. */
  3121. activateChaptersTrack_(track) {
  3122. if (!track || track.kind != 'chapters') {
  3123. return;
  3124. }
  3125. // Hidden mode is required for the cuechange event to launch correctly and
  3126. // get the cues and the activeCues
  3127. track.mode = 'hidden';
  3128. // In Safari the initial assignment does not always work, so we schedule
  3129. // this process to be repeated several times to ensure that it has been put
  3130. // in the correct mode.
  3131. const timer = new shaka.util.Timer(() => {
  3132. track.mode = 'hidden';
  3133. }).tickNow().tickAfter(0.5);
  3134. this.cleanupOnUnload_.push(() => {
  3135. timer.stop();
  3136. });
  3137. }
  3138. /**
  3139. * Releases all of the mutexes of the player. Meant for use by the tests.
  3140. * @export
  3141. */
  3142. releaseAllMutexes() {
  3143. this.mutex_.releaseAll();
  3144. }
  3145. /**
  3146. * Create a new DrmEngine instance. This may be replaced by tests to create
  3147. * fake instances. Configuration and initialization will be handled after
  3148. * |createDrmEngine|.
  3149. *
  3150. * @param {shaka.drm.DrmEngine.PlayerInterface} playerInterface
  3151. * @return {!shaka.drm.DrmEngine}
  3152. */
  3153. createDrmEngine(playerInterface) {
  3154. return new shaka.drm.DrmEngine(playerInterface);
  3155. }
  3156. /**
  3157. * Creates a new instance of NetworkingEngine. This can be replaced by tests
  3158. * to create fake instances instead.
  3159. *
  3160. * @param {(function():?shaka.media.PreloadManager)=} getPreloadManager
  3161. * @return {!shaka.net.NetworkingEngine}
  3162. */
  3163. createNetworkingEngine(getPreloadManager) {
  3164. if (!getPreloadManager) {
  3165. getPreloadManager = () => null;
  3166. }
  3167. const getAbrManager = () => {
  3168. if (getPreloadManager()) {
  3169. return getPreloadManager().getAbrManager();
  3170. } else {
  3171. return this.abrManager_;
  3172. }
  3173. };
  3174. const getParser = () => {
  3175. if (getPreloadManager()) {
  3176. return getPreloadManager().getParser();
  3177. } else {
  3178. return this.parser_;
  3179. }
  3180. };
  3181. const lateQueue = (fn) => {
  3182. if (getPreloadManager()) {
  3183. getPreloadManager().addQueuedOperation(true, fn);
  3184. } else {
  3185. fn();
  3186. }
  3187. };
  3188. const dispatchEvent = (event) => {
  3189. if (getPreloadManager()) {
  3190. getPreloadManager().dispatchEvent(event);
  3191. } else {
  3192. this.dispatchEvent(event);
  3193. }
  3194. };
  3195. const getStats = () => {
  3196. if (getPreloadManager()) {
  3197. return getPreloadManager().getStats();
  3198. } else {
  3199. return this.stats_;
  3200. }
  3201. };
  3202. /** @type {shaka.net.NetworkingEngine.onProgressUpdated} */
  3203. const onProgressUpdated_ = (deltaTimeMs,
  3204. bytesDownloaded, allowSwitch, request) => {
  3205. // In some situations, such as during offline storage, the abr manager
  3206. // might not yet exist. Therefore, we need to check if abr manager has
  3207. // been initialized before using it.
  3208. const abrManager = getAbrManager();
  3209. if (abrManager) {
  3210. abrManager.segmentDownloaded(deltaTimeMs, bytesDownloaded,
  3211. allowSwitch, request);
  3212. }
  3213. };
  3214. /** @type {shaka.net.NetworkingEngine.OnHeadersReceived} */
  3215. const onHeadersReceived_ = (headers, request, requestType) => {
  3216. // Release a 'downloadheadersreceived' event.
  3217. const name = shaka.util.FakeEvent.EventName.DownloadHeadersReceived;
  3218. const data = new Map()
  3219. .set('headers', headers)
  3220. .set('request', request)
  3221. .set('requestType', requestType);
  3222. dispatchEvent(shaka.Player.makeEvent_(name, data));
  3223. lateQueue(() => {
  3224. if (this.cmsdManager_) {
  3225. this.cmsdManager_.processHeaders(headers);
  3226. }
  3227. });
  3228. };
  3229. /** @type {shaka.net.NetworkingEngine.OnDownloadCompleted} */
  3230. const onDownloadCompleted_ = (request, response) => {
  3231. // Release a 'downloadcompleted' event.
  3232. const name = shaka.util.FakeEvent.EventName.DownloadCompleted;
  3233. const data = new Map()
  3234. .set('request', request)
  3235. .set('response', response);
  3236. dispatchEvent(shaka.Player.makeEvent_(name, data));
  3237. };
  3238. /** @type {shaka.net.NetworkingEngine.OnDownloadFailed} */
  3239. const onDownloadFailed_ = (request, error, httpResponseCode, aborted) => {
  3240. // Release a 'downloadfailed' event.
  3241. const name = shaka.util.FakeEvent.EventName.DownloadFailed;
  3242. const data = new Map()
  3243. .set('request', request)
  3244. .set('error', error)
  3245. .set('httpResponseCode', httpResponseCode)
  3246. .set('aborted', aborted);
  3247. dispatchEvent(shaka.Player.makeEvent_(name, data));
  3248. };
  3249. /** @type {shaka.net.NetworkingEngine.OnRequest} */
  3250. const onRequest_ = (type, request, context) => {
  3251. lateQueue(() => {
  3252. this.cmcdManager_.applyData(type, request, context);
  3253. });
  3254. };
  3255. /** @type {shaka.net.NetworkingEngine.OnRetry} */
  3256. const onRetry_ = (type, context, newUrl, oldUrl) => {
  3257. const parser = getParser();
  3258. if (parser && parser.banLocation) {
  3259. parser.banLocation(oldUrl);
  3260. }
  3261. };
  3262. /** @type {shaka.net.NetworkingEngine.OnResponse} */
  3263. const onResponse_ = (type, response, context) => {
  3264. if (response.data) {
  3265. const bytesDownloaded = response.data.byteLength;
  3266. const stats = getStats();
  3267. if (stats) {
  3268. stats.addBytesDownloaded(bytesDownloaded);
  3269. if (type === shaka.net.NetworkingEngine.RequestType.MANIFEST) {
  3270. stats.setManifestSize(bytesDownloaded);
  3271. }
  3272. }
  3273. }
  3274. };
  3275. return new shaka.net.NetworkingEngine(
  3276. onProgressUpdated_, onHeadersReceived_, onDownloadCompleted_,
  3277. onDownloadFailed_, onRequest_, onRetry_, onResponse_);
  3278. }
  3279. /**
  3280. * Creates a new instance of Playhead. This can be replaced by tests to
  3281. * create fake instances instead.
  3282. *
  3283. * @param {?number} startTime
  3284. * @return {!shaka.media.Playhead}
  3285. */
  3286. createPlayhead(startTime) {
  3287. goog.asserts.assert(this.manifest_, 'Must have manifest');
  3288. goog.asserts.assert(this.video_, 'Must have video');
  3289. return new shaka.media.MediaSourcePlayhead(
  3290. this.video_,
  3291. this.manifest_,
  3292. this.config_.streaming,
  3293. startTime,
  3294. () => this.onSeek_(),
  3295. (event) => this.dispatchEvent(event));
  3296. }
  3297. /**
  3298. * Create the observers for MSE playback. These observers are responsible for
  3299. * notifying the app and player of specific events during MSE playback.
  3300. *
  3301. * @param {number} startTime
  3302. * @return {!shaka.media.PlayheadObserverManager}
  3303. * @private
  3304. */
  3305. createPlayheadObserversForMSE_(startTime) {
  3306. goog.asserts.assert(this.manifest_, 'Must have manifest');
  3307. goog.asserts.assert(this.regionTimeline_, 'Must have region timeline');
  3308. goog.asserts.assert(this.metadataRegionTimeline_,
  3309. 'Must have metadata region timeline');
  3310. goog.asserts.assert(this.emsgRegionTimeline_,
  3311. 'Must have emsg region timeline');
  3312. goog.asserts.assert(this.video_, 'Must have video element');
  3313. const startsPastZero = this.isLive() || startTime > 0;
  3314. // Create the region observer. This will allow us to notify the app when we
  3315. // move in and out of timeline regions.
  3316. /** @type {!shaka.media.RegionObserver<shaka.extern.TimelineRegionInfo>} */
  3317. const regionObserver = new shaka.media.RegionObserver(
  3318. this.regionTimeline_, startsPastZero);
  3319. regionObserver.addEventListener('enter', (event) => {
  3320. /** @type {shaka.extern.TimelineRegionInfo} */
  3321. const region = event['region'];
  3322. this.onRegionEvent_(
  3323. shaka.util.FakeEvent.EventName.TimelineRegionEnter, region);
  3324. });
  3325. regionObserver.addEventListener('exit', (event) => {
  3326. /** @type {shaka.extern.TimelineRegionInfo} */
  3327. const region = event['region'];
  3328. this.onRegionEvent_(
  3329. shaka.util.FakeEvent.EventName.TimelineRegionExit, region);
  3330. });
  3331. regionObserver.addEventListener('skip', (event) => {
  3332. /** @type {shaka.extern.TimelineRegionInfo} */
  3333. const region = event['region'];
  3334. /** @type {boolean} */
  3335. const seeking = event['seeking'];
  3336. // If we are seeking, we don't want to surface the enter/exit events since
  3337. // they didn't play through them.
  3338. if (!seeking) {
  3339. this.onRegionEvent_(
  3340. shaka.util.FakeEvent.EventName.TimelineRegionEnter, region);
  3341. this.onRegionEvent_(
  3342. shaka.util.FakeEvent.EventName.TimelineRegionExit, region);
  3343. }
  3344. });
  3345. /**
  3346. * @type {!shaka.media.RegionObserver<
  3347. * shaka.extern.MetadataTimelineRegionInfo>}
  3348. */
  3349. const metadataRegionObserver = new shaka.media.RegionObserver(
  3350. this.metadataRegionTimeline_, startsPastZero);
  3351. metadataRegionObserver.addEventListener('enter', (event) => {
  3352. /** @type {shaka.extern.MetadataTimelineRegionInfo} */
  3353. const region = event['region'];
  3354. this.dispatchMetadataEvent_(region);
  3355. });
  3356. /**
  3357. * @type {!shaka.media.RegionObserver<shaka.extern.EmsgTimelineRegionInfo>}
  3358. */
  3359. const emsgRegionObserver = new shaka.media.RegionObserver(
  3360. this.emsgRegionTimeline_, startsPastZero);
  3361. emsgRegionObserver.addEventListener('enter', (event) => {
  3362. /** @type {shaka.extern.EmsgTimelineRegionInfo} */
  3363. const region = event['region'];
  3364. this.dispatchEmsgEvent_(region);
  3365. });
  3366. // Now that we have all our observers, create a manager for them.
  3367. const manager = new shaka.media.PlayheadObserverManager(this.video_);
  3368. manager.manage(regionObserver);
  3369. manager.manage(metadataRegionObserver);
  3370. manager.manage(emsgRegionObserver);
  3371. if (this.qualityObserver_) {
  3372. manager.manage(this.qualityObserver_);
  3373. }
  3374. return manager;
  3375. }
  3376. /**
  3377. * Create the observers for src equals playback. These observers are
  3378. * responsible for notifying the app and player of specific events during src
  3379. * equals playback.
  3380. *
  3381. * @param {number} startTime
  3382. * @return {!shaka.media.PlayheadObserverManager}
  3383. * @private
  3384. */
  3385. createPlayheadObserversForSrcEquals_(startTime) {
  3386. goog.asserts.assert(this.metadataRegionTimeline_,
  3387. 'Must have metadata region timeline');
  3388. goog.asserts.assert(this.video_, 'Must have video element');
  3389. const startsPastZero = startTime > 0;
  3390. /**
  3391. * @type {!shaka.media.RegionObserver<
  3392. * shaka.extern.MetadataTimelineRegionInfo>}
  3393. */
  3394. const metadataRegionObserver = new shaka.media.RegionObserver(
  3395. this.metadataRegionTimeline_, startsPastZero);
  3396. metadataRegionObserver.addEventListener('enter', (event) => {
  3397. /** @type {shaka.extern.MetadataTimelineRegionInfo} */
  3398. const region = event['region'];
  3399. this.dispatchMetadataEvent_(region);
  3400. });
  3401. // Now that we have all our observers, create a manager for them.
  3402. const manager = new shaka.media.PlayheadObserverManager(this.video_);
  3403. manager.manage(metadataRegionObserver);
  3404. return manager;
  3405. }
  3406. /**
  3407. * Initialize and start the buffering system (observer and timer) so that we
  3408. * can monitor our buffer lead during playback.
  3409. *
  3410. * @param {!HTMLMediaElement} mediaElement
  3411. * @param {boolean} srcEquals
  3412. * @private
  3413. */
  3414. startBufferManagement_(mediaElement, srcEquals) {
  3415. goog.asserts.assert(
  3416. !this.bufferObserver_,
  3417. 'No buffering observer should exist before initialization.');
  3418. goog.asserts.assert(
  3419. !this.bufferPoller_,
  3420. 'No buffer timer should exist before initialization.');
  3421. // Give dummy values, will be updated below.
  3422. this.bufferObserver_ = new shaka.media.BufferingObserver(1, 2);
  3423. // Force us back to a buffering state. This ensure everything is starting in
  3424. // the same state.
  3425. this.bufferObserver_.setState(shaka.media.BufferingObserver.State.STARVING);
  3426. this.updateBufferingSettings_();
  3427. this.updateBufferState_();
  3428. this.bufferPoller_ = new shaka.util.Timer(() => {
  3429. this.pollBufferState_();
  3430. });
  3431. if (this.config_.streaming.rebufferingGoal) {
  3432. this.bufferPoller_.tickEvery(/* seconds= */ 0.25);
  3433. }
  3434. this.loadEventManager_.listen(mediaElement, 'waiting',
  3435. (e) => this.pollBufferState_());
  3436. this.loadEventManager_.listen(mediaElement, 'canplaythrough',
  3437. (e) => this.pollBufferState_());
  3438. this.loadEventManager_.listen(mediaElement, 'playing',
  3439. (e) => this.pollBufferState_());
  3440. this.loadEventManager_.listen(mediaElement, 'seeked',
  3441. (e) => this.pollBufferState_());
  3442. if (srcEquals) {
  3443. this.loadEventManager_.listen(mediaElement, 'stalled',
  3444. (e) => this.pollBufferState_());
  3445. this.loadEventManager_.listen(mediaElement, 'progress',
  3446. (e) => this.pollBufferState_());
  3447. this.loadEventManager_.listen(mediaElement, 'timeupdate',
  3448. (e) => this.pollBufferState_());
  3449. }
  3450. }
  3451. /**
  3452. * Updates the buffering thresholds based on the new rebuffering goal.
  3453. *
  3454. * @private
  3455. */
  3456. updateBufferingSettings_() {
  3457. const rebufferingGoal = this.config_.streaming.rebufferingGoal;
  3458. // The threshold to transition back to satisfied when starving.
  3459. const starvingThreshold = rebufferingGoal;
  3460. // The threshold to transition into starving when satisfied.
  3461. // We use a "typical" threshold, unless the rebufferingGoal is unusually
  3462. // low.
  3463. // Then we force the value down to half the rebufferingGoal, since
  3464. // starvingThreshold must be strictly larger than satisfiedThreshold for the
  3465. // logic in BufferingObserver to work correctly.
  3466. const satisfiedThreshold = Math.min(
  3467. shaka.Player.TYPICAL_BUFFERING_THRESHOLD_, rebufferingGoal / 2);
  3468. this.bufferObserver_.setThresholds(starvingThreshold, satisfiedThreshold);
  3469. }
  3470. /**
  3471. * This method is called periodically to check what the buffering observer
  3472. * says so that we can update the rest of the buffering behaviours.
  3473. *
  3474. * @private
  3475. */
  3476. pollBufferState_() {
  3477. goog.asserts.assert(
  3478. this.video_,
  3479. 'Need a media element to update the buffering observer');
  3480. goog.asserts.assert(
  3481. this.bufferObserver_,
  3482. 'Need a buffering observer to update');
  3483. let bufferedToEnd;
  3484. switch (this.loadMode_) {
  3485. case shaka.Player.LoadMode.SRC_EQUALS:
  3486. bufferedToEnd = this.isBufferedToEndSrc_();
  3487. break;
  3488. case shaka.Player.LoadMode.MEDIA_SOURCE:
  3489. bufferedToEnd = this.isBufferedToEndMS_();
  3490. break;
  3491. default:
  3492. bufferedToEnd = false;
  3493. break;
  3494. }
  3495. const bufferLead = shaka.media.TimeRangesUtils.bufferedAheadOf(
  3496. this.video_.buffered,
  3497. this.video_.currentTime);
  3498. const stateChanged = this.bufferObserver_.update(bufferLead, bufferedToEnd);
  3499. // If the state changed, we need to surface the event.
  3500. if (stateChanged) {
  3501. this.updateBufferState_();
  3502. }
  3503. }
  3504. /**
  3505. * Create a new media source engine. This will ONLY be replaced by tests as a
  3506. * way to inject fake media source engine instances.
  3507. *
  3508. * @param {!HTMLMediaElement} mediaElement
  3509. * @param {!shaka.extern.TextDisplayer} textDisplayer
  3510. * @param {!shaka.media.MediaSourceEngine.PlayerInterface} playerInterface
  3511. * @param {shaka.lcevc.Dec} lcevcDec
  3512. *
  3513. * @return {!shaka.media.MediaSourceEngine}
  3514. */
  3515. createMediaSourceEngine(mediaElement, textDisplayer, playerInterface,
  3516. lcevcDec) {
  3517. return new shaka.media.MediaSourceEngine(
  3518. mediaElement,
  3519. textDisplayer,
  3520. playerInterface,
  3521. lcevcDec);
  3522. }
  3523. /**
  3524. * Create a new CMCD manager.
  3525. *
  3526. * @private
  3527. */
  3528. createCmcd_() {
  3529. /** @type {shaka.util.CmcdManager.PlayerInterface} */
  3530. const playerInterface = {
  3531. getBandwidthEstimate: () => this.abrManager_ ?
  3532. this.abrManager_.getBandwidthEstimate() : NaN,
  3533. getBufferedInfo: () => this.getBufferedInfo(),
  3534. getCurrentTime: () => this.video_ ? this.video_.currentTime : 0,
  3535. getPlaybackRate: () => this.getPlaybackRate(),
  3536. getNetworkingEngine: () => this.getNetworkingEngine(),
  3537. getVariantTracks: () => this.getVariantTracks(),
  3538. isLive: () => this.isLive(),
  3539. getLiveLatency: () => this.getLiveLatency(),
  3540. };
  3541. return new shaka.util.CmcdManager(playerInterface, this.config_.cmcd);
  3542. }
  3543. /**
  3544. * Create a new CMSD manager.
  3545. *
  3546. * @private
  3547. */
  3548. createCmsd_() {
  3549. return new shaka.util.CmsdManager(this.config_.cmsd);
  3550. }
  3551. /**
  3552. * Creates a new instance of StreamingEngine. This can be replaced by tests
  3553. * to create fake instances instead.
  3554. *
  3555. * @return {!shaka.media.StreamingEngine}
  3556. */
  3557. createStreamingEngine() {
  3558. goog.asserts.assert(
  3559. this.abrManager_ && this.mediaSourceEngine_ && this.manifest_ &&
  3560. this.video_,
  3561. 'Must not be destroyed');
  3562. /** @type {shaka.media.StreamingEngine.PlayerInterface} */
  3563. const playerInterface = {
  3564. getPresentationTime: () => this.playhead_ ? this.playhead_.getTime() : 0,
  3565. getBandwidthEstimate: () => this.abrManager_.getBandwidthEstimate(),
  3566. getPlaybackRate: () => this.getPlaybackRate(),
  3567. video: this.video_,
  3568. mediaSourceEngine: this.mediaSourceEngine_,
  3569. netEngine: this.networkingEngine_,
  3570. onError: (error) => this.onError_(error),
  3571. onEvent: (event) => this.dispatchEvent(event),
  3572. onSegmentAppended: (reference, stream, isMuxed) => {
  3573. this.onSegmentAppended_(
  3574. reference.startTime, reference.endTime, stream.type, isMuxed);
  3575. },
  3576. onInitSegmentAppended: (position, initSegment) => {
  3577. const mediaQuality = initSegment.getMediaQuality();
  3578. if (mediaQuality && this.qualityObserver_) {
  3579. this.qualityObserver_.addMediaQualityChange(mediaQuality, position);
  3580. }
  3581. },
  3582. beforeAppendSegment: (contentType, segment) => {
  3583. return this.drmEngine_.parseInbandPssh(contentType, segment);
  3584. },
  3585. disableStream: (stream, time) => this.disableStream(stream, time),
  3586. };
  3587. return new shaka.media.StreamingEngine(this.manifest_, playerInterface);
  3588. }
  3589. /**
  3590. * Changes configuration settings on the Player. This checks the names of
  3591. * keys and the types of values to avoid coding errors. If there are errors,
  3592. * this logs them to the console and returns false. Correct fields are still
  3593. * applied even if there are other errors. You can pass an explicit
  3594. * <code>undefined</code> value to restore the default value. This has two
  3595. * modes of operation:
  3596. *
  3597. * <p>
  3598. * First, this can be passed a single "plain" object. This object should
  3599. * follow the {@link shaka.extern.PlayerConfiguration} object. Not all fields
  3600. * need to be set; unset fields retain their old values.
  3601. *
  3602. * <p>
  3603. * Second, this can be passed two arguments. The first is the name of the key
  3604. * to set. This should be a '.' separated path to the key. For example,
  3605. * <code>'streaming.alwaysStreamText'</code>. The second argument is the
  3606. * value to set.
  3607. *
  3608. * @param {string|!Object} config This should either be a field name or an
  3609. * object.
  3610. * @param {*=} value In the second mode, this is the value to set.
  3611. * @return {boolean} True if the passed config object was valid, false if
  3612. * there were invalid entries.
  3613. * @export
  3614. */
  3615. configure(config, value) {
  3616. const Platform = shaka.util.Platform;
  3617. goog.asserts.assert(this.config_, 'Config must not be null!');
  3618. goog.asserts.assert(typeof(config) == 'object' || arguments.length == 2,
  3619. 'String configs should have values!');
  3620. // ('fieldName', value) format
  3621. if (arguments.length == 2 && typeof(config) == 'string') {
  3622. config = shaka.util.ConfigUtils.convertToConfigObject(config, value);
  3623. }
  3624. goog.asserts.assert(typeof(config) == 'object', 'Should be an object!');
  3625. // Deprecate 'streaming.forceTransmuxTS' configuration.
  3626. if (config['streaming'] && 'forceTransmuxTS' in config['streaming']) {
  3627. shaka.Deprecate.deprecateFeature(5,
  3628. 'streaming.forceTransmuxTS configuration',
  3629. 'Please Use mediaSource.forceTransmux instead.');
  3630. config['mediaSource']['mediaSource'] =
  3631. config['streaming']['forceTransmuxTS'];
  3632. delete config['streaming']['forceTransmuxTS'];
  3633. }
  3634. // Deprecate 'streaming.forceTransmux' configuration.
  3635. if (config['streaming'] && 'forceTransmux' in config['streaming']) {
  3636. shaka.Deprecate.deprecateFeature(5,
  3637. 'streaming.forceTransmux configuration',
  3638. 'Please Use mediaSource.forceTransmux instead.');
  3639. config['mediaSource']['mediaSource'] =
  3640. config['streaming']['forceTransmux'];
  3641. delete config['streaming']['forceTransmux'];
  3642. }
  3643. // Deprecate 'streaming.useNativeHlsOnSafari' configuration.
  3644. if (config['streaming'] && 'useNativeHlsOnSafari' in config['streaming']) {
  3645. shaka.Deprecate.deprecateFeature(5,
  3646. 'streaming.useNativeHlsOnSafari configuration',
  3647. 'Please Use streaming.useNativeHlsForFairPlay or ' +
  3648. 'streaming.preferNativeHls instead.');
  3649. config['streaming']['preferNativeHls'] =
  3650. config['streaming']['useNativeHlsOnSafari'] && Platform.isApple();
  3651. delete config['streaming']['useNativeHlsOnSafari'];
  3652. }
  3653. // Deprecate 'streaming.liveSync' boolean configuration.
  3654. if (config['streaming'] &&
  3655. typeof config['streaming']['liveSync'] == 'boolean') {
  3656. shaka.Deprecate.deprecateFeature(5,
  3657. 'streaming.liveSync',
  3658. 'Please Use streaming.liveSync.enabled instead.');
  3659. const liveSyncValue = config['streaming']['liveSync'];
  3660. config['streaming']['liveSync'] = {};
  3661. config['streaming']['liveSync']['enabled'] = liveSyncValue;
  3662. }
  3663. // map liveSyncMinLatency and liveSyncMaxLatency to liveSync.targetLatency
  3664. // if liveSync.targetLatency isn't set.
  3665. if (config['streaming'] && (!config['streaming']['liveSync'] ||
  3666. !('targetLatency' in config['streaming']['liveSync'])) &&
  3667. ('liveSyncMinLatency' in config['streaming'] ||
  3668. 'liveSyncMaxLatency' in config['streaming'])) {
  3669. const min = config['streaming']['liveSyncMinLatency'] || 0;
  3670. const max = config['streaming']['liveSyncMaxLatency'] || 1;
  3671. const mid = Math.abs(max - min) / 2;
  3672. config['streaming']['liveSync'] = config['streaming']['liveSync'] || {};
  3673. config['streaming']['liveSync']['targetLatency'] = min + mid;
  3674. config['streaming']['liveSync']['targetLatencyTolerance'] = mid;
  3675. }
  3676. // Deprecate 'streaming.liveSyncMaxLatency' configuration.
  3677. if (config['streaming'] && 'liveSyncMaxLatency' in config['streaming']) {
  3678. shaka.Deprecate.deprecateFeature(5,
  3679. 'streaming.liveSyncMaxLatency',
  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']['liveSyncMaxLatency'];
  3684. }
  3685. // Deprecate 'streaming.liveSyncMinLatency' configuration.
  3686. if (config['streaming'] && 'liveSyncMinLatency' in config['streaming']) {
  3687. shaka.Deprecate.deprecateFeature(5,
  3688. 'streaming.liveSyncMinLatency',
  3689. 'Please Use streaming.liveSync.targetLatency and ' +
  3690. 'streaming.liveSync.targetLatencyTolerance instead. ' +
  3691. 'Or, set the values in your DASH manifest');
  3692. delete config['streaming']['liveSyncMinLatency'];
  3693. }
  3694. // Deprecate 'streaming.liveSyncTargetLatency' configuration.
  3695. if (config['streaming'] && 'liveSyncTargetLatency' in config['streaming']) {
  3696. shaka.Deprecate.deprecateFeature(5,
  3697. 'streaming.liveSyncTargetLatency',
  3698. 'Please Use streaming.liveSync.targetLatency instead.');
  3699. config['streaming']['liveSync'] = config['streaming']['liveSync'] || {};
  3700. config['streaming']['liveSync']['targetLatency'] =
  3701. config['streaming']['liveSyncTargetLatency'];
  3702. delete config['streaming']['liveSyncTargetLatency'];
  3703. }
  3704. // Deprecate 'streaming.liveSyncTargetLatencyTolerance' configuration.
  3705. if (config['streaming'] &&
  3706. 'liveSyncTargetLatencyTolerance' in config['streaming']) {
  3707. shaka.Deprecate.deprecateFeature(5,
  3708. 'streaming.liveSyncTargetLatencyTolerance',
  3709. 'Please Use streaming.liveSync.targetLatencyTolerance instead.');
  3710. config['streaming']['liveSync'] = config['streaming']['liveSync'] || {};
  3711. config['streaming']['liveSync']['targetLatencyTolerance'] =
  3712. config['streaming']['liveSyncTargetLatencyTolerance'];
  3713. delete config['streaming']['liveSyncTargetLatencyTolerance'];
  3714. }
  3715. // Deprecate 'streaming.liveSyncPlaybackRate' configuration.
  3716. if (config['streaming'] && 'liveSyncPlaybackRate' in config['streaming']) {
  3717. shaka.Deprecate.deprecateFeature(5,
  3718. 'streaming.liveSyncPlaybackRate',
  3719. 'Please Use streaming.liveSync.maxPlaybackRate instead.');
  3720. config['streaming']['liveSync'] = config['streaming']['liveSync'] || {};
  3721. config['streaming']['liveSync']['maxPlaybackRate'] =
  3722. config['streaming']['liveSyncPlaybackRate'];
  3723. delete config['streaming']['liveSyncPlaybackRate'];
  3724. }
  3725. // Deprecate 'streaming.liveSyncMinPlaybackRate' configuration.
  3726. if (config['streaming'] &&
  3727. 'liveSyncMinPlaybackRate' in config['streaming']) {
  3728. shaka.Deprecate.deprecateFeature(5,
  3729. 'streaming.liveSyncMinPlaybackRate',
  3730. 'Please Use streaming.liveSync.minPlaybackRate instead.');
  3731. config['streaming']['liveSync'] = config['streaming']['liveSync'] || {};
  3732. config['streaming']['liveSync']['minPlaybackRate'] =
  3733. config['streaming']['liveSyncMinPlaybackRate'];
  3734. delete config['streaming']['liveSyncMinPlaybackRate'];
  3735. }
  3736. // Deprecate 'streaming.liveSyncPanicMode' configuration.
  3737. if (config['streaming'] && 'liveSyncPanicMode' in config['streaming']) {
  3738. shaka.Deprecate.deprecateFeature(5,
  3739. 'streaming.liveSyncPanicMode',
  3740. 'Please Use streaming.liveSync.panicMode instead.');
  3741. config['streaming']['liveSync'] = config['streaming']['liveSync'] || {};
  3742. config['streaming']['liveSync']['panicMode'] =
  3743. config['streaming']['liveSyncPanicMode'];
  3744. delete config['streaming']['liveSyncPanicMode'];
  3745. }
  3746. // Deprecate 'streaming.liveSyncPanicThreshold' configuration.
  3747. if (config['streaming'] &&
  3748. 'liveSyncPanicThreshold' in config['streaming']) {
  3749. shaka.Deprecate.deprecateFeature(5,
  3750. 'streaming.liveSyncPanicThreshold',
  3751. 'Please Use streaming.liveSync.panicThreshold instead.');
  3752. config['streaming']['liveSync'] = config['streaming']['liveSync'] || {};
  3753. config['streaming']['liveSync']['panicThreshold'] =
  3754. config['streaming']['liveSyncPanicThreshold'];
  3755. delete config['streaming']['liveSyncPanicThreshold'];
  3756. }
  3757. // Deprecate 'mediaSource.sourceBufferExtraFeatures' configuration.
  3758. if (config['mediaSource'] &&
  3759. 'sourceBufferExtraFeatures' in config['mediaSource']) {
  3760. shaka.Deprecate.deprecateFeature(5,
  3761. 'mediaSource.sourceBufferExtraFeatures configuration',
  3762. 'Please Use mediaSource.addExtraFeaturesToSourceBuffer() instead.');
  3763. const sourceBufferExtraFeatures =
  3764. config['mediaSource']['sourceBufferExtraFeatures'];
  3765. config['mediaSource']['addExtraFeaturesToSourceBuffer'] = () => {
  3766. return sourceBufferExtraFeatures;
  3767. };
  3768. delete config['mediaSource']['sourceBufferExtraFeatures'];
  3769. }
  3770. // Deprecate 'manifest.hls.useSafariBehaviorForLive' configuration.
  3771. if (config['manifest'] && config['manifest']['hls'] &&
  3772. 'useSafariBehaviorForLive' in config['manifest']['hls']) {
  3773. shaka.Deprecate.deprecateFeature(5,
  3774. 'manifest.hls.useSafariBehaviorForLive configuration',
  3775. 'Please Use liveSync config to keep on live Edge instead.');
  3776. delete config['manifest']['hls']['useSafariBehaviorForLive'];
  3777. }
  3778. // Deprecate 'streaming.parsePrftBox' configuration.
  3779. if (config['streaming'] && 'parsePrftBox' in config['streaming']) {
  3780. shaka.Deprecate.deprecateFeature(5,
  3781. 'streaming.parsePrftBox configuration',
  3782. 'Now fired without needing a configuration.');
  3783. delete config['streaming']['parsePrftBox'];
  3784. }
  3785. // Deprecate 'manifest.dash.enableAudioGroups' configuration.
  3786. if (config['manifest'] && config['manifest']['dash'] &&
  3787. 'enableAudioGroups' in config['manifest']['dash']) {
  3788. shaka.Deprecate.deprecateFeature(5,
  3789. 'manifest.dash.enableAudioGroups configuration',
  3790. 'It is now enabled by default and cannot be disabled.');
  3791. delete config['manifest']['dash']['enableAudioGroups'];
  3792. }
  3793. // Deprecate 'streaming.dispatchAllEmsgBoxes' configuration.
  3794. if (config['streaming'] && 'dispatchAllEmsgBoxes' in config['streaming']) {
  3795. shaka.Deprecate.deprecateFeature(5,
  3796. 'streaming.dispatchAllEmsgBoxes configuration',
  3797. 'Please Use mediaSource.dispatchAllEmsgBoxes instead.');
  3798. config['mediaSource']['dispatchAllEmsgBoxes'] =
  3799. config['streaming']['dispatchAllEmsgBoxes'];
  3800. delete config['streaming']['dispatchAllEmsgBoxes'];
  3801. }
  3802. // Deprecate 'streaming.autoLowLatencyMode' configuration.
  3803. if (config['streaming'] && 'autoLowLatencyMode' in config['streaming']) {
  3804. shaka.Deprecate.deprecateFeature(5,
  3805. 'streaming.autoLowLatencyMode configuration',
  3806. 'Please Use streaming.lowLatencyMode instead.');
  3807. config['streaming']['lowLatencyMode'] =
  3808. config['streaming']['autoLowLatencyMode'];
  3809. delete config['streaming']['autoLowLatencyMode'];
  3810. }
  3811. // Deprecate 'manifest.dash.ignoreSupplementalCodecs' configuration.
  3812. if (config['manifest'] && config['manifest']['dash'] &&
  3813. 'ignoreSupplementalCodecs' in config['manifest']['dash']) {
  3814. shaka.Deprecate.deprecateFeature(5,
  3815. 'manifest.dash.ignoreSupplementalCodecs configuration',
  3816. 'Please Use manifest.ignoreSupplementalCodecs instead.');
  3817. config['manifest']['ignoreSupplementalCodecs'] =
  3818. config['manifest']['dash']['ignoreSupplementalCodecs'];
  3819. delete config['manifest']['dash']['ignoreSupplementalCodecs'];
  3820. }
  3821. // Deprecate 'manifest.hls.ignoreSupplementalCodecs' configuration.
  3822. if (config['manifest'] && config['manifest']['hls'] &&
  3823. 'ignoreSupplementalCodecs' in config['manifest']['hls']) {
  3824. shaka.Deprecate.deprecateFeature(5,
  3825. 'manifest.hls.ignoreSupplementalCodecs configuration',
  3826. 'Please Use manifest.ignoreSupplementalCodecs instead.');
  3827. config['manifest']['ignoreSupplementalCodecs'] =
  3828. config['manifest']['hls']['ignoreSupplementalCodecs'];
  3829. delete config['manifest']['hls']['ignoreSupplementalCodecs'];
  3830. }
  3831. // Deprecate 'manifest.dash.updatePeriod' configuration.
  3832. if (config['manifest'] && config['manifest']['dash'] &&
  3833. 'updatePeriod' in config['manifest']['dash']) {
  3834. shaka.Deprecate.deprecateFeature(5,
  3835. 'manifest.dash.updatePeriod configuration',
  3836. 'Please Use manifest.updatePeriod instead.');
  3837. config['manifest']['updatePeriod'] =
  3838. config['manifest']['dash']['updatePeriod'];
  3839. delete config['manifest']['dash']['updatePeriod'];
  3840. }
  3841. // Deprecate 'manifest.hls.updatePeriod' configuration.
  3842. if (config['manifest'] && config['manifest']['hls'] &&
  3843. 'updatePeriod' in config['manifest']['hls']) {
  3844. shaka.Deprecate.deprecateFeature(5,
  3845. 'manifest.hls.updatePeriod configuration',
  3846. 'Please Use manifest.updatePeriod instead.');
  3847. config['manifest']['updatePeriod'] =
  3848. config['manifest']['hls']['updatePeriod'];
  3849. delete config['manifest']['hls']['updatePeriod'];
  3850. }
  3851. // Deprecate 'manifest.dash.ignoreDrmInfo' configuration.
  3852. if (config['manifest'] && config['manifest']['dash'] &&
  3853. 'ignoreDrmInfo' in config['manifest']['dash']) {
  3854. shaka.Deprecate.deprecateFeature(5,
  3855. 'manifest.dash.ignoreDrmInfo configuration',
  3856. 'Please Use manifest.ignoreDrmInfo instead.');
  3857. config['manifest']['ignoreDrmInfo'] =
  3858. config['manifest']['dash']['ignoreDrmInfo'];
  3859. delete config['manifest']['dash']['ignoreDrmInfo'];
  3860. }
  3861. // Deprecate AdvancedDrmConfiguration's videoRobustness and audioRobustness
  3862. // as a string. It's now an array of strings.
  3863. if (config['drm'] && config['drm']['advanced']) {
  3864. let fixedUp = false;
  3865. for (const keySystem in config['drm']['advanced']) {
  3866. const {videoRobustness, audioRobustness} =
  3867. config['drm']['advanced'][keySystem];
  3868. if ('videoRobustness' in config['drm']['advanced'][keySystem] &&
  3869. !Array.isArray(
  3870. config['drm']['advanced'][keySystem]['videoRobustness'])) {
  3871. config['drm']['advanced'][keySystem]['videoRobustness'] =
  3872. [videoRobustness];
  3873. fixedUp = true;
  3874. }
  3875. if ('audioRobustness' in config['drm']['advanced'][keySystem] &&
  3876. !Array.isArray(
  3877. config['drm']['advanced'][keySystem]['audioRobustness'])) {
  3878. config['drm']['advanced'][keySystem]['audioRobustness'] =
  3879. [audioRobustness];
  3880. fixedUp = true;
  3881. }
  3882. }
  3883. if (fixedUp) {
  3884. shaka.Deprecate.deprecateFeature(5,
  3885. 'AdvancedDrmConfiguration\'s videoRobustness and audioRobustness',
  3886. 'These properties are no longer strings but array of strings, ' +
  3887. 'please update your usage of these properties.');
  3888. }
  3889. }
  3890. // Enforce inaccurateManifestTolerance: 0 when using crossBoundaryStrategy
  3891. // different from KEEP.
  3892. if (config['streaming'] && 'crossBoundaryStrategy' in config['streaming']) {
  3893. if (config['streaming']['crossBoundaryStrategy'] !=
  3894. shaka.config.CrossBoundaryStrategy.KEEP) {
  3895. config['streaming']['inaccurateManifestTolerance'] = 0;
  3896. }
  3897. }
  3898. const ret = shaka.util.PlayerConfiguration.mergeConfigObjects(
  3899. this.config_, config, this.defaultConfig_());
  3900. this.applyConfig_();
  3901. return ret;
  3902. }
  3903. /**
  3904. * Changes low latency configuration settings on the Player.
  3905. *
  3906. * @param {!Object} config This object should follow the
  3907. * {@link shaka.extern.PlayerConfiguration} object. Not all fields
  3908. * need to be set; unset fields retain their old values.
  3909. * @export
  3910. */
  3911. configurationForLowLatency(config) {
  3912. this.lowLatencyConfig_ = config;
  3913. }
  3914. /**
  3915. * Apply config changes.
  3916. * @private
  3917. */
  3918. applyConfig_() {
  3919. this.manifestFilterer_ = new shaka.media.ManifestFilterer(
  3920. this.config_, this.maxHwRes_, this.drmEngine_);
  3921. if (this.parser_) {
  3922. const manifestConfig =
  3923. shaka.util.ObjectUtils.cloneObject(this.config_.manifest);
  3924. // Don't read video segments if the player is attached to an audio element
  3925. if (this.video_ && this.video_.nodeName === 'AUDIO') {
  3926. manifestConfig.disableVideo = true;
  3927. }
  3928. this.parser_.configure(manifestConfig);
  3929. }
  3930. if (this.drmEngine_) {
  3931. this.drmEngine_.configure(this.config_.drm);
  3932. }
  3933. if (this.streamingEngine_) {
  3934. this.streamingEngine_.configure(this.config_.streaming);
  3935. // Need to apply the restrictions.
  3936. // this.filterManifestWithRestrictions_() may throw.
  3937. try {
  3938. if (this.loadMode_ != shaka.Player.LoadMode.DESTROYED) {
  3939. if (this.manifestFilterer_.filterManifestWithRestrictions(
  3940. this.manifest_)) {
  3941. this.onTracksChanged_();
  3942. }
  3943. }
  3944. } catch (error) {
  3945. this.onError_(error);
  3946. }
  3947. if (this.abrManager_) {
  3948. // Update AbrManager variants to match these new settings.
  3949. this.updateAbrManagerVariants_();
  3950. }
  3951. // If the streams we are playing are restricted, we need to switch.
  3952. const activeVariant = this.streamingEngine_.getCurrentVariant();
  3953. if (activeVariant) {
  3954. if (!activeVariant.allowedByApplication ||
  3955. !activeVariant.allowedByKeySystem) {
  3956. shaka.log.debug('Choosing new variant after changing configuration');
  3957. this.chooseVariantAndSwitch_();
  3958. }
  3959. }
  3960. }
  3961. if (this.networkingEngine_) {
  3962. this.networkingEngine_.setForceHTTP(this.config_.streaming.forceHTTP);
  3963. this.networkingEngine_.setForceHTTPS(this.config_.streaming.forceHTTPS);
  3964. this.networkingEngine_.setMinBytesForProgressEvents(
  3965. this.config_.streaming.minBytesForProgressEvents);
  3966. }
  3967. if (this.mediaSourceEngine_) {
  3968. this.mediaSourceEngine_.configure(this.config_.mediaSource);
  3969. const {segmentRelativeVttTiming} = this.config_.manifest;
  3970. this.mediaSourceEngine_.setSegmentRelativeVttTiming(
  3971. segmentRelativeVttTiming);
  3972. }
  3973. if (this.textDisplayer_) {
  3974. const textDisplayerFactory = this.config_.textDisplayFactory;
  3975. if (this.lastTextFactory_ != textDisplayerFactory) {
  3976. const oldDisplayer = this.textDisplayer_;
  3977. this.textDisplayer_ = textDisplayerFactory();
  3978. if (this.textDisplayer_.configure) {
  3979. this.textDisplayer_.configure(this.config_.textDisplayer);
  3980. } else {
  3981. shaka.Deprecate.deprecateFeature(5,
  3982. 'Text displayer w/ configure',
  3983. 'Text displayer should have a "configure" method!');
  3984. }
  3985. if (!this.textDisplayer_.setTextLanguage) {
  3986. shaka.Deprecate.deprecateFeature(5,
  3987. 'Text displayer w/ setTextLanguage',
  3988. 'Text displayer should have a "setTextLanguage" method!');
  3989. }
  3990. this.textDisplayer_.setTextVisibility(oldDisplayer.isTextVisible());
  3991. oldDisplayer.destroy();
  3992. if (this.mediaSourceEngine_) {
  3993. this.mediaSourceEngine_.setTextDisplayer(this.textDisplayer_);
  3994. }
  3995. this.lastTextFactory_ = textDisplayerFactory;
  3996. if (this.streamingEngine_) {
  3997. // Reload the text stream, so the cues will load again.
  3998. this.streamingEngine_.reloadTextStream();
  3999. }
  4000. } else {
  4001. if (this.textDisplayer_.configure) {
  4002. this.textDisplayer_.configure(this.config_.textDisplayer);
  4003. }
  4004. }
  4005. }
  4006. if (this.abrManager_) {
  4007. this.abrManager_.configure(this.config_.abr);
  4008. // Simply enable/disable ABR with each call, since multiple calls to these
  4009. // methods have no effect.
  4010. if (this.config_.abr.enabled) {
  4011. this.abrManager_.enable();
  4012. } else {
  4013. this.abrManager_.disable();
  4014. }
  4015. this.onAbrStatusChanged_();
  4016. }
  4017. if (this.bufferObserver_) {
  4018. this.updateBufferingSettings_();
  4019. }
  4020. if (this.bufferPoller_) {
  4021. if (!this.config_.streaming.rebufferingGoal) {
  4022. this.bufferPoller_.stop();
  4023. } else {
  4024. this.bufferPoller_.tickEvery(/* seconds= */ 0.25);
  4025. }
  4026. }
  4027. if (this.manifest_) {
  4028. shaka.Player.applyPlayRange_(this.manifest_.presentationTimeline,
  4029. this.config_.playRangeStart,
  4030. this.config_.playRangeEnd);
  4031. }
  4032. if (this.adManager_) {
  4033. this.adManager_.configure(this.config_.ads);
  4034. }
  4035. if (this.cmcdManager_) {
  4036. this.cmcdManager_.configure(this.config_.cmcd);
  4037. }
  4038. if (this.cmsdManager_) {
  4039. this.cmsdManager_.configure(this.config_.cmsd);
  4040. }
  4041. }
  4042. /**
  4043. * Return a copy of the current configuration. Modifications of the returned
  4044. * value will not affect the Player's active configuration. You must call
  4045. * <code>player.configure()</code> to make changes.
  4046. *
  4047. * @return {shaka.extern.PlayerConfiguration}
  4048. * @export
  4049. */
  4050. getConfiguration() {
  4051. goog.asserts.assert(this.config_, 'Config must not be null!');
  4052. const ret = this.defaultConfig_();
  4053. shaka.util.PlayerConfiguration.mergeConfigObjects(
  4054. ret, this.config_, this.defaultConfig_());
  4055. return ret;
  4056. }
  4057. /**
  4058. * Return a copy of the current configuration for low latency.
  4059. *
  4060. * @return {!Object}
  4061. * @export
  4062. */
  4063. getConfigurationForLowLatency() {
  4064. return this.lowLatencyConfig_;
  4065. }
  4066. /**
  4067. * Return a copy of the current non default configuration. Modifications of
  4068. * the returned value will not affect the Player's active configuration.
  4069. * You must call <code>player.configure()</code> to make changes.
  4070. *
  4071. * @return {!Object}
  4072. * @export
  4073. */
  4074. getNonDefaultConfiguration() {
  4075. goog.asserts.assert(this.config_, 'Config must not be null!');
  4076. const ret = this.defaultConfig_();
  4077. shaka.util.PlayerConfiguration.mergeConfigObjects(
  4078. ret, this.config_, this.defaultConfig_());
  4079. return shaka.util.ConfigUtils.getDifferenceFromConfigObjects(
  4080. this.config_, this.defaultConfig_());
  4081. }
  4082. /**
  4083. * Return a reference to the current configuration. Modifications to the
  4084. * returned value will affect the Player's active configuration. This method
  4085. * is not exported as sharing configuration with external objects is not
  4086. * supported.
  4087. *
  4088. * @return {shaka.extern.PlayerConfiguration}
  4089. */
  4090. getSharedConfiguration() {
  4091. goog.asserts.assert(
  4092. this.config_, 'Cannot call getSharedConfiguration after call destroy!');
  4093. return this.config_;
  4094. }
  4095. /**
  4096. * Returns the ratio of video length buffered compared to buffering Goal
  4097. * @return {number}
  4098. * @export
  4099. */
  4100. getBufferFullness() {
  4101. if (this.video_) {
  4102. const bufferedLength = this.video_.buffered.length;
  4103. const bufferedEnd =
  4104. bufferedLength ? this.video_.buffered.end(bufferedLength - 1) : 0;
  4105. const bufferingGoal = this.getConfiguration().streaming.bufferingGoal;
  4106. const lengthToBeBuffered = Math.min(this.video_.currentTime +
  4107. bufferingGoal, this.seekRange().end);
  4108. if (bufferedEnd >= lengthToBeBuffered) {
  4109. return 1;
  4110. } else if (bufferedEnd <= this.video_.currentTime) {
  4111. return 0;
  4112. } else if (bufferedEnd < lengthToBeBuffered) {
  4113. return ((bufferedEnd - this.video_.currentTime) /
  4114. (lengthToBeBuffered - this.video_.currentTime));
  4115. }
  4116. }
  4117. return 0;
  4118. }
  4119. /**
  4120. * Reset configuration to default.
  4121. * @export
  4122. */
  4123. resetConfiguration() {
  4124. goog.asserts.assert(this.config_, 'Cannot be destroyed');
  4125. // Remove the old keys so we remove open-ended dictionaries like drm.servers
  4126. // but keeps the same object reference.
  4127. for (const key in this.config_) {
  4128. delete this.config_[key];
  4129. }
  4130. shaka.util.PlayerConfiguration.mergeConfigObjects(
  4131. this.config_, this.defaultConfig_(), this.defaultConfig_());
  4132. this.applyConfig_();
  4133. }
  4134. /**
  4135. * Get the current load mode.
  4136. *
  4137. * @return {shaka.Player.LoadMode}
  4138. * @export
  4139. */
  4140. getLoadMode() {
  4141. return this.loadMode_;
  4142. }
  4143. /**
  4144. * Get the current manifest type.
  4145. *
  4146. * @return {?string}
  4147. * @export
  4148. */
  4149. getManifestType() {
  4150. if (!this.manifest_) {
  4151. return null;
  4152. }
  4153. return this.manifest_.type;
  4154. }
  4155. /**
  4156. * Get the media element that the player is currently using to play loaded
  4157. * content. If the player has not loaded content, this will return
  4158. * <code>null</code>.
  4159. *
  4160. * @return {HTMLMediaElement}
  4161. * @export
  4162. */
  4163. getMediaElement() {
  4164. return this.video_;
  4165. }
  4166. /**
  4167. * @return {shaka.net.NetworkingEngine} A reference to the Player's networking
  4168. * engine. Applications may use this to make requests through Shaka's
  4169. * networking plugins.
  4170. * @export
  4171. */
  4172. getNetworkingEngine() {
  4173. return this.networkingEngine_;
  4174. }
  4175. /**
  4176. * Get the uri to the asset that the player has loaded. If the player has not
  4177. * loaded content, this will return <code>null</code>.
  4178. *
  4179. * @return {?string}
  4180. * @export
  4181. */
  4182. getAssetUri() {
  4183. return this.assetUri_;
  4184. }
  4185. /**
  4186. * Returns a shaka.ads.AdManager instance, responsible for Dynamic
  4187. * Ad Insertion functionality.
  4188. *
  4189. * @return {shaka.extern.IAdManager}
  4190. * @export
  4191. */
  4192. getAdManager() {
  4193. // NOTE: this clause is redundant, but it keeps the compiler from
  4194. // inlining this function. Inlining leads to setting the adManager
  4195. // not taking effect in the compiled build.
  4196. // Closure has a @noinline flag, but apparently not all cases are
  4197. // supported by it, and ours isn't.
  4198. // If they expand support, we might be able to get rid of this
  4199. // clause.
  4200. if (!this.adManager_) {
  4201. return null;
  4202. }
  4203. return this.adManager_;
  4204. }
  4205. /**
  4206. * Get if the player is playing live content. If the player has not loaded
  4207. * content, this will return <code>false</code>.
  4208. *
  4209. * @return {boolean}
  4210. * @export
  4211. */
  4212. isLive() {
  4213. if (this.manifest_ && !this.isRemotePlayback()) {
  4214. return this.manifest_.presentationTimeline.isLive();
  4215. }
  4216. // For native HLS, the duration for live streams seems to be Infinity.
  4217. if (this.video_ && this.video_.src) {
  4218. return this.video_.duration == Infinity;
  4219. }
  4220. return false;
  4221. }
  4222. /**
  4223. * Get if the player is playing in-progress content. If the player has not
  4224. * loaded content, this will return <code>false</code>.
  4225. *
  4226. * @return {boolean}
  4227. * @export
  4228. */
  4229. isInProgress() {
  4230. return this.manifest_ ?
  4231. this.manifest_.presentationTimeline.isInProgress() :
  4232. false;
  4233. }
  4234. /**
  4235. * Check if the manifest contains only audio-only content. If the player has
  4236. * not loaded content, this will return <code>false</code>.
  4237. *
  4238. * <p>
  4239. * The player does not support content that contain more than one type of
  4240. * variants (i.e. mixing audio-only, video-only, audio-video). Content will be
  4241. * filtered to only contain one type of variant.
  4242. *
  4243. * @return {boolean}
  4244. * @export
  4245. */
  4246. isAudioOnly() {
  4247. if (this.manifest_ && !this.isRemotePlayback()) {
  4248. const variants = this.manifest_.variants;
  4249. if (!variants.length) {
  4250. return false;
  4251. }
  4252. // Note that if there are some audio-only variants and some audio-video
  4253. // variants, the audio-only variants are removed during filtering.
  4254. // Therefore if the first variant has no video, that's sufficient to say
  4255. // it is audio-only content.
  4256. return !variants[0].video;
  4257. } else if (this.video_ && this.video_.src) {
  4258. // If we have video track info, use that. It will be the least
  4259. // error-prone way with native HLS. In contrast, videoHeight might be
  4260. // unset until the first frame is loaded. Since isAudioOnly is queried
  4261. // by the UI on the 'trackschanged' event, the videoTracks info should be
  4262. // up-to-date.
  4263. if (this.video_.videoTracks) {
  4264. return this.video_.videoTracks.length == 0;
  4265. }
  4266. // We cast to the more specific HTMLVideoElement to access videoHeight.
  4267. // This might be an audio element, though, in which case videoHeight will
  4268. // be undefined at runtime. For audio elements, this will always return
  4269. // true.
  4270. const video = /** @type {HTMLVideoElement} */(this.video_);
  4271. return video.videoHeight == 0;
  4272. } else {
  4273. return false;
  4274. }
  4275. }
  4276. /**
  4277. * Get the range of time (in seconds) that seeking is allowed. If the player
  4278. * has not loaded content and the manifest is HLS, this will return a range
  4279. * from 0 to 0.
  4280. *
  4281. * @return {{start: number, end: number}}
  4282. * @export
  4283. */
  4284. seekRange() {
  4285. if (this.manifest_ && !this.isRemotePlayback()) {
  4286. // With HLS lazy-loading, there were some situations where the manifest
  4287. // had partially loaded, enough to move onto further load stages, but no
  4288. // segments had been loaded, so the timeline is still unknown.
  4289. // See: https://github.com/shaka-project/shaka-player/pull/4590
  4290. if (!this.fullyLoaded_ &&
  4291. this.manifest_.type == shaka.media.ManifestParser.HLS) {
  4292. return {'start': 0, 'end': 0};
  4293. }
  4294. const timeline = this.manifest_.presentationTimeline;
  4295. return {
  4296. 'start': timeline.getSeekRangeStart(),
  4297. 'end': timeline.getSeekRangeEnd(),
  4298. };
  4299. }
  4300. // If we have loaded content with src=, we ask the video element for its
  4301. // seekable range. This covers both plain mp4s and native HLS playbacks.
  4302. if (this.video_ && this.video_.src) {
  4303. const seekable = this.video_.seekable;
  4304. if (seekable && seekable.length) {
  4305. const playRangeStart =
  4306. this.config_ ? this.config_.playRangeStart : 0;
  4307. const start = Math.max(seekable.start(0), playRangeStart);
  4308. const playRangeEnd =
  4309. this.config_ ? this.config_.playRangeEnd : Infinity;
  4310. const end = Math.min(seekable.end(seekable.length - 1), playRangeEnd);
  4311. return {
  4312. 'start': start,
  4313. 'end': end,
  4314. };
  4315. }
  4316. }
  4317. return {'start': 0, 'end': 0};
  4318. }
  4319. /**
  4320. * Go to live in a live stream.
  4321. *
  4322. * @export
  4323. */
  4324. goToLive() {
  4325. if (this.isLive()) {
  4326. this.video_.currentTime = this.seekRange().end;
  4327. } else {
  4328. shaka.log.warning('goToLive is for live streams!');
  4329. }
  4330. }
  4331. /**
  4332. * Indicates if the player has fully loaded the stream.
  4333. *
  4334. * @return {boolean}
  4335. * @export
  4336. */
  4337. isFullyLoaded() {
  4338. return this.fullyLoaded_;
  4339. }
  4340. /**
  4341. * Get the key system currently used by EME. If EME is not being used, this
  4342. * will return an empty string. If the player has not loaded content, this
  4343. * will return an empty string.
  4344. *
  4345. * @return {string}
  4346. * @export
  4347. */
  4348. keySystem() {
  4349. return shaka.drm.DrmUtils.keySystem(this.drmInfo());
  4350. }
  4351. /**
  4352. * Get the drm info used to initialize EME. If EME is not being used, this
  4353. * will return <code>null</code>. If the player is idle or has not initialized
  4354. * EME yet, this will return <code>null</code>.
  4355. *
  4356. * @return {?shaka.extern.DrmInfo}
  4357. * @export
  4358. */
  4359. drmInfo() {
  4360. return this.drmEngine_ ? this.drmEngine_.getDrmInfo() : null;
  4361. }
  4362. /**
  4363. * Get the drm engine.
  4364. * This method should only be used for testing. Applications SHOULD NOT
  4365. * use this in production.
  4366. *
  4367. * @return {?shaka.drm.DrmEngine}
  4368. */
  4369. getDrmEngine() {
  4370. return this.drmEngine_;
  4371. }
  4372. /**
  4373. * Get the next known expiration time for any EME session. If the session
  4374. * never expires, this will return <code>Infinity</code>. If there are no EME
  4375. * sessions, this will return <code>Infinity</code>. If the player has not
  4376. * loaded content, this will return <code>Infinity</code>.
  4377. *
  4378. * @return {number}
  4379. * @export
  4380. */
  4381. getExpiration() {
  4382. return this.drmEngine_ ? this.drmEngine_.getExpiration() : Infinity;
  4383. }
  4384. /**
  4385. * Returns the active sessions metadata
  4386. *
  4387. * @return {!Array<shaka.extern.DrmSessionMetadata>}
  4388. * @export
  4389. */
  4390. getActiveSessionsMetadata() {
  4391. return this.drmEngine_ ? this.drmEngine_.getActiveSessionsMetadata() : [];
  4392. }
  4393. /**
  4394. * Gets a map of EME key ID to the current key status.
  4395. *
  4396. * @return {!Object<string, string>}
  4397. * @export
  4398. */
  4399. getKeyStatuses() {
  4400. return this.drmEngine_ ? this.drmEngine_.getKeyStatuses() : {};
  4401. }
  4402. /**
  4403. * Check if the player is currently in a buffering state (has too little
  4404. * content to play smoothly). If the player has not loaded content, this will
  4405. * return <code>false</code>.
  4406. *
  4407. * @return {boolean}
  4408. * @export
  4409. */
  4410. isBuffering() {
  4411. const State = shaka.media.BufferingObserver.State;
  4412. return this.bufferObserver_ ?
  4413. this.bufferObserver_.getState() == State.STARVING :
  4414. false;
  4415. }
  4416. /**
  4417. * Get the playback rate of what is playing right now. If we are using trick
  4418. * play, this will return the trick play rate.
  4419. * If no content is playing, this will return 0.
  4420. * If content is buffering, this will return the expected playback rate once
  4421. * the video starts playing.
  4422. *
  4423. * <p>
  4424. * If the player has not loaded content, this will return a playback rate of
  4425. * 0.
  4426. *
  4427. * @return {number}
  4428. * @export
  4429. */
  4430. getPlaybackRate() {
  4431. if (!this.video_) {
  4432. return 0;
  4433. }
  4434. return this.playRateController_ ?
  4435. this.playRateController_.getRealRate() :
  4436. 1;
  4437. }
  4438. /**
  4439. * Enable trick play to skip through content without playing by repeatedly
  4440. * seeking. For example, a rate of 2.5 would result in 2.5 seconds of content
  4441. * being skipped every second. A negative rate will result in moving
  4442. * backwards.
  4443. *
  4444. * <p>
  4445. * If the player has not loaded content or is still loading content this will
  4446. * be a no-op. Wait until <code>load</code> has completed before calling.
  4447. *
  4448. * <p>
  4449. * Trick play will be canceled automatically if the playhead hits the
  4450. * beginning or end of the seekable range for the content.
  4451. *
  4452. * @param {number} rate
  4453. * @param {boolean=} useTrickPlayTrack
  4454. * @export
  4455. */
  4456. trickPlay(rate, useTrickPlayTrack = true) {
  4457. // A playbackRate of 0 is used internally when we are in a buffering state,
  4458. // and doesn't make sense for trick play. If you set a rate of 0 for trick
  4459. // play, we will reject it and issue a warning. If it happens during a
  4460. // test, we will fail the test through this assertion.
  4461. goog.asserts.assert(rate != 0, 'Should never set a trick play rate of 0!');
  4462. if (rate == 0) {
  4463. shaka.log.alwaysWarn('A trick play rate of 0 is unsupported!');
  4464. return;
  4465. }
  4466. this.playRateController_.set(rate);
  4467. if (this.loadMode_ == shaka.Player.LoadMode.MEDIA_SOURCE) {
  4468. this.abrManager_.playbackRateChanged(rate);
  4469. this.streamingEngine_.setTrickPlay(
  4470. useTrickPlayTrack && Math.abs(rate) > 1);
  4471. }
  4472. this.setupTrickPlayEventListeners_(rate);
  4473. }
  4474. /**
  4475. * Cancel trick-play. If the player has not loaded content or is still loading
  4476. * content this will be a no-op.
  4477. *
  4478. * @export
  4479. */
  4480. cancelTrickPlay() {
  4481. const defaultPlaybackRate = this.playRateController_.getDefaultRate();
  4482. if (this.loadMode_ == shaka.Player.LoadMode.SRC_EQUALS) {
  4483. this.playRateController_.set(defaultPlaybackRate);
  4484. }
  4485. if (this.loadMode_ == shaka.Player.LoadMode.MEDIA_SOURCE) {
  4486. this.playRateController_.set(defaultPlaybackRate);
  4487. this.abrManager_.playbackRateChanged(defaultPlaybackRate);
  4488. this.streamingEngine_.setTrickPlay(false);
  4489. }
  4490. this.trickPlayEventManager_.removeAll();
  4491. }
  4492. /**
  4493. * Return a list of variant tracks that can be switched to.
  4494. *
  4495. * <p>
  4496. * If the player has not loaded content, this will return an empty list.
  4497. *
  4498. * @return {!Array<shaka.extern.Track>}
  4499. * @export
  4500. */
  4501. getVariantTracks() {
  4502. if (this.manifest_ && !this.isRemotePlayback()) {
  4503. const currentVariant = this.streamingEngine_ ?
  4504. this.streamingEngine_.getCurrentVariant() : null;
  4505. const tracks = [];
  4506. let activeTracks = 0;
  4507. // Convert each variant to a track.
  4508. for (const variant of this.manifest_.variants) {
  4509. if (!shaka.util.StreamUtils.isPlayable(variant)) {
  4510. continue;
  4511. }
  4512. const track = shaka.util.StreamUtils.variantToTrack(variant);
  4513. track.active = variant == currentVariant;
  4514. if (!track.active && activeTracks != 1 && currentVariant != null &&
  4515. variant.video == currentVariant.video &&
  4516. variant.audio == currentVariant.audio) {
  4517. track.active = true;
  4518. }
  4519. if (track.active) {
  4520. activeTracks++;
  4521. }
  4522. tracks.push(track);
  4523. }
  4524. goog.asserts.assert(activeTracks <= 1,
  4525. 'It should only have one active track');
  4526. return tracks;
  4527. } else if (this.video_ && this.video_.audioTracks) {
  4528. // Safari's native HLS always shows a single element in videoTracks.
  4529. // You can't use that API to change resolutions. But we can use
  4530. // audioTracks to generate a variant list that is usable for changing
  4531. // languages.
  4532. const audioTracks = Array.from(this.video_.audioTracks);
  4533. return audioTracks.map((audio) =>
  4534. shaka.util.StreamUtils.html5AudioTrackToTrack(audio));
  4535. } else {
  4536. return [];
  4537. }
  4538. }
  4539. /**
  4540. * Return a list of text tracks that can be switched to.
  4541. *
  4542. * <p>
  4543. * If the player has not loaded content, this will return an empty list.
  4544. *
  4545. * @return {!Array<shaka.extern.Track>}
  4546. * @export
  4547. */
  4548. getTextTracks() {
  4549. if (this.manifest_ && !this.isRemotePlayback()) {
  4550. const currentTextStream = this.streamingEngine_ ?
  4551. this.streamingEngine_.getCurrentTextStream() : null;
  4552. const tracks = [];
  4553. // Convert all selectable text streams to tracks.
  4554. for (const text of this.manifest_.textStreams) {
  4555. const track = shaka.util.StreamUtils.textStreamToTrack(text);
  4556. track.active = text == currentTextStream;
  4557. tracks.push(track);
  4558. }
  4559. return tracks;
  4560. } else if (this.video_ && this.video_.src && this.video_.textTracks) {
  4561. const textTracks = this.getFilteredTextTracks_();
  4562. const StreamUtils = shaka.util.StreamUtils;
  4563. return textTracks.map((text) => StreamUtils.html5TextTrackToTrack(text));
  4564. } else {
  4565. return [];
  4566. }
  4567. }
  4568. /**
  4569. * Return a list of image tracks that can be switched to.
  4570. *
  4571. * If the player has not loaded content, this will return an empty list.
  4572. *
  4573. * @return {!Array<shaka.extern.Track>}
  4574. * @export
  4575. */
  4576. getImageTracks() {
  4577. const StreamUtils = shaka.util.StreamUtils;
  4578. let imageStreams = this.externalSrcEqualsThumbnailsStreams_;
  4579. if (this.manifest_) {
  4580. imageStreams = this.manifest_.imageStreams;
  4581. }
  4582. return imageStreams.map((image) => StreamUtils.imageStreamToTrack(image));
  4583. }
  4584. /**
  4585. * Returns Thumbnail objects for each thumbnail.
  4586. *
  4587. * If the player has not loaded content, this will return a null.
  4588. *
  4589. * @param {?number=} trackId
  4590. * @return {!Promise<?Array<!shaka.extern.Thumbnail>>}
  4591. * @export
  4592. */
  4593. async getAllThumbnails(trackId) {
  4594. const imageStream = await this.getBestImageStream_(trackId);
  4595. if (!imageStream) {
  4596. return null;
  4597. }
  4598. const thumbnails = [];
  4599. imageStream.segmentIndex.forEachTopLevelReference((reference) => {
  4600. const dimensions = this.parseTilesLayout_(
  4601. reference.getTilesLayout() || imageStream.tilesLayout);
  4602. if (dimensions) {
  4603. const numThumbnails = dimensions.rows * dimensions.columns;
  4604. const duration = reference.trueEndTime - reference.startTime;
  4605. for (let i = 0; i < numThumbnails; i++) {
  4606. const sampleTime = reference.startTime + duration * i / numThumbnails;
  4607. const thumbnail =
  4608. this.getThumbnailsByStream_(
  4609. /** @type {shaka.extern.Stream} */ (imageStream), sampleTime);
  4610. if (thumbnail) {
  4611. thumbnails.push(thumbnail);
  4612. }
  4613. }
  4614. }
  4615. });
  4616. if (imageStream.closeSegmentIndex) {
  4617. imageStream.closeSegmentIndex();
  4618. }
  4619. return thumbnails;
  4620. }
  4621. /**
  4622. * Parses a tiles layout.
  4623. *
  4624. * @param {string|undefined} tilesLayout
  4625. * @return {?{
  4626. * columns: number,
  4627. * rows: number
  4628. * }}
  4629. * @private
  4630. */
  4631. parseTilesLayout_(tilesLayout) {
  4632. if (!tilesLayout) {
  4633. return null;
  4634. }
  4635. // This expression is used to detect one or more numbers (0-9) followed
  4636. // by an x and after one or more numbers (0-9)
  4637. const match = /(\d+)x(\d+)/.exec(tilesLayout);
  4638. if (!match) {
  4639. shaka.log.warning('Tiles layout does not contain a valid format ' +
  4640. ' (columns x rows)');
  4641. return null;
  4642. }
  4643. const columns = parseInt(match[1], 10);
  4644. const rows = parseInt(match[2], 10);
  4645. return {columns, rows};
  4646. }
  4647. /**
  4648. * Return a Thumbnail object from a time.
  4649. *
  4650. * If the player has not loaded content, this will return a null.
  4651. *
  4652. * @param {?number} trackId
  4653. * @param {number} time
  4654. * @return {!Promise<?shaka.extern.Thumbnail>}
  4655. * @export
  4656. */
  4657. async getThumbnails(trackId, time) {
  4658. const imageStream = await this.getBestImageStream_(trackId);
  4659. if (!imageStream) {
  4660. return null;
  4661. }
  4662. return this.getThumbnailsByStream_(imageStream, time);
  4663. }
  4664. /**
  4665. * Return a the best image stream from an optional trackId.
  4666. *
  4667. * If the player has not loaded content, this will return a null.
  4668. *
  4669. * @param {?number=} trackId
  4670. * @return {!Promise<?shaka.extern.Stream>}
  4671. * @private
  4672. */
  4673. async getBestImageStream_(trackId) {
  4674. if (this.loadMode_ != shaka.Player.LoadMode.MEDIA_SOURCE &&
  4675. this.loadMode_ != shaka.Player.LoadMode.SRC_EQUALS) {
  4676. return null;
  4677. }
  4678. let imageStreams = this.externalSrcEqualsThumbnailsStreams_;
  4679. if (this.manifest_) {
  4680. imageStreams = this.manifest_.imageStreams;
  4681. }
  4682. let imageStream = imageStreams[0];
  4683. if (!imageStream) {
  4684. return null;
  4685. }
  4686. if (trackId != null) {
  4687. imageStream = imageStreams.find(
  4688. (stream) => stream.id == trackId);
  4689. }
  4690. if (!imageStream) {
  4691. return null;
  4692. }
  4693. if (!imageStream.segmentIndex) {
  4694. await imageStream.createSegmentIndex();
  4695. }
  4696. return imageStream;
  4697. }
  4698. /**
  4699. * Return a Thumbnail object from a image stream and time.
  4700. *
  4701. * @param {shaka.extern.Stream} imageStream
  4702. * @param {number} time
  4703. * @return {?shaka.extern.Thumbnail}
  4704. * @private
  4705. */
  4706. getThumbnailsByStream_(imageStream, time) {
  4707. const referencePosition = imageStream.segmentIndex.find(time);
  4708. if (referencePosition == null) {
  4709. return null;
  4710. }
  4711. const reference = imageStream.segmentIndex.get(referencePosition);
  4712. const dimensions = this.parseTilesLayout_(
  4713. reference.getTilesLayout() || imageStream.tilesLayout);
  4714. if (!dimensions) {
  4715. return null;
  4716. }
  4717. const fullImageWidth = imageStream.width || 0;
  4718. const fullImageHeight = imageStream.height || 0;
  4719. let width = fullImageWidth / dimensions.columns;
  4720. let height = fullImageHeight / dimensions.rows;
  4721. const totalImages = dimensions.columns * dimensions.rows;
  4722. const segmentDuration = reference.trueEndTime - reference.startTime;
  4723. const thumbnailDuration =
  4724. reference.getTileDuration() || (segmentDuration / totalImages);
  4725. let thumbnailTime = reference.startTime;
  4726. let positionX = 0;
  4727. let positionY = 0;
  4728. // If the number of images in the segment is greater than 1, we have to
  4729. // find the correct image. For that we will return to the app the
  4730. // coordinates of the position of the correct image.
  4731. // Image search is always from left to right and top to bottom.
  4732. // Note: The time between images within the segment is always
  4733. // equidistant.
  4734. //
  4735. // Eg: Total images 5, tileLayout 5x1, segmentDuration 5, thumbnailTime 2
  4736. // positionX = 0.4 * fullImageWidth
  4737. // positionY = 0
  4738. if (totalImages > 1) {
  4739. const thumbnailPosition =
  4740. Math.floor((time - reference.startTime) / thumbnailDuration);
  4741. thumbnailTime = reference.startTime +
  4742. (thumbnailPosition * thumbnailDuration);
  4743. positionX = (thumbnailPosition % dimensions.columns) * width;
  4744. positionY = Math.floor(thumbnailPosition / dimensions.columns) * height;
  4745. }
  4746. let sprite = false;
  4747. const thumbnailSprite = reference.getThumbnailSprite();
  4748. if (thumbnailSprite) {
  4749. sprite = true;
  4750. height = thumbnailSprite.height;
  4751. positionX = thumbnailSprite.positionX;
  4752. positionY = thumbnailSprite.positionY;
  4753. width = thumbnailSprite.width;
  4754. }
  4755. return {
  4756. segment: reference,
  4757. imageHeight: fullImageHeight,
  4758. imageWidth: fullImageWidth,
  4759. height: height,
  4760. positionX: positionX,
  4761. positionY: positionY,
  4762. startTime: thumbnailTime,
  4763. duration: thumbnailDuration,
  4764. uris: reference.getUris(),
  4765. width: width,
  4766. sprite: sprite,
  4767. mimeType: reference.mimeType || imageStream.mimeType,
  4768. codecs: reference.codecs || imageStream.codecs,
  4769. };
  4770. }
  4771. /**
  4772. * Select a specific text track. <code>track</code> should come from a call to
  4773. * <code>getTextTracks</code>. If the track is not found, this will be a
  4774. * no-op. If the player has not loaded content, this will be a no-op.
  4775. *
  4776. * <p>
  4777. * Note that <code>AdaptationEvents</code> are not fired for manual track
  4778. * selections.
  4779. *
  4780. * @param {shaka.extern.Track} track
  4781. * @export
  4782. */
  4783. selectTextTrack(track) {
  4784. const selectMediaSourceMode = () => {
  4785. const stream = this.manifest_.textStreams.find(
  4786. (stream) => stream.id == track.id);
  4787. if (!stream) {
  4788. if (!this.isRemotePlayback()) {
  4789. shaka.log.error('No stream with id', track.id);
  4790. }
  4791. return;
  4792. }
  4793. if (stream == this.streamingEngine_.getCurrentTextStream()) {
  4794. shaka.log.debug('Text track already selected.');
  4795. return;
  4796. }
  4797. // Add entries to the history.
  4798. this.addTextStreamToSwitchHistory_(stream, /* fromAdaptation= */ false);
  4799. this.streamingEngine_.switchTextStream(stream);
  4800. this.onTextChanged_();
  4801. this.setTextDisplayerLanguage_();
  4802. // Workaround for
  4803. // https://github.com/shaka-project/shaka-player/issues/1299
  4804. // When track is selected, back-propagate the language to
  4805. // currentTextLanguage_.
  4806. this.currentTextLanguage_ = stream.language;
  4807. };
  4808. const selectSrcEqualsMode = () => {
  4809. if (this.video_ && this.video_.textTracks) {
  4810. const textTracks = this.getFilteredTextTracks_();
  4811. const oldTrack = textTracks.find((textTrack) =>
  4812. textTrack.mode !== 'disabled');
  4813. const newTrack = textTracks.find((textTrack) =>
  4814. shaka.util.StreamUtils.html5TrackId(textTrack) === track.id);
  4815. if (!newTrack) {
  4816. shaka.log.error('No track with id', track.id);
  4817. return;
  4818. }
  4819. if (oldTrack !== newTrack) {
  4820. if (oldTrack) {
  4821. oldTrack.mode = 'disabled';
  4822. this.loadEventManager_.unlisten(oldTrack, 'cuechange');
  4823. this.textDisplayer_.remove(0, Infinity);
  4824. }
  4825. if (newTrack) {
  4826. this.enableNativeTrack_(newTrack);
  4827. }
  4828. }
  4829. this.onTextChanged_();
  4830. this.setTextDisplayerLanguage_();
  4831. }
  4832. };
  4833. if (this.manifest_ && this.playhead_) {
  4834. selectMediaSourceMode();
  4835. // When using MSE + remote we need to set tracks for both MSE and native
  4836. // apis so that synchronization is maintained.
  4837. if (!this.isRemotePlayback()) {
  4838. return;
  4839. }
  4840. }
  4841. selectSrcEqualsMode();
  4842. }
  4843. /**
  4844. * @param {!TextTrack} track
  4845. * @private
  4846. */
  4847. enableNativeTrack_(track) {
  4848. this.loadEventManager_.listen(track, 'cuechange', () => {
  4849. // Always remove cues from the past to avoid memory grow.
  4850. const removeEnd = Math.max(0,
  4851. this.video_.currentTime - this.config_.streaming.bufferBehind);
  4852. this.textDisplayer_.remove(0, removeEnd);
  4853. const time = {
  4854. periodStart: 0,
  4855. segmentStart: 0,
  4856. segmentEnd: this.video_.duration,
  4857. vttOffset: 0,
  4858. };
  4859. /** @type {!Array<shaka.text.Cue>} */
  4860. const allCues = [];
  4861. const nativeCues = Array.from(track.activeCues || []);
  4862. for (const nativeCue of nativeCues) {
  4863. const cue = shaka.text.Utils.mapNativeCueToShakaCue(nativeCue);
  4864. if (cue) {
  4865. const modifyCueCallback = this.config_.mediaSource.modifyCueCallback;
  4866. // Closure compiler removes the call to modifyCueCallback for reasons
  4867. // unknown to us.
  4868. // See https://github.com/shaka-project/shaka-player/pull/8261
  4869. // We'll want to revisit this condition once we migrated to TS.
  4870. // See https://github.com/shaka-project/shaka-player/issues/8262 for TS.
  4871. if (modifyCueCallback) {
  4872. modifyCueCallback(cue, null, time);
  4873. }
  4874. allCues.push(cue);
  4875. }
  4876. }
  4877. this.textDisplayer_.append(allCues);
  4878. });
  4879. track.mode = document.pictureInPictureElement ? 'showing' : 'hidden';
  4880. }
  4881. /**
  4882. * Select a specific variant track to play. <code>track</code> should come
  4883. * from a call to <code>getVariantTracks</code>. If <code>track</code> cannot
  4884. * be found, this will be a no-op. If the player has not loaded content, this
  4885. * will be a no-op.
  4886. *
  4887. * <p>
  4888. * Changing variants will take effect once the currently buffered content has
  4889. * been played. To force the change to happen sooner, use
  4890. * <code>clearBuffer</code> with <code>safeMargin</code>. Setting
  4891. * <code>clearBuffer</code> to <code>true</code> will clear all buffered
  4892. * content after <code>safeMargin</code>, allowing the new variant to start
  4893. * playing sooner.
  4894. *
  4895. * <p>
  4896. * Note that <code>AdaptationEvents</code> are not fired for manual track
  4897. * selections.
  4898. *
  4899. * @param {shaka.extern.Track} track
  4900. * @param {boolean=} clearBuffer
  4901. * @param {number=} safeMargin Optional amount of buffer (in seconds) to
  4902. * retain when clearing the buffer. Useful for switching variant quickly
  4903. * without causing a buffering event. Defaults to 0 if not provided. Ignored
  4904. * if clearBuffer is false. Can cause hiccups on some browsers if chosen too
  4905. * small, e.g. The amount of two segments is a fair minimum to consider as
  4906. * safeMargin value.
  4907. * @export
  4908. */
  4909. selectVariantTrack(track, clearBuffer = false, safeMargin = 0) {
  4910. const selectMediaSourceMode = () => {
  4911. const variant = this.manifest_.variants.find(
  4912. (variant) => variant.id == track.id);
  4913. if (!variant) {
  4914. if (!this.isRemotePlayback()) {
  4915. shaka.log.error('No variant with id', track.id);
  4916. }
  4917. return;
  4918. }
  4919. // Double check that the track is allowed to be played. The track list
  4920. // should only contain playable variants, but if restrictions change and
  4921. // |selectVariantTrack| is called before the track list is updated, we
  4922. // could get a now-restricted variant.
  4923. if (!shaka.util.StreamUtils.isPlayable(variant)) {
  4924. shaka.log.error('Unable to switch to restricted track', track.id);
  4925. return;
  4926. }
  4927. const active = this.streamingEngine_.getCurrentVariant();
  4928. if (this.config_.abr.enabled && (active.video != variant.video ||
  4929. (active.audio && variant.audio &&
  4930. active.audio.language == variant.audio.language &&
  4931. active.audio.channelsCount == variant.audio.channelsCount &&
  4932. active.audio.label == variant.audio.label))) {
  4933. shaka.log.alwaysWarn('Changing tracks while abr manager is enabled ' +
  4934. 'will likely result in the selected track ' +
  4935. 'being overridden. Consider disabling abr ' +
  4936. 'before calling selectVariantTrack().');
  4937. }
  4938. if (this.isRemotePlayback()) {
  4939. this.switchVariant_(
  4940. variant, /* fromAdaptation= */ false,
  4941. /* clearBuffer= */ false, /* safeMargin= */ 0);
  4942. } else {
  4943. this.switchVariant_(
  4944. variant, /* fromAdaptation= */ false,
  4945. clearBuffer || false, safeMargin || 0);
  4946. }
  4947. // Workaround for
  4948. // https://github.com/shaka-project/shaka-player/issues/1299
  4949. // When track is selected, back-propagate the language to
  4950. // currentAudioLanguage_.
  4951. this.currentAdaptationSetCriteria_.configure({
  4952. language: variant.language,
  4953. role: (variant.audio && variant.audio.roles &&
  4954. variant.audio.roles[0]) || '',
  4955. channelCount: variant.audio && variant.audio.channelsCount ?
  4956. variant.audio.channelsCount : 0,
  4957. hdrLevel: variant.video && variant.video.hdr ? variant.video.hdr : '',
  4958. spatialAudio: variant.audio && variant.audio.spatialAudio ?
  4959. variant.audio.spatialAudio : false,
  4960. videoLayout: variant.video && variant.video.videoLayout ?
  4961. variant.video.videoLayout : '',
  4962. audioLabel: variant.audio && variant.audio.label ?
  4963. variant.audio.label : '',
  4964. videoLabel: '',
  4965. codecSwitchingStrategy: this.config_.mediaSource.codecSwitchingStrategy,
  4966. audioCodec: variant.audio && variant.audio.codecs ?
  4967. variant.audio.codecs : '',
  4968. });
  4969. // Update AbrManager variants to match these new settings.
  4970. this.updateAbrManagerVariants_();
  4971. };
  4972. const selectSrcEqualsMode = () => {
  4973. if (this.video_ && this.video_.audioTracks) {
  4974. // Safari's native HLS won't let you choose an explicit variant, though
  4975. // you can choose audio languages this way.
  4976. const audioTracks = Array.from(this.video_.audioTracks);
  4977. for (const audioTrack of audioTracks) {
  4978. if (shaka.util.StreamUtils.html5TrackId(audioTrack) == track.id) {
  4979. // This will reset the "enabled" of other tracks to false.
  4980. this.switchHtml5Track_(audioTrack);
  4981. return;
  4982. }
  4983. }
  4984. }
  4985. };
  4986. if (this.manifest_ && this.playhead_) {
  4987. selectMediaSourceMode();
  4988. // When using MSE + remote we need to set tracks for both MSE and native
  4989. // apis so that synchronization is maintained.
  4990. if (!this.isRemotePlayback()) {
  4991. return;
  4992. }
  4993. }
  4994. selectSrcEqualsMode();
  4995. }
  4996. /**
  4997. * Select an audio track compatible with the current video track.
  4998. * If the player has not loaded any content, this will be a no-op.
  4999. *
  5000. * @param {shaka.extern.AudioTrack} audioTrack
  5001. * @param {number=} safeMargin Optional amount of buffer (in seconds) to
  5002. * retain when clearing the buffer. Useful for switching quickly
  5003. * without causing a buffering event. Defaults to 0 if not provided. Can
  5004. * cause hiccups on some browsers if chosen too small, e.g. The amount of
  5005. * two segments is a fair minimum to consider as safeMargin value.
  5006. * @export
  5007. */
  5008. selectAudioTrack(audioTrack, safeMargin = 0) {
  5009. const ArrayUtils = shaka.util.ArrayUtils;
  5010. const variants = this.getVariantTracks();
  5011. if (!variants.length) {
  5012. return;
  5013. }
  5014. const active = variants.find((t) => t.active);
  5015. if (!active) {
  5016. return;
  5017. }
  5018. const validVariant = variants.find((t) => {
  5019. return t.videoId === active.videoId &&
  5020. t.language == audioTrack.language &&
  5021. t.label == audioTrack.label &&
  5022. t.audioMimeType == audioTrack.mimeType &&
  5023. t.audioCodec == audioTrack.codecs &&
  5024. t.primary == audioTrack.primary &&
  5025. ArrayUtils.equal(t.audioRoles, audioTrack.roles) &&
  5026. t.accessibilityPurpose == audioTrack.accessibilityPurpose &&
  5027. t.channelsCount == audioTrack.channelsCount &&
  5028. t.audioSamplingRate == audioTrack.audioSamplingRate &&
  5029. t.spatialAudio == audioTrack.spatialAudio;
  5030. });
  5031. if (validVariant && !validVariant.active) {
  5032. this.selectVariantTrack(validVariant,
  5033. /* clearBuffer= */ true, safeMargin);
  5034. }
  5035. }
  5036. /**
  5037. * Return a list of audio tracks compatible with the current video track.
  5038. *
  5039. * @return {!Array<shaka.extern.AudioTrack>}
  5040. * @export
  5041. */
  5042. getAudioTracks() {
  5043. const variants = this.getVariantTracks();
  5044. if (!variants.length) {
  5045. return [];
  5046. }
  5047. const active = variants.find((t) => t.active);
  5048. if (!active) {
  5049. return [];
  5050. }
  5051. let filteredTracks = variants;
  5052. if (this.loadMode_ == shaka.Player.LoadMode.MEDIA_SOURCE) {
  5053. // Filter by current videoId and has audio.
  5054. filteredTracks = variants.filter((t) => {
  5055. return t.originalVideoId === active.originalVideoId && t.audioCodec;
  5056. });
  5057. }
  5058. if (!filteredTracks.length) {
  5059. return [];
  5060. }
  5061. /** @type {!Map<string, shaka.extern.AudioTrack>} */
  5062. const audioTracksMap = new Map();
  5063. for (const track of filteredTracks) {
  5064. let id = track.originalAudioId;
  5065. if (!id && track.audioId != null) {
  5066. id = String(track.audioId);
  5067. }
  5068. if (!id) {
  5069. continue;
  5070. }
  5071. /** @type {shaka.extern.AudioTrack} */
  5072. const audioTrack = {
  5073. active: track.active,
  5074. language: track.language,
  5075. label: track.label,
  5076. mimeType: track.audioMimeType,
  5077. codecs: track.audioCodec,
  5078. primary: track.primary,
  5079. roles: track.audioRoles || [],
  5080. accessibilityPurpose: track.accessibilityPurpose,
  5081. channelsCount: track.channelsCount,
  5082. audioSamplingRate: track.audioSamplingRate,
  5083. spatialAudio: track.spatialAudio,
  5084. originalLanguage: track.originalLanguage,
  5085. };
  5086. audioTracksMap.set(id, audioTrack);
  5087. }
  5088. return Array.from(audioTracksMap.values());
  5089. }
  5090. /**
  5091. * Return a list of audio language-role combinations available. If the
  5092. * player has not loaded any content, this will return an empty list.
  5093. *
  5094. * <br>
  5095. *
  5096. * This API is deprecated and will be removed in version 5.0, please migrate
  5097. * to using `getAudioTracks` and `selectAudioTrack`.
  5098. *
  5099. * @return {!Array<shaka.extern.LanguageRole>}
  5100. * @deprecated
  5101. * @export
  5102. */
  5103. getAudioLanguagesAndRoles() {
  5104. return shaka.Player.getLanguageAndRolesFrom_(this.getVariantTracks());
  5105. }
  5106. /**
  5107. * Return a list of text language-role combinations available. If the player
  5108. * has not loaded any content, this will be return an empty list.
  5109. *
  5110. * @return {!Array<shaka.extern.LanguageRole>}
  5111. * @export
  5112. */
  5113. getTextLanguagesAndRoles() {
  5114. return shaka.Player.getLanguageAndRolesFrom_(this.getTextTracks());
  5115. }
  5116. /**
  5117. * Return a list of audio languages available. If the player has not loaded
  5118. * any content, this will return an empty list.
  5119. *
  5120. * <br>
  5121. *
  5122. * This API is deprecated and will be removed in version 5.0, please migrate
  5123. * to using `getAudioTracks` and `selectAudioTrack`.
  5124. *
  5125. * @return {!Array<string>}
  5126. * @deprecated
  5127. * @export
  5128. */
  5129. getAudioLanguages() {
  5130. return Array.from(shaka.Player.getLanguagesFrom_(this.getVariantTracks()));
  5131. }
  5132. /**
  5133. * Return a list of text languages available. If the player has not loaded
  5134. * any content, this will return an empty list.
  5135. *
  5136. * @return {!Array<string>}
  5137. * @export
  5138. */
  5139. getTextLanguages() {
  5140. return Array.from(shaka.Player.getLanguagesFrom_(this.getTextTracks()));
  5141. }
  5142. /**
  5143. * Sets the current audio language and current variant role to the selected
  5144. * language, role and channel count, and chooses a new variant if need be.
  5145. * If the player has not loaded any content, this will be a no-op.
  5146. *
  5147. * <br>
  5148. *
  5149. * This API is deprecated and will be removed in version 5.0, please migrate
  5150. * to using `getAudioTracks` and `selectAudioTrack`.
  5151. *
  5152. * @param {string} language
  5153. * @param {string=} role
  5154. * @param {number=} channelsCount
  5155. * @param {number=} safeMargin
  5156. * @param {string=} codec
  5157. * @param {boolean=} spatialAudio
  5158. * @param {string=} label
  5159. * @deprecated
  5160. * @export
  5161. */
  5162. selectAudioLanguage(language, role, channelsCount = 0, safeMargin = 0,
  5163. codec = '', spatialAudio = false, label = '') {
  5164. const selectMediaSourceMode = () => {
  5165. this.currentAdaptationSetCriteria_ =
  5166. this.config_.adaptationSetCriteriaFactory();
  5167. this.currentAdaptationSetCriteria_.configure({
  5168. language,
  5169. role: role || '',
  5170. channelCount: channelsCount || 0,
  5171. hdrLevel: '',
  5172. spatialAudio: spatialAudio || false,
  5173. videoLayout: '',
  5174. audioLabel: label || '',
  5175. videoLabel: '',
  5176. codecSwitchingStrategy:
  5177. this.config_.mediaSource.codecSwitchingStrategy,
  5178. audioCodec: codec || '',
  5179. });
  5180. const diff = (a, b) => {
  5181. if (!a.video && !b.video) {
  5182. return 0;
  5183. } else if (!a.video || !b.video) {
  5184. return Infinity;
  5185. } else {
  5186. return Math.abs((a.video.height || 0) - (b.video.height || 0)) +
  5187. Math.abs((a.video.width || 0) - (b.video.width || 0));
  5188. }
  5189. };
  5190. // Find the variant whose size is closest to the active variant. This
  5191. // ensures we stay at about the same resolution when just changing the
  5192. // language/role.
  5193. const active = this.streamingEngine_.getCurrentVariant();
  5194. const set =
  5195. this.currentAdaptationSetCriteria_.create(this.manifest_.variants);
  5196. let bestVariant = null;
  5197. for (const curVariant of set.values()) {
  5198. if (!shaka.util.StreamUtils.isPlayable(curVariant)) {
  5199. continue;
  5200. }
  5201. if (!bestVariant ||
  5202. diff(bestVariant, active) > diff(curVariant, active)) {
  5203. bestVariant = curVariant;
  5204. }
  5205. }
  5206. if (bestVariant == active) {
  5207. shaka.log.debug('Audio already selected.');
  5208. return;
  5209. }
  5210. if (bestVariant) {
  5211. const track = shaka.util.StreamUtils.variantToTrack(bestVariant);
  5212. this.selectVariantTrack(
  5213. track, /* clearBuffer= */ true, safeMargin || 0);
  5214. return;
  5215. }
  5216. // If we haven't switched yet, just use ABR to find a new track.
  5217. this.chooseVariantAndSwitch_();
  5218. };
  5219. const selectSrcEqualsMode = () => {
  5220. if (this.video_ && this.video_.audioTracks) {
  5221. const track = shaka.util.StreamUtils.filterStreamsByLanguageAndRole(
  5222. this.getVariantTracks(), language, role || '', false)[0];
  5223. if (track) {
  5224. this.selectVariantTrack(track);
  5225. }
  5226. }
  5227. };
  5228. if (this.manifest_ && this.playhead_) {
  5229. selectMediaSourceMode();
  5230. // When using MSE + remote we need to set tracks for both MSE and native
  5231. // apis so that synchronization is maintained.
  5232. if (!this.isRemotePlayback()) {
  5233. return;
  5234. }
  5235. }
  5236. selectSrcEqualsMode();
  5237. }
  5238. /**
  5239. * Sets the current text language and current text role to the selected
  5240. * language and role, and chooses a new variant if need be. If the player has
  5241. * not loaded any content, this will be a no-op.
  5242. *
  5243. * @param {string} language
  5244. * @param {string=} role
  5245. * @param {boolean=} forced
  5246. * @export
  5247. */
  5248. selectTextLanguage(language, role, forced = false) {
  5249. const selectMediaSourceMode = () => {
  5250. this.currentTextLanguage_ = language;
  5251. this.currentTextRole_ = role || '';
  5252. this.currentTextForced_ = forced || false;
  5253. const chosenText = this.chooseTextStream_();
  5254. if (chosenText) {
  5255. if (chosenText == this.streamingEngine_.getCurrentTextStream()) {
  5256. shaka.log.debug('Text track already selected.');
  5257. return;
  5258. }
  5259. this.addTextStreamToSwitchHistory_(
  5260. chosenText, /* fromAdaptation= */ false);
  5261. if (this.shouldStreamText_()) {
  5262. this.streamingEngine_.switchTextStream(chosenText);
  5263. this.onTextChanged_();
  5264. this.setTextDisplayerLanguage_();
  5265. }
  5266. }
  5267. };
  5268. const selectSrcEqualsMode = () => {
  5269. const track = shaka.util.StreamUtils.filterStreamsByLanguageAndRole(
  5270. this.getTextTracks(), language, role || '', forced || false)[0];
  5271. if (track) {
  5272. this.selectTextTrack(track);
  5273. }
  5274. };
  5275. if (this.manifest_ && this.playhead_) {
  5276. selectMediaSourceMode();
  5277. // When using MSE + remote we need to set tracks for both MSE and native
  5278. // apis so that synchronization is maintained.
  5279. if (!this.isRemotePlayback()) {
  5280. return;
  5281. }
  5282. }
  5283. selectSrcEqualsMode();
  5284. }
  5285. /**
  5286. * Select variant tracks that have a given label. This assumes the
  5287. * label uniquely identifies an audio stream, so all the variants
  5288. * are expected to have the same variant.audio.
  5289. *
  5290. * This API is deprecated and will be removed in version 5.0, please migrate
  5291. * to using `getAudioTracks` and `selectAudioTrack`.
  5292. *
  5293. * @param {string} label
  5294. * @param {boolean=} clearBuffer Optional clear buffer or not when
  5295. * switch to new variant
  5296. * Defaults to true if not provided
  5297. * @param {number=} safeMargin Optional amount of buffer (in seconds) to
  5298. * retain when clearing the buffer.
  5299. * Defaults to 0 if not provided. Ignored if clearBuffer is false.
  5300. * @deprecated
  5301. * @export
  5302. */
  5303. selectVariantsByLabel(label, clearBuffer = true, safeMargin = 0) {
  5304. const selectMediaSourceMode = () => {
  5305. let firstVariantWithLabel = null;
  5306. for (const variant of this.manifest_.variants) {
  5307. if (variant.audio.label == label) {
  5308. firstVariantWithLabel = variant;
  5309. break;
  5310. }
  5311. }
  5312. if (firstVariantWithLabel == null) {
  5313. shaka.log.warning('No variants were found with label: ' +
  5314. label + '. Ignoring the request to switch.');
  5315. return;
  5316. }
  5317. // Label is a unique identifier of a variant's audio stream.
  5318. // Because of that we assume that all the variants with the same
  5319. // label have the same language.
  5320. this.currentAdaptationSetCriteria_ =
  5321. this.config_.adaptationSetCriteriaFactory();
  5322. this.currentAdaptationSetCriteria_.configure({
  5323. language: firstVariantWithLabel.language,
  5324. role: '',
  5325. channelCount: 0,
  5326. hdrLevel: '',
  5327. spatialAudio: false,
  5328. videoLayout: '',
  5329. videoLabel: '',
  5330. audioLabel: label,
  5331. codecSwitchingStrategy:
  5332. this.config_.mediaSource.codecSwitchingStrategy,
  5333. audioCodec: '',
  5334. });
  5335. this.chooseVariantAndSwitch_(clearBuffer, safeMargin);
  5336. };
  5337. const selectSrcEqualsMode = () => {
  5338. if (this.video_ && this.video_.audioTracks) {
  5339. const audioTracks = Array.from(this.video_.audioTracks);
  5340. let trackMatch = null;
  5341. for (const audioTrack of audioTracks) {
  5342. if (audioTrack.label == label) {
  5343. trackMatch = audioTrack;
  5344. }
  5345. }
  5346. if (trackMatch) {
  5347. this.switchHtml5Track_(trackMatch);
  5348. }
  5349. }
  5350. };
  5351. if (this.manifest_ && this.playhead_) {
  5352. selectMediaSourceMode();
  5353. // When using MSE + remote we need to set tracks for both MSE and native
  5354. // apis so that synchronization is maintained.
  5355. if (!this.isRemotePlayback()) {
  5356. return;
  5357. }
  5358. }
  5359. selectSrcEqualsMode();
  5360. }
  5361. /**
  5362. * Check if the text displayer is enabled.
  5363. *
  5364. * @return {boolean}
  5365. * @export
  5366. */
  5367. isTextTrackVisible() {
  5368. const expected = this.isTextVisible_;
  5369. if (this.textDisplayer_) {
  5370. const actual = this.textDisplayer_.isTextVisible();
  5371. goog.asserts.assert(
  5372. actual == expected, 'text visibility has fallen out of sync');
  5373. // Always return the actual value so that the app has the most accurate
  5374. // information (in the case that the values come out of sync in prod).
  5375. return actual;
  5376. }
  5377. return expected;
  5378. }
  5379. /**
  5380. * Return a list of chapters tracks.
  5381. *
  5382. * @return {!Array<shaka.extern.Track>}
  5383. * @export
  5384. */
  5385. getChaptersTracks() {
  5386. if (this.video_ && this.video_.currentSrc && this.video_.textTracks) {
  5387. const textTracks = this.getChaptersTracks_();
  5388. const StreamUtils = shaka.util.StreamUtils;
  5389. return textTracks.map((text) => StreamUtils.html5TextTrackToTrack(text));
  5390. } else {
  5391. return [];
  5392. }
  5393. }
  5394. /**
  5395. * This returns the list of chapters.
  5396. *
  5397. * @param {string} language
  5398. * @return {!Array<shaka.extern.Chapter>}
  5399. * @export
  5400. */
  5401. getChapters(language) {
  5402. if (!this.video_ || !this.video_.currentSrc || !this.video_.textTracks) {
  5403. return [];
  5404. }
  5405. const LanguageUtils = shaka.util.LanguageUtils;
  5406. const inputLanguage = LanguageUtils.normalize(language);
  5407. const chaptersTracks = this.getChaptersTracks_();
  5408. const chaptersTracksWithLanguage = chaptersTracks
  5409. .filter((t) => LanguageUtils.normalize(t.language) == inputLanguage);
  5410. if (!chaptersTracksWithLanguage || !chaptersTracksWithLanguage.length) {
  5411. return [];
  5412. }
  5413. const chapters = [];
  5414. const uniqueChapters = new Set();
  5415. for (const chaptersTrack of chaptersTracksWithLanguage) {
  5416. if (chaptersTrack && chaptersTrack.cues) {
  5417. for (const cue of chaptersTrack.cues) {
  5418. let id = cue.id;
  5419. if (!id || id == '') {
  5420. id = cue.startTime + '-' + cue.endTime + '-' + cue.text;
  5421. }
  5422. /** @type {shaka.extern.Chapter} */
  5423. const chapter = {
  5424. id: id,
  5425. title: cue.text,
  5426. startTime: cue.startTime,
  5427. endTime: cue.endTime,
  5428. };
  5429. if (!uniqueChapters.has(id)) {
  5430. chapters.push(chapter);
  5431. uniqueChapters.add(id);
  5432. }
  5433. }
  5434. }
  5435. }
  5436. return chapters;
  5437. }
  5438. /**
  5439. * Ignore the TextTracks with the 'metadata' or 'chapters' kind, or the one
  5440. * generated by the SimpleTextDisplayer.
  5441. *
  5442. * @return {!Array<TextTrack>}
  5443. * @private
  5444. */
  5445. getFilteredTextTracks_() {
  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' && t.kind != 'chapters' &&
  5450. t.label != shaka.Player.TextTrackLabel);
  5451. }
  5452. /**
  5453. * Get the one text track generated by the SimpleTextDisplayer.
  5454. *
  5455. * @return {?TextTrack}
  5456. * @private
  5457. */
  5458. getGeneratedTextTrack_() {
  5459. goog.asserts.assert(this.video_.textTracks,
  5460. 'TextTracks should be valid.');
  5461. return Array.from(this.video_.textTracks)
  5462. .find((t) => t.label == shaka.Player.TextTrackLabel);
  5463. }
  5464. /**
  5465. * Get the TextTracks with the 'metadata' kind.
  5466. *
  5467. * @return {!Array<TextTrack>}
  5468. * @private
  5469. */
  5470. getMetadataTracks_() {
  5471. goog.asserts.assert(this.video_.textTracks,
  5472. 'TextTracks should be valid.');
  5473. return Array.from(this.video_.textTracks)
  5474. .filter((t) => t.kind == 'metadata');
  5475. }
  5476. /**
  5477. * Get the TextTracks with the 'chapters' kind.
  5478. *
  5479. * @return {!Array<TextTrack>}
  5480. * @private
  5481. */
  5482. getChaptersTracks_() {
  5483. goog.asserts.assert(this.video_.textTracks,
  5484. 'TextTracks should be valid.');
  5485. return Array.from(this.video_.textTracks)
  5486. .filter((t) => t.kind == 'chapters');
  5487. }
  5488. /**
  5489. * Enable or disable the text displayer. If the player is in an unloaded
  5490. * state, the request will be applied next time content is loaded.
  5491. *
  5492. * @param {boolean} isVisible
  5493. * @export
  5494. */
  5495. setTextTrackVisibility(isVisible) {
  5496. const oldVisibility = this.isTextVisible_;
  5497. // Convert to boolean in case apps pass 0/1 instead false/true.
  5498. const newVisibility = !!isVisible;
  5499. if (oldVisibility == newVisibility) {
  5500. return;
  5501. }
  5502. this.isTextVisible_ = newVisibility;
  5503. // Hold of on setting the text visibility until we have all the components
  5504. // we need. This ensures that they stay in-sync.
  5505. if (this.loadMode_ == shaka.Player.LoadMode.MEDIA_SOURCE) {
  5506. this.textDisplayer_.setTextVisibility(newVisibility);
  5507. // When the user wants to see captions, we stream captions. When the user
  5508. // doesn't want to see captions, we don't stream captions. This is to
  5509. // avoid bandwidth consumption by an unused resource. The app developer
  5510. // can override this and configure us to always stream captions.
  5511. if (!this.config_.streaming.alwaysStreamText) {
  5512. if (newVisibility) {
  5513. if (this.streamingEngine_.getCurrentTextStream()) {
  5514. // We already have a selected text stream.
  5515. } else {
  5516. // Find the text stream that best matches the user's preferences.
  5517. const streams =
  5518. shaka.util.StreamUtils.filterStreamsByLanguageAndRole(
  5519. this.manifest_.textStreams,
  5520. this.currentTextLanguage_,
  5521. this.currentTextRole_,
  5522. this.currentTextForced_);
  5523. // It is possible that there are no streams to play.
  5524. if (streams.length > 0) {
  5525. this.streamingEngine_.switchTextStream(streams[0]);
  5526. this.onTextChanged_();
  5527. this.setTextDisplayerLanguage_();
  5528. }
  5529. }
  5530. } else {
  5531. this.streamingEngine_.unloadTextStream();
  5532. }
  5533. }
  5534. } else if (this.video_ && this.video_.src && this.video_.textTracks) {
  5535. this.textDisplayer_.setTextVisibility(newVisibility);
  5536. }
  5537. // We need to fire the event after we have updated everything so that
  5538. // everything will be in a stable state when the app responds to the
  5539. // event.
  5540. this.onTextTrackVisibility_();
  5541. }
  5542. /**
  5543. * Get the current playhead position as a date.
  5544. *
  5545. * @return {Date}
  5546. * @export
  5547. */
  5548. getPlayheadTimeAsDate() {
  5549. let presentationTime = 0;
  5550. if (this.playhead_) {
  5551. presentationTime = this.playhead_.getTime();
  5552. } else if (this.startTime_ == null) {
  5553. // A live stream with no requested start time and no playhead yet. We
  5554. // would start at the live edge, but we don't have that yet, so return
  5555. // the current date & time.
  5556. return new Date();
  5557. } else {
  5558. // A specific start time has been requested. This is what Playhead will
  5559. // use once it is created.
  5560. presentationTime = this.startTime_;
  5561. }
  5562. if (this.manifest_ && !this.isRemotePlayback()) {
  5563. const timeline = this.manifest_.presentationTimeline;
  5564. const startTime = timeline.getInitialProgramDateTime() ||
  5565. timeline.getPresentationStartTime();
  5566. return new Date(/* ms= */ (startTime + presentationTime) * 1000);
  5567. } else if (this.video_ && this.video_.getStartDate) {
  5568. // Apple's native HLS gives us getStartDate(), which is only available if
  5569. // EXT-X-PROGRAM-DATETIME is in the playlist.
  5570. const startDate = this.video_.getStartDate();
  5571. if (isNaN(startDate.getTime())) {
  5572. shaka.log.warning(
  5573. 'EXT-X-PROGRAM-DATETIME required to get playhead time as Date!');
  5574. return null;
  5575. }
  5576. return new Date(startDate.getTime() + (presentationTime * 1000));
  5577. } else {
  5578. shaka.log.warning('No way to get playhead time as Date!');
  5579. return null;
  5580. }
  5581. }
  5582. /**
  5583. * Get the presentation start time as a date.
  5584. *
  5585. * @return {Date}
  5586. * @export
  5587. */
  5588. getPresentationStartTimeAsDate() {
  5589. if (this.manifest_ && !this.isRemotePlayback()) {
  5590. const timeline = this.manifest_.presentationTimeline;
  5591. const startTime = timeline.getInitialProgramDateTime() ||
  5592. timeline.getPresentationStartTime();
  5593. goog.asserts.assert(startTime != null,
  5594. 'Presentation start time should not be null!');
  5595. return new Date(/* ms= */ startTime * 1000);
  5596. } else if (this.video_ && this.video_.getStartDate) {
  5597. // Apple's native HLS gives us getStartDate(), which is only available if
  5598. // EXT-X-PROGRAM-DATETIME is in the playlist.
  5599. const startDate = this.video_.getStartDate();
  5600. if (isNaN(startDate.getTime())) {
  5601. shaka.log.warning(
  5602. 'EXT-X-PROGRAM-DATETIME required to get presentation start time ' +
  5603. 'as Date!');
  5604. return null;
  5605. }
  5606. return startDate;
  5607. } else {
  5608. shaka.log.warning('No way to get presentation start time as Date!');
  5609. return null;
  5610. }
  5611. }
  5612. /**
  5613. * Get the presentation segment availability duration. This should only be
  5614. * called when the player has loaded a live stream. If the player has not
  5615. * loaded a live stream, this will return <code>null</code>.
  5616. *
  5617. * @return {?number}
  5618. * @export
  5619. */
  5620. getSegmentAvailabilityDuration() {
  5621. if (!this.isLive()) {
  5622. shaka.log.warning('getSegmentAvailabilityDuration is for live streams!');
  5623. return null;
  5624. }
  5625. if (this.manifest_) {
  5626. const timeline = this.manifest_.presentationTimeline;
  5627. return timeline.getSegmentAvailabilityDuration();
  5628. } else {
  5629. shaka.log.warning('No way to get segment segment availability duration!');
  5630. return null;
  5631. }
  5632. }
  5633. /**
  5634. * Get information about what the player has buffered. If the player has not
  5635. * loaded content or is currently loading content, the buffered content will
  5636. * be empty.
  5637. *
  5638. * @return {shaka.extern.BufferedInfo}
  5639. * @export
  5640. */
  5641. getBufferedInfo() {
  5642. if (this.loadMode_ == shaka.Player.LoadMode.MEDIA_SOURCE) {
  5643. return this.mediaSourceEngine_.getBufferedInfo();
  5644. }
  5645. const info = {
  5646. total: [],
  5647. audio: [],
  5648. video: [],
  5649. text: [],
  5650. };
  5651. if (this.loadMode_ == shaka.Player.LoadMode.SRC_EQUALS) {
  5652. const TimeRangesUtils = shaka.media.TimeRangesUtils;
  5653. info.total = TimeRangesUtils.getBufferedInfo(this.video_.buffered);
  5654. }
  5655. return info;
  5656. }
  5657. /**
  5658. * Get latency in milliseconds between the live edge and what's currently
  5659. * playing.
  5660. *
  5661. * @return {?number} The latency in milliseconds, or null if nothing
  5662. * is playing.
  5663. */
  5664. getLiveLatency() {
  5665. if (!this.video_ || !this.video_.currentTime) {
  5666. return null;
  5667. }
  5668. const now = this.getPresentationStartTimeAsDate().getTime() +
  5669. this.video_.currentTime * 1000;
  5670. return Math.floor(Date.now() - now);
  5671. }
  5672. /**
  5673. * Get statistics for the current playback session. If the player is not
  5674. * playing content, this will return an empty stats object.
  5675. *
  5676. * @return {shaka.extern.Stats}
  5677. * @export
  5678. */
  5679. getStats() {
  5680. // If the Player is not in a fully-loaded state, then return an empty stats
  5681. // blob so that this call will never fail.
  5682. const loaded = this.loadMode_ == shaka.Player.LoadMode.MEDIA_SOURCE ||
  5683. this.loadMode_ == shaka.Player.LoadMode.SRC_EQUALS;
  5684. if (!loaded) {
  5685. return shaka.util.Stats.getEmptyBlob();
  5686. }
  5687. this.updateStateHistory_();
  5688. goog.asserts.assert(this.video_, 'If we have stats, we should have video_');
  5689. const element = /** @type {!HTMLVideoElement} */ (this.video_);
  5690. const completionRatio = element.currentTime / element.duration;
  5691. if (!isNaN(completionRatio) && !this.isLive()) {
  5692. this.stats_.setCompletionPercent(Math.round(100 * completionRatio));
  5693. }
  5694. if (this.playhead_) {
  5695. this.stats_.setGapsJumped(this.playhead_.getGapsJumped());
  5696. this.stats_.setStallsDetected(this.playhead_.getStallsDetected());
  5697. }
  5698. if (element.getVideoPlaybackQuality) {
  5699. const info = element.getVideoPlaybackQuality();
  5700. this.stats_.setDroppedFrames(
  5701. Number(info.droppedVideoFrames),
  5702. Number(info.totalVideoFrames));
  5703. this.stats_.setCorruptedFrames(Number(info.corruptedVideoFrames));
  5704. }
  5705. const licenseSeconds =
  5706. this.drmEngine_ ? this.drmEngine_.getLicenseTime() : NaN;
  5707. this.stats_.setLicenseTime(licenseSeconds);
  5708. if (this.loadMode_ == shaka.Player.LoadMode.MEDIA_SOURCE) {
  5709. // Event through we are loaded, it is still possible that we don't have a
  5710. // variant yet because we set the load mode before we select the first
  5711. // variant to stream.
  5712. const variant = this.streamingEngine_.getCurrentVariant();
  5713. const textStream = this.streamingEngine_.getCurrentTextStream();
  5714. if (variant) {
  5715. const rate = this.playRateController_ ?
  5716. this.playRateController_.getRealRate() : 1;
  5717. const variantBandwidth = rate * variant.bandwidth;
  5718. let currentStreamBandwidth = variantBandwidth;
  5719. if (textStream && textStream.bandwidth) {
  5720. currentStreamBandwidth += (rate * textStream.bandwidth);
  5721. }
  5722. this.stats_.setCurrentStreamBandwidth(currentStreamBandwidth);
  5723. }
  5724. if (variant && variant.video) {
  5725. this.stats_.setResolution(
  5726. /* width= */ variant.video.width || NaN,
  5727. /* height= */ variant.video.height || NaN);
  5728. }
  5729. if (this.isLive()) {
  5730. const latency = this.getLiveLatency() || 0;
  5731. this.stats_.setLiveLatency(latency / 1000);
  5732. }
  5733. if (this.manifest_) {
  5734. this.stats_.setManifestPeriodCount(this.manifest_.periodCount);
  5735. this.stats_.setManifestGapCount(this.manifest_.gapCount);
  5736. if (this.manifest_.presentationTimeline) {
  5737. const maxSegmentDuration =
  5738. this.manifest_.presentationTimeline.getMaxSegmentDuration();
  5739. this.stats_.setMaxSegmentDuration(maxSegmentDuration);
  5740. }
  5741. }
  5742. const estimate = this.abrManager_.getBandwidthEstimate();
  5743. this.stats_.setBandwidthEstimate(estimate);
  5744. }
  5745. if (this.loadMode_ == shaka.Player.LoadMode.SRC_EQUALS) {
  5746. this.stats_.addBytesDownloaded(NaN);
  5747. this.stats_.setResolution(
  5748. /* width= */ element.videoWidth || NaN,
  5749. /* height= */ element.videoHeight || NaN);
  5750. }
  5751. return this.stats_.getBlob();
  5752. }
  5753. /**
  5754. * Adds the given text track to the loaded manifest. <code>load()</code> must
  5755. * resolve before calling. The presentation must have a duration.
  5756. *
  5757. * This returns the created track, which can immediately be selected by the
  5758. * application. The track will not be automatically selected.
  5759. *
  5760. * @param {string} uri
  5761. * @param {string} language
  5762. * @param {string} kind
  5763. * @param {string=} mimeType
  5764. * @param {string=} codec
  5765. * @param {string=} label
  5766. * @param {boolean=} forced
  5767. * @return {!Promise<shaka.extern.Track>}
  5768. * @export
  5769. */
  5770. async addTextTrackAsync(uri, language, kind, mimeType, codec, label,
  5771. forced = false) {
  5772. if (this.loadMode_ != shaka.Player.LoadMode.MEDIA_SOURCE &&
  5773. this.loadMode_ != shaka.Player.LoadMode.SRC_EQUALS) {
  5774. shaka.log.error(
  5775. 'Must call load() and wait for it to resolve before adding text ' +
  5776. 'tracks.');
  5777. throw new shaka.util.Error(
  5778. shaka.util.Error.Severity.RECOVERABLE,
  5779. shaka.util.Error.Category.PLAYER,
  5780. shaka.util.Error.Code.CONTENT_NOT_LOADED);
  5781. }
  5782. if (kind != 'subtitles' && kind != 'captions') {
  5783. shaka.log.alwaysWarn(
  5784. 'Using a kind value different of `subtitles` or `captions` can ' +
  5785. 'cause unwanted issues.');
  5786. }
  5787. if (!mimeType) {
  5788. mimeType = await this.getTextMimetype_(uri);
  5789. }
  5790. let adCuePoints = [];
  5791. if (this.adManager_) {
  5792. adCuePoints = this.adManager_.getCuePoints();
  5793. }
  5794. if (this.loadMode_ == shaka.Player.LoadMode.SRC_EQUALS) {
  5795. if (forced) {
  5796. // See: https://github.com/whatwg/html/issues/4472
  5797. kind = 'forced';
  5798. }
  5799. await this.addSrcTrackElement_(uri, language, kind, mimeType, label || '',
  5800. adCuePoints);
  5801. const LanguageUtils = shaka.util.LanguageUtils;
  5802. const languageNormalized = LanguageUtils.normalize(language);
  5803. const textTracks = this.getTextTracks();
  5804. const srcTrack = textTracks.find((t) => {
  5805. return LanguageUtils.normalize(t.language) == languageNormalized &&
  5806. t.label == (label || '') &&
  5807. t.kind == kind;
  5808. });
  5809. if (srcTrack) {
  5810. this.onTracksChanged_();
  5811. return srcTrack;
  5812. }
  5813. // This should not happen, but there are browser implementations that may
  5814. // not support the Track element.
  5815. shaka.log.error('Cannot add this text when loaded with src=');
  5816. throw new shaka.util.Error(
  5817. shaka.util.Error.Severity.RECOVERABLE,
  5818. shaka.util.Error.Category.TEXT,
  5819. shaka.util.Error.Code.CANNOT_ADD_EXTERNAL_TEXT_TO_SRC_EQUALS);
  5820. }
  5821. const ContentType = shaka.util.ManifestParserUtils.ContentType;
  5822. const seekRange = this.seekRange();
  5823. let duration = seekRange.end - seekRange.start;
  5824. if (this.manifest_) {
  5825. duration = this.manifest_.presentationTimeline.getDuration();
  5826. }
  5827. if (duration == Infinity) {
  5828. throw new shaka.util.Error(
  5829. shaka.util.Error.Severity.RECOVERABLE,
  5830. shaka.util.Error.Category.MANIFEST,
  5831. shaka.util.Error.Code.CANNOT_ADD_EXTERNAL_TEXT_TO_LIVE_STREAM);
  5832. }
  5833. if (adCuePoints.length) {
  5834. goog.asserts.assert(
  5835. this.networkingEngine_, 'Need networking engine.');
  5836. const data = await this.getTextData_(uri,
  5837. this.networkingEngine_,
  5838. this.config_.streaming.retryParameters);
  5839. const vvtText = this.convertToWebVTT_(data, mimeType, adCuePoints);
  5840. const blob = new Blob([vvtText], {type: 'text/vtt'});
  5841. uri = shaka.media.MediaSourceEngine.createObjectURL(blob);
  5842. mimeType = 'text/vtt';
  5843. }
  5844. /** @type {shaka.extern.Stream} */
  5845. const stream = {
  5846. id: this.nextExternalStreamId_++,
  5847. originalId: null,
  5848. groupId: null,
  5849. createSegmentIndex: () => Promise.resolve(),
  5850. segmentIndex: shaka.media.SegmentIndex.forSingleSegment(
  5851. /* startTime= */ 0,
  5852. /* duration= */ duration,
  5853. /* uris= */ [uri]),
  5854. mimeType: mimeType || '',
  5855. codecs: codec || '',
  5856. kind: kind,
  5857. encrypted: false,
  5858. drmInfos: [],
  5859. keyIds: new Set(),
  5860. language: language,
  5861. originalLanguage: language,
  5862. label: label || null,
  5863. type: ContentType.TEXT,
  5864. primary: false,
  5865. trickModeVideo: null,
  5866. dependencyStream: null,
  5867. emsgSchemeIdUris: null,
  5868. roles: [],
  5869. forced: !!forced,
  5870. channelsCount: null,
  5871. audioSamplingRate: null,
  5872. spatialAudio: false,
  5873. closedCaptions: null,
  5874. accessibilityPurpose: null,
  5875. external: true,
  5876. fastSwitching: false,
  5877. fullMimeTypes: new Set([shaka.util.MimeUtils.getFullType(
  5878. mimeType || '', codec || '')]),
  5879. isAudioMuxedInVideo: false,
  5880. baseOriginalId: null,
  5881. };
  5882. const fullMimeType = shaka.util.MimeUtils.getFullType(
  5883. stream.mimeType, stream.codecs);
  5884. const supported = shaka.text.TextEngine.isTypeSupported(fullMimeType);
  5885. if (!supported) {
  5886. throw new shaka.util.Error(
  5887. shaka.util.Error.Severity.CRITICAL,
  5888. shaka.util.Error.Category.TEXT,
  5889. shaka.util.Error.Code.MISSING_TEXT_PLUGIN,
  5890. mimeType);
  5891. }
  5892. this.manifest_.textStreams.push(stream);
  5893. this.onTracksChanged_();
  5894. return shaka.util.StreamUtils.textStreamToTrack(stream);
  5895. }
  5896. /**
  5897. * Adds the given thumbnails track to the loaded manifest.
  5898. * <code>load()</code> must resolve before calling. The presentation must
  5899. * have a duration.
  5900. *
  5901. * This returns the created track, which can immediately be used by the
  5902. * application.
  5903. *
  5904. * @param {string} uri
  5905. * @param {string=} mimeType
  5906. * @return {!Promise<shaka.extern.Track>}
  5907. * @export
  5908. */
  5909. async addThumbnailsTrack(uri, mimeType) {
  5910. if (this.loadMode_ != shaka.Player.LoadMode.MEDIA_SOURCE &&
  5911. this.loadMode_ != shaka.Player.LoadMode.SRC_EQUALS) {
  5912. shaka.log.error(
  5913. 'Must call load() and wait for it to resolve before adding image ' +
  5914. 'tracks.');
  5915. throw new shaka.util.Error(
  5916. shaka.util.Error.Severity.RECOVERABLE,
  5917. shaka.util.Error.Category.PLAYER,
  5918. shaka.util.Error.Code.CONTENT_NOT_LOADED);
  5919. }
  5920. if (!mimeType) {
  5921. mimeType = await this.getTextMimetype_(uri);
  5922. }
  5923. if (mimeType != 'text/vtt') {
  5924. throw new shaka.util.Error(
  5925. shaka.util.Error.Severity.RECOVERABLE,
  5926. shaka.util.Error.Category.TEXT,
  5927. shaka.util.Error.Code.UNSUPPORTED_EXTERNAL_THUMBNAILS_URI,
  5928. uri);
  5929. }
  5930. const ContentType = shaka.util.ManifestParserUtils.ContentType;
  5931. const seekRange = this.seekRange();
  5932. let duration = seekRange.end - seekRange.start;
  5933. if (this.manifest_) {
  5934. duration = this.manifest_.presentationTimeline.getDuration();
  5935. }
  5936. if (duration == Infinity) {
  5937. throw new shaka.util.Error(
  5938. shaka.util.Error.Severity.RECOVERABLE,
  5939. shaka.util.Error.Category.MANIFEST,
  5940. shaka.util.Error.Code.CANNOT_ADD_EXTERNAL_THUMBNAILS_TO_LIVE_STREAM);
  5941. }
  5942. goog.asserts.assert(
  5943. this.networkingEngine_, 'Need networking engine.');
  5944. const buffer = await this.getTextData_(uri,
  5945. this.networkingEngine_,
  5946. this.config_.streaming.retryParameters);
  5947. const factory = shaka.text.TextEngine.findParser(mimeType);
  5948. if (!factory) {
  5949. throw new shaka.util.Error(
  5950. shaka.util.Error.Severity.CRITICAL,
  5951. shaka.util.Error.Category.TEXT,
  5952. shaka.util.Error.Code.MISSING_TEXT_PLUGIN,
  5953. mimeType);
  5954. }
  5955. const TextParser = factory();
  5956. const time = {
  5957. periodStart: 0,
  5958. segmentStart: 0,
  5959. segmentEnd: duration,
  5960. vttOffset: 0,
  5961. };
  5962. const data = shaka.util.BufferUtils.toUint8(buffer);
  5963. const cues = TextParser.parseMedia(data, time, uri, /* images= */ []);
  5964. const references = [];
  5965. for (const cue of cues) {
  5966. let uris = null;
  5967. const getUris = () => {
  5968. if (uris == null) {
  5969. uris = shaka.util.ManifestParserUtils.resolveUris(
  5970. [uri], [cue.payload]);
  5971. }
  5972. return uris || [];
  5973. };
  5974. const reference = new shaka.media.SegmentReference(
  5975. cue.startTime,
  5976. cue.endTime,
  5977. getUris,
  5978. /* startByte= */ 0,
  5979. /* endByte= */ null,
  5980. /* initSegmentReference= */ null,
  5981. /* timestampOffset= */ 0,
  5982. /* appendWindowStart= */ 0,
  5983. /* appendWindowEnd= */ Infinity,
  5984. );
  5985. if (cue.payload.includes('#xywh')) {
  5986. const spriteInfo = cue.payload.split('#xywh=')[1].split(',');
  5987. if (spriteInfo.length === 4) {
  5988. reference.setThumbnailSprite({
  5989. height: parseInt(spriteInfo[3], 10),
  5990. positionX: parseInt(spriteInfo[0], 10),
  5991. positionY: parseInt(spriteInfo[1], 10),
  5992. width: parseInt(spriteInfo[2], 10),
  5993. });
  5994. }
  5995. }
  5996. references.push(reference);
  5997. }
  5998. let segmentMimeType = mimeType;
  5999. if (references.length) {
  6000. segmentMimeType = await shaka.net.NetworkingUtils.getMimeType(
  6001. references[0].getUris()[0],
  6002. this.networkingEngine_, this.config_.manifest.retryParameters);
  6003. }
  6004. /** @type {shaka.extern.Stream} */
  6005. const stream = {
  6006. id: this.nextExternalStreamId_++,
  6007. originalId: null,
  6008. groupId: null,
  6009. createSegmentIndex: () => Promise.resolve(),
  6010. segmentIndex: new shaka.media.SegmentIndex(references),
  6011. mimeType: segmentMimeType || '',
  6012. codecs: '',
  6013. kind: '',
  6014. encrypted: false,
  6015. drmInfos: [],
  6016. keyIds: new Set(),
  6017. language: 'und',
  6018. originalLanguage: null,
  6019. label: null,
  6020. type: ContentType.IMAGE,
  6021. primary: false,
  6022. trickModeVideo: null,
  6023. dependencyStream: null,
  6024. emsgSchemeIdUris: null,
  6025. roles: [],
  6026. forced: false,
  6027. channelsCount: null,
  6028. audioSamplingRate: null,
  6029. spatialAudio: false,
  6030. closedCaptions: null,
  6031. tilesLayout: '1x1',
  6032. accessibilityPurpose: null,
  6033. external: true,
  6034. fastSwitching: false,
  6035. fullMimeTypes: new Set([shaka.util.MimeUtils.getFullType(
  6036. segmentMimeType || '', '')]),
  6037. isAudioMuxedInVideo: false,
  6038. baseOriginalId: null,
  6039. };
  6040. if (this.loadMode_ == shaka.Player.LoadMode.SRC_EQUALS) {
  6041. this.externalSrcEqualsThumbnailsStreams_.push(stream);
  6042. } else {
  6043. this.manifest_.imageStreams.push(stream);
  6044. }
  6045. this.onTracksChanged_();
  6046. return shaka.util.StreamUtils.imageStreamToTrack(stream);
  6047. }
  6048. /**
  6049. * Adds the given chapters track to the loaded manifest. <code>load()</code>
  6050. * must resolve before calling. The presentation must have a duration.
  6051. *
  6052. * This returns the created track.
  6053. *
  6054. * @param {string} uri
  6055. * @param {string} language
  6056. * @param {string=} mimeType
  6057. * @return {!Promise<shaka.extern.Track>}
  6058. * @export
  6059. */
  6060. async addChaptersTrack(uri, language, mimeType) {
  6061. if (this.loadMode_ != shaka.Player.LoadMode.MEDIA_SOURCE &&
  6062. this.loadMode_ != shaka.Player.LoadMode.SRC_EQUALS) {
  6063. shaka.log.error(
  6064. 'Must call load() and wait for it to resolve before adding ' +
  6065. 'chapters tracks.');
  6066. throw new shaka.util.Error(
  6067. shaka.util.Error.Severity.RECOVERABLE,
  6068. shaka.util.Error.Category.PLAYER,
  6069. shaka.util.Error.Code.CONTENT_NOT_LOADED);
  6070. }
  6071. if (!mimeType) {
  6072. mimeType = await this.getTextMimetype_(uri);
  6073. }
  6074. let adCuePoints = [];
  6075. if (this.adManager_) {
  6076. adCuePoints = this.adManager_.getCuePoints();
  6077. }
  6078. /** @type {!HTMLTrackElement} */
  6079. const trackElement = await this.addSrcTrackElement_(
  6080. uri, language, /* kind= */ 'chapters', mimeType, /* label= */ '',
  6081. adCuePoints);
  6082. const chaptersTracks = this.getChaptersTracks();
  6083. const chaptersTrack = chaptersTracks.find((t) => {
  6084. return t.language == language;
  6085. });
  6086. if (chaptersTrack) {
  6087. await new Promise((resolve, reject) => {
  6088. // The chapter data isn't available until the 'load' event fires, and
  6089. // that won't happen until the chapters track is activated by the
  6090. // activateChaptersTrack_ method.
  6091. this.loadEventManager_.listenOnce(trackElement, 'load', resolve);
  6092. this.loadEventManager_.listenOnce(trackElement, 'error', (event) => {
  6093. reject(new shaka.util.Error(
  6094. shaka.util.Error.Severity.RECOVERABLE,
  6095. shaka.util.Error.Category.TEXT,
  6096. shaka.util.Error.Code.CHAPTERS_TRACK_FAILED));
  6097. });
  6098. });
  6099. this.onTracksChanged_();
  6100. return chaptersTrack;
  6101. }
  6102. // This should not happen, but there are browser implementations that may
  6103. // not support the Track element.
  6104. shaka.log.error('Cannot add this text when loaded with src=');
  6105. throw new shaka.util.Error(
  6106. shaka.util.Error.Severity.RECOVERABLE,
  6107. shaka.util.Error.Category.TEXT,
  6108. shaka.util.Error.Code.CANNOT_ADD_EXTERNAL_TEXT_TO_SRC_EQUALS);
  6109. }
  6110. /**
  6111. * @param {string} uri
  6112. * @return {!Promise<string>}
  6113. * @private
  6114. */
  6115. async getTextMimetype_(uri) {
  6116. let mimeType;
  6117. try {
  6118. goog.asserts.assert(
  6119. this.networkingEngine_, 'Need networking engine.');
  6120. mimeType = await shaka.net.NetworkingUtils.getMimeType(uri,
  6121. this.networkingEngine_,
  6122. this.config_.streaming.retryParameters);
  6123. } catch (error) {}
  6124. if (mimeType) {
  6125. return mimeType;
  6126. }
  6127. shaka.log.error(
  6128. 'The mimeType has not been provided and it could not be deduced ' +
  6129. 'from its uri.');
  6130. throw new shaka.util.Error(
  6131. shaka.util.Error.Severity.RECOVERABLE,
  6132. shaka.util.Error.Category.TEXT,
  6133. shaka.util.Error.Code.TEXT_COULD_NOT_GUESS_MIME_TYPE,
  6134. uri);
  6135. }
  6136. /**
  6137. * @param {string} uri
  6138. * @param {string} language
  6139. * @param {string} kind
  6140. * @param {string} mimeType
  6141. * @param {string} label
  6142. * @param {!Array<!shaka.extern.AdCuePoint>} adCuePoints
  6143. * @return {!Promise<!HTMLTrackElement>}
  6144. * @private
  6145. */
  6146. async addSrcTrackElement_(uri, language, kind, mimeType, label,
  6147. adCuePoints) {
  6148. if (mimeType != 'text/vtt' || adCuePoints.length) {
  6149. goog.asserts.assert(
  6150. this.networkingEngine_, 'Need networking engine.');
  6151. const data = await this.getTextData_(uri,
  6152. this.networkingEngine_,
  6153. this.config_.streaming.retryParameters);
  6154. const vvtText = this.convertToWebVTT_(data, mimeType, adCuePoints);
  6155. const blob = new Blob([vvtText], {type: 'text/vtt'});
  6156. uri = shaka.media.MediaSourceEngine.createObjectURL(blob);
  6157. mimeType = 'text/vtt';
  6158. }
  6159. const trackElement =
  6160. /** @type {!HTMLTrackElement} */(document.createElement('track'));
  6161. trackElement.src = this.cmcdManager_.appendTextTrackData(uri);
  6162. trackElement.label = label;
  6163. trackElement.kind = kind;
  6164. trackElement.srclang = language;
  6165. // Because we're pulling in the text track file via Javascript, the
  6166. // same-origin policy applies. If you'd like to have a player served
  6167. // from one domain, but the text track served from another, you'll
  6168. // need to enable CORS in order to do so. In addition to enabling CORS
  6169. // on the server serving the text tracks, you will need to add the
  6170. // crossorigin attribute to the video element itself.
  6171. if (!this.video_.getAttribute('crossorigin')) {
  6172. this.video_.setAttribute('crossorigin', 'anonymous');
  6173. }
  6174. this.video_.appendChild(trackElement);
  6175. return trackElement;
  6176. }
  6177. /**
  6178. * @param {string} uri
  6179. * @param {!shaka.net.NetworkingEngine} netEngine
  6180. * @param {shaka.extern.RetryParameters} retryParams
  6181. * @return {!Promise<BufferSource>}
  6182. * @private
  6183. */
  6184. async getTextData_(uri, netEngine, retryParams) {
  6185. const type = shaka.net.NetworkingEngine.RequestType.SEGMENT;
  6186. const request = shaka.net.NetworkingEngine.makeRequest([uri], retryParams);
  6187. request.method = 'GET';
  6188. this.cmcdManager_.applyTextData(request);
  6189. const response = await netEngine.request(type, request).promise;
  6190. return response.data;
  6191. }
  6192. /**
  6193. * Converts an input string to a WebVTT format string.
  6194. *
  6195. * @param {BufferSource} buffer
  6196. * @param {string} mimeType
  6197. * @param {!Array<!shaka.extern.AdCuePoint>} adCuePoints
  6198. * @return {string}
  6199. * @private
  6200. */
  6201. convertToWebVTT_(buffer, mimeType, adCuePoints) {
  6202. const factory = shaka.text.TextEngine.findParser(mimeType);
  6203. if (factory) {
  6204. const obj = factory();
  6205. const time = {
  6206. periodStart: 0,
  6207. segmentStart: 0,
  6208. segmentEnd: this.video_.duration,
  6209. vttOffset: 0,
  6210. };
  6211. const data = shaka.util.BufferUtils.toUint8(buffer);
  6212. const cues = obj.parseMedia(
  6213. data, time, /* uri= */ null, /* images= */ []);
  6214. return shaka.text.WebVttGenerator.convert(cues, adCuePoints);
  6215. }
  6216. throw new shaka.util.Error(
  6217. shaka.util.Error.Severity.CRITICAL,
  6218. shaka.util.Error.Category.TEXT,
  6219. shaka.util.Error.Code.MISSING_TEXT_PLUGIN,
  6220. mimeType);
  6221. }
  6222. /**
  6223. * Set the maximum resolution that the platform's hardware can handle.
  6224. *
  6225. * @param {number} width
  6226. * @param {number} height
  6227. * @export
  6228. */
  6229. setMaxHardwareResolution(width, height) {
  6230. this.maxHwRes_.width = width;
  6231. this.maxHwRes_.height = height;
  6232. }
  6233. /**
  6234. * Retry streaming after a streaming failure has occurred. When the player has
  6235. * not loaded content or is loading content, this will be a no-op and will
  6236. * return <code>false</code>.
  6237. *
  6238. * <p>
  6239. * If the player has loaded content, and streaming has not seen an error, this
  6240. * will return <code>false</code>.
  6241. *
  6242. * <p>
  6243. * If the player has loaded content, and streaming seen an error, but the
  6244. * could not resume streaming, this will return <code>false</code>.
  6245. *
  6246. * @param {number=} retryDelaySeconds
  6247. * @return {boolean}
  6248. * @export
  6249. */
  6250. retryStreaming(retryDelaySeconds = 0.1) {
  6251. return this.loadMode_ == shaka.Player.LoadMode.MEDIA_SOURCE ?
  6252. this.streamingEngine_.retry(retryDelaySeconds) :
  6253. false;
  6254. }
  6255. /**
  6256. * Get the manifest that the player has loaded. If the player has not loaded
  6257. * any content, this will return <code>null</code>.
  6258. *
  6259. * NOTE: This structure is NOT covered by semantic versioning compatibility
  6260. * guarantees. It may change at any time!
  6261. *
  6262. * This is marked as deprecated to warn Closure Compiler users at compile-time
  6263. * to avoid using this method.
  6264. *
  6265. * @return {?shaka.extern.Manifest}
  6266. * @export
  6267. * @deprecated
  6268. */
  6269. getManifest() {
  6270. shaka.log.alwaysWarn(
  6271. 'Shaka Player\'s internal Manifest structure is NOT covered by ' +
  6272. 'semantic versioning compatibility guarantees. It may change at any ' +
  6273. 'time! Please consider filing a feature request for whatever you ' +
  6274. 'use getManifest() for.');
  6275. return this.manifest_;
  6276. }
  6277. /**
  6278. * Get the type of manifest parser that the player is using. If the player has
  6279. * not loaded any content, this will return <code>null</code>.
  6280. *
  6281. * @return {?shaka.extern.ManifestParser.Factory}
  6282. * @export
  6283. */
  6284. getManifestParserFactory() {
  6285. return this.parserFactory_;
  6286. }
  6287. /**
  6288. * Gets information about the currently fetched video, audio, and text.
  6289. * In the case of a multi-codec or multi-mimeType manifest, this can let you
  6290. * determine the exact codecs and mimeTypes being fetched at the moment.
  6291. *
  6292. * @return {!shaka.extern.PlaybackInfo}
  6293. * @export
  6294. */
  6295. getFetchedPlaybackInfo() {
  6296. const output = /** @type {!shaka.extern.PlaybackInfo} */ ({
  6297. 'video': null,
  6298. 'audio': null,
  6299. 'text': null,
  6300. });
  6301. if (this.loadMode_ != shaka.Player.LoadMode.MEDIA_SOURCE) {
  6302. return output;
  6303. }
  6304. const ContentType = shaka.util.ManifestParserUtils.ContentType;
  6305. const variant = this.streamingEngine_.getCurrentVariant();
  6306. const textStream = this.streamingEngine_.getCurrentTextStream();
  6307. const currentTime = this.video_.currentTime;
  6308. for (const stream of [variant.video, variant.audio, textStream]) {
  6309. if (!stream || !stream.segmentIndex) {
  6310. continue;
  6311. }
  6312. const position = stream.segmentIndex.find(currentTime);
  6313. const reference = stream.segmentIndex.get(position);
  6314. const info = /** @type {!shaka.extern.PlaybackStreamInfo} */ ({
  6315. 'codecs': reference.codecs || stream.codecs,
  6316. 'mimeType': reference.mimeType || stream.mimeType,
  6317. 'bandwidth': reference.bandwidth || stream.bandwidth,
  6318. });
  6319. if (stream.type == ContentType.VIDEO) {
  6320. info['width'] = stream.width;
  6321. info['height'] = stream.height;
  6322. output['video'] = info;
  6323. } else if (stream.type == ContentType.AUDIO) {
  6324. output['audio'] = info;
  6325. } else if (stream.type == ContentType.TEXT) {
  6326. output['text'] = info;
  6327. }
  6328. }
  6329. return output;
  6330. }
  6331. /**
  6332. * @param {shaka.extern.Variant} variant
  6333. * @param {boolean} fromAdaptation
  6334. * @private
  6335. */
  6336. addVariantToSwitchHistory_(variant, fromAdaptation) {
  6337. const switchHistory = this.stats_.getSwitchHistory();
  6338. switchHistory.updateCurrentVariant(variant, fromAdaptation);
  6339. }
  6340. /**
  6341. * @param {shaka.extern.Stream} textStream
  6342. * @param {boolean} fromAdaptation
  6343. * @private
  6344. */
  6345. addTextStreamToSwitchHistory_(textStream, fromAdaptation) {
  6346. const switchHistory = this.stats_.getSwitchHistory();
  6347. switchHistory.updateCurrentText(textStream, fromAdaptation);
  6348. }
  6349. /**
  6350. * @return {shaka.extern.PlayerConfiguration}
  6351. * @private
  6352. */
  6353. defaultConfig_() {
  6354. const config = shaka.util.PlayerConfiguration.createDefault();
  6355. config.streaming.failureCallback = (error) => {
  6356. this.defaultStreamingFailureCallback_(error);
  6357. };
  6358. // Because this.video_ may not be set when the config is built, the default
  6359. // TextDisplay factory must capture a reference to "this".
  6360. config.textDisplayFactory = () => {
  6361. // On iOS where the Fullscreen API is not available we prefer
  6362. // SimpleTextDisplayer because it works with the Fullscreen API of the
  6363. // video element itself.
  6364. const Platform = shaka.util.Platform;
  6365. if (this.videoContainer_ &&
  6366. (!Platform.isApple() || document.fullscreenEnabled)) {
  6367. return new shaka.text.UITextDisplayer(
  6368. this.video_, this.videoContainer_);
  6369. } else {
  6370. if ('addTextTrack' in this.video_) {
  6371. return new shaka.text.SimpleTextDisplayer(
  6372. this.video_, shaka.Player.TextTrackLabel);
  6373. } else {
  6374. shaka.log.warning('Text tracks are not supported by the ' +
  6375. 'browser, disabling.');
  6376. return new shaka.text.StubTextDisplayer();
  6377. }
  6378. }
  6379. };
  6380. return config;
  6381. }
  6382. /**
  6383. * Set the videoContainer to construct UITextDisplayer.
  6384. * @param {HTMLElement} videoContainer
  6385. * @export
  6386. */
  6387. setVideoContainer(videoContainer) {
  6388. this.videoContainer_ = videoContainer;
  6389. }
  6390. /**
  6391. * @param {!shaka.util.Error} error
  6392. * @private
  6393. */
  6394. defaultStreamingFailureCallback_(error) {
  6395. // For live streams, we retry streaming automatically for certain errors.
  6396. // For VOD streams, all streaming failures are fatal.
  6397. if (!this.isLive()) {
  6398. return;
  6399. }
  6400. let retryDelaySeconds = null;
  6401. if (error.code == shaka.util.Error.Code.BAD_HTTP_STATUS ||
  6402. error.code == shaka.util.Error.Code.HTTP_ERROR) {
  6403. // These errors can be near-instant, so delay a bit before retrying.
  6404. retryDelaySeconds = 1;
  6405. if (this.config_.streaming.lowLatencyMode) {
  6406. retryDelaySeconds = 0.1;
  6407. }
  6408. } else if (error.code == shaka.util.Error.Code.TIMEOUT) {
  6409. // We already waited for a timeout, so retry quickly.
  6410. retryDelaySeconds = 0.1;
  6411. }
  6412. if (retryDelaySeconds != null) {
  6413. error.severity = shaka.util.Error.Severity.RECOVERABLE;
  6414. shaka.log.warning('Live streaming error. Retrying automatically...');
  6415. this.retryStreaming(retryDelaySeconds);
  6416. }
  6417. }
  6418. /**
  6419. * For CEA closed captions embedded in the video streams, create dummy text
  6420. * stream. This can be safely called again on existing manifests, for
  6421. * manifest updates.
  6422. * @param {!shaka.extern.Manifest} manifest
  6423. * @private
  6424. */
  6425. makeTextStreamsForClosedCaptions_(manifest) {
  6426. const ContentType = shaka.util.ManifestParserUtils.ContentType;
  6427. const TextStreamKind = shaka.util.ManifestParserUtils.TextStreamKind;
  6428. const CEA608_MIME = shaka.util.MimeUtils.CEA608_CLOSED_CAPTION_MIMETYPE;
  6429. const CEA708_MIME = shaka.util.MimeUtils.CEA708_CLOSED_CAPTION_MIMETYPE;
  6430. // A set, to make sure we don't create two text streams for the same video.
  6431. const closedCaptionsSet = new Set();
  6432. for (const textStream of manifest.textStreams) {
  6433. if (textStream.mimeType == CEA608_MIME ||
  6434. textStream.mimeType == CEA708_MIME) {
  6435. // This function might be called on a manifest update, so don't make a
  6436. // new text stream for closed caption streams we have seen before.
  6437. closedCaptionsSet.add(textStream.originalId);
  6438. }
  6439. }
  6440. for (const variant of manifest.variants) {
  6441. const video = variant.video;
  6442. if (video && video.closedCaptions) {
  6443. for (const id of video.closedCaptions.keys()) {
  6444. if (!closedCaptionsSet.has(id)) {
  6445. const mimeType = id.startsWith('CC') ? CEA608_MIME : CEA708_MIME;
  6446. // Add an empty segmentIndex, for the benefit of the period combiner
  6447. // in our builtin DASH parser.
  6448. const segmentIndex = new shaka.media.MetaSegmentIndex();
  6449. const language = video.closedCaptions.get(id);
  6450. const textStream = {
  6451. id: this.nextExternalStreamId_++, // A globally unique ID.
  6452. originalId: id, // The CC ID string, like 'CC1', 'CC3', etc.
  6453. groupId: null,
  6454. createSegmentIndex: () => Promise.resolve(),
  6455. segmentIndex,
  6456. mimeType,
  6457. codecs: '',
  6458. kind: TextStreamKind.CLOSED_CAPTION,
  6459. encrypted: false,
  6460. drmInfos: [],
  6461. keyIds: new Set(),
  6462. language,
  6463. originalLanguage: language,
  6464. label: null,
  6465. type: ContentType.TEXT,
  6466. primary: false,
  6467. trickModeVideo: null,
  6468. dependencyStream: null,
  6469. emsgSchemeIdUris: null,
  6470. roles: video.roles,
  6471. forced: false,
  6472. channelsCount: null,
  6473. audioSamplingRate: null,
  6474. spatialAudio: false,
  6475. closedCaptions: null,
  6476. accessibilityPurpose: null,
  6477. external: false,
  6478. fastSwitching: false,
  6479. fullMimeTypes: new Set([shaka.util.MimeUtils.getFullType(
  6480. mimeType, '')]),
  6481. isAudioMuxedInVideo: false,
  6482. baseOriginalId: null,
  6483. };
  6484. manifest.textStreams.push(textStream);
  6485. closedCaptionsSet.add(id);
  6486. }
  6487. }
  6488. }
  6489. }
  6490. }
  6491. /**
  6492. * @param {shaka.extern.Variant} initialVariant
  6493. * @param {number} time
  6494. * @return {!Promise<number>}
  6495. * @private
  6496. */
  6497. async adjustStartTime_(initialVariant, time) {
  6498. /** @type {?shaka.extern.Stream} */
  6499. const activeAudio = initialVariant.audio;
  6500. /** @type {?shaka.extern.Stream} */
  6501. const activeVideo = initialVariant.video;
  6502. /**
  6503. * @param {?shaka.extern.Stream} stream
  6504. * @param {number} time
  6505. * @return {!Promise<?number>}
  6506. */
  6507. const getAdjustedTime = async (stream, time) => {
  6508. if (!stream) {
  6509. return null;
  6510. }
  6511. if (!stream.segmentIndex) {
  6512. await stream.createSegmentIndex();
  6513. }
  6514. const iter = stream.segmentIndex.getIteratorForTime(time);
  6515. const ref = iter ? iter.next().value : null;
  6516. if (!ref) {
  6517. return null;
  6518. }
  6519. const refTime = ref.startTime;
  6520. goog.asserts.assert(refTime <= time,
  6521. 'Segment should start before target time!');
  6522. return refTime;
  6523. };
  6524. const audioStartTime = await getAdjustedTime(activeAudio, time);
  6525. const videoStartTime = await getAdjustedTime(activeVideo, time);
  6526. // If we have both video and audio times, pick the larger one. If we picked
  6527. // the smaller one, that one will download an entire segment to buffer the
  6528. // difference.
  6529. if (videoStartTime != null && audioStartTime != null) {
  6530. return Math.max(videoStartTime, audioStartTime);
  6531. } else if (videoStartTime != null) {
  6532. return videoStartTime;
  6533. } else if (audioStartTime != null) {
  6534. return audioStartTime;
  6535. } else {
  6536. return time;
  6537. }
  6538. }
  6539. /**
  6540. * Update the buffering state to be either "we are buffering" or "we are not
  6541. * buffering", firing events to the app as needed.
  6542. *
  6543. * @private
  6544. */
  6545. updateBufferState_() {
  6546. const isBuffering = this.isBuffering();
  6547. shaka.log.v2('Player changing buffering state to', isBuffering);
  6548. // Make sure we have all the components we need before we consider ourselves
  6549. // as being loaded.
  6550. // TODO: Make the check for "loaded" simpler.
  6551. const loaded = this.stats_ && this.bufferObserver_ && this.playhead_;
  6552. if (loaded) {
  6553. if (this.config_.streaming.rebufferingGoal == 0) {
  6554. // Disable buffer control with playback rate
  6555. this.playRateController_.setBuffering(/* isBuffering= */ false);
  6556. } else {
  6557. this.playRateController_.setBuffering(isBuffering);
  6558. }
  6559. if (this.cmcdManager_) {
  6560. this.cmcdManager_.setBuffering(isBuffering);
  6561. }
  6562. this.updateStateHistory_();
  6563. const dynamicTargetLatency =
  6564. this.config_.streaming.liveSync.dynamicTargetLatency.enabled;
  6565. const maxAttempts =
  6566. this.config_.streaming.liveSync.dynamicTargetLatency.maxAttempts;
  6567. if (dynamicTargetLatency && isBuffering &&
  6568. this.rebufferingCount_ < maxAttempts) {
  6569. const maxLatency =
  6570. this.config_.streaming.liveSync.dynamicTargetLatency.maxLatency;
  6571. const targetLatencyTolerance =
  6572. this.config_.streaming.liveSync.targetLatencyTolerance;
  6573. const rebufferIncrement =
  6574. this.config_.streaming.liveSync.dynamicTargetLatency
  6575. .rebufferIncrement;
  6576. if (this.currentTargetLatency_) {
  6577. this.currentTargetLatency_ = Math.min(
  6578. this.currentTargetLatency_ +
  6579. ++this.rebufferingCount_ * rebufferIncrement,
  6580. maxLatency - targetLatencyTolerance);
  6581. }
  6582. }
  6583. }
  6584. // Surface the buffering event so that the app knows if/when we are
  6585. // buffering.
  6586. const eventName = shaka.util.FakeEvent.EventName.Buffering;
  6587. const data = (new Map()).set('buffering', isBuffering);
  6588. this.dispatchEvent(shaka.Player.makeEvent_(eventName, data));
  6589. }
  6590. /**
  6591. * A callback for when the playback rate changes. We need to watch the
  6592. * playback rate so that if the playback rate on the media element changes
  6593. * (that was not caused by our play rate controller) we can notify the
  6594. * controller so that it can stay in-sync with the change.
  6595. *
  6596. * @private
  6597. */
  6598. onRateChange_() {
  6599. /** @type {number} */
  6600. const newRate = this.video_.playbackRate;
  6601. // On Edge, when someone seeks using the native controls, it will set the
  6602. // playback rate to zero until they finish seeking, after which it will
  6603. // return the playback rate.
  6604. //
  6605. // If the playback rate changes while seeking, Edge will cache the playback
  6606. // rate and use it after seeking.
  6607. //
  6608. // https://github.com/shaka-project/shaka-player/issues/951
  6609. if (newRate == 0) {
  6610. return;
  6611. }
  6612. if (this.playRateController_) {
  6613. // The playback rate has changed. This could be us or someone else.
  6614. // If this was us, setting the rate again will be a no-op.
  6615. this.playRateController_.set(newRate);
  6616. if (this.loadMode_ == shaka.Player.LoadMode.MEDIA_SOURCE) {
  6617. this.abrManager_.playbackRateChanged(newRate);
  6618. }
  6619. this.setupTrickPlayEventListeners_(newRate);
  6620. }
  6621. const event = shaka.Player.makeEvent_(
  6622. shaka.util.FakeEvent.EventName.RateChange);
  6623. this.dispatchEvent(event);
  6624. }
  6625. /**
  6626. * Configures all the necessary listeners when trick play is being performed.
  6627. *
  6628. * @param {number} rate
  6629. * @private
  6630. */
  6631. setupTrickPlayEventListeners_(rate) {
  6632. this.trickPlayEventManager_.removeAll();
  6633. this.trickPlayEventManager_.listen(this.video_, 'timeupdate', () => {
  6634. const currentTime = this.video_.currentTime;
  6635. const seekRange = this.seekRange();
  6636. const safeSeekOffset = this.isLive() ?
  6637. this.config_.streaming.safeSeekOffset : 0;
  6638. // Cancel trick play if we hit the beginning or end of the seekable
  6639. // (Sub-second accuracy not required here)
  6640. if (rate > 0) {
  6641. if (Math.floor(currentTime) >= Math.floor(seekRange.end)) {
  6642. this.cancelTrickPlay();
  6643. }
  6644. } else {
  6645. if (Math.floor(currentTime) <=
  6646. Math.floor(seekRange.start + safeSeekOffset)) {
  6647. this.cancelTrickPlay();
  6648. }
  6649. }
  6650. });
  6651. }
  6652. /**
  6653. * Try updating the state history. If the player has not finished
  6654. * initializing, this will be a no-op.
  6655. *
  6656. * @private
  6657. */
  6658. updateStateHistory_() {
  6659. // If we have not finish initializing, this will be a no-op.
  6660. if (!this.stats_) {
  6661. return;
  6662. }
  6663. if (!this.bufferObserver_) {
  6664. return;
  6665. }
  6666. const State = shaka.media.BufferingObserver.State;
  6667. const history = this.stats_.getStateHistory();
  6668. let updateState = 'playing';
  6669. if (this.bufferObserver_.getState() == State.STARVING) {
  6670. updateState = 'buffering';
  6671. } else if (this.isEnded()) {
  6672. updateState = 'ended';
  6673. } else if (this.video_.paused) {
  6674. updateState = 'paused';
  6675. }
  6676. const stateChanged = history.update(updateState);
  6677. if (stateChanged) {
  6678. const eventName = shaka.util.FakeEvent.EventName.StateChanged;
  6679. const data = (new Map()).set('newstate', updateState);
  6680. this.dispatchEvent(shaka.Player.makeEvent_(eventName, data));
  6681. }
  6682. }
  6683. /**
  6684. * Callback for liveSync and vodDynamicPlaybackRate
  6685. *
  6686. * @private
  6687. */
  6688. onTimeUpdate_() {
  6689. const playbackRate = this.video_.playbackRate;
  6690. const isLive = this.isLive();
  6691. if (this.config_.streaming.vodDynamicPlaybackRate && !isLive) {
  6692. const minPlaybackRate =
  6693. this.config_.streaming.vodDynamicPlaybackRateLowBufferRate;
  6694. const bufferFullness = this.getBufferFullness();
  6695. const bufferThreshold =
  6696. this.config_.streaming.vodDynamicPlaybackRateBufferRatio;
  6697. if (bufferFullness <= bufferThreshold) {
  6698. if (playbackRate != minPlaybackRate) {
  6699. shaka.log.debug('Buffer fullness ratio (' + bufferFullness + ') ' +
  6700. 'is less than the vodDynamicPlaybackRateBufferRatio (' +
  6701. bufferThreshold + '). Updating playbackRate to ' + minPlaybackRate);
  6702. this.trickPlay(minPlaybackRate, /* useTrickPlayTrack= */ false);
  6703. }
  6704. } else if (bufferFullness == 1) {
  6705. if (playbackRate !== this.playRateController_.getDefaultRate()) {
  6706. shaka.log.debug('Buffer is full. Cancel trick play.');
  6707. this.cancelTrickPlay();
  6708. }
  6709. }
  6710. }
  6711. // If the live stream has reached its end, do not sync.
  6712. if (!isLive) {
  6713. return;
  6714. }
  6715. const seekRange = this.seekRange();
  6716. if (!Number.isFinite(seekRange.end)) {
  6717. return;
  6718. }
  6719. const currentTime = this.video_.currentTime;
  6720. if (currentTime < seekRange.start) {
  6721. // Bad stream?
  6722. return;
  6723. }
  6724. // We don't want to block the user from pausing the stream.
  6725. if (this.video_.paused) {
  6726. return;
  6727. }
  6728. let targetLatency;
  6729. let maxLatency;
  6730. let maxPlaybackRate;
  6731. let minLatency;
  6732. let minPlaybackRate;
  6733. const targetLatencyTolerance =
  6734. this.config_.streaming.liveSync.targetLatencyTolerance;
  6735. const dynamicTargetLatency =
  6736. this.config_.streaming.liveSync.dynamicTargetLatency.enabled;
  6737. const stabilityThreshold =
  6738. this.config_.streaming.liveSync.dynamicTargetLatency.stabilityThreshold;
  6739. if (this.config_.streaming.liveSync &&
  6740. this.config_.streaming.liveSync.enabled) {
  6741. targetLatency = this.config_.streaming.liveSync.targetLatency;
  6742. maxLatency = targetLatency + targetLatencyTolerance;
  6743. minLatency = Math.max(0, targetLatency - targetLatencyTolerance);
  6744. maxPlaybackRate = this.config_.streaming.liveSync.maxPlaybackRate;
  6745. minPlaybackRate = this.config_.streaming.liveSync.minPlaybackRate;
  6746. } else {
  6747. // serviceDescription must override if it is defined in the MPD and
  6748. // liveSync configuration is not set.
  6749. if (this.manifest_ && this.manifest_.serviceDescription) {
  6750. targetLatency = this.manifest_.serviceDescription.targetLatency;
  6751. if (this.manifest_.serviceDescription.targetLatency != null) {
  6752. maxLatency = this.manifest_.serviceDescription.targetLatency +
  6753. targetLatencyTolerance;
  6754. } else if (this.manifest_.serviceDescription.maxLatency != null) {
  6755. maxLatency = this.manifest_.serviceDescription.maxLatency;
  6756. }
  6757. if (this.manifest_.serviceDescription.targetLatency != null) {
  6758. minLatency = Math.max(0,
  6759. this.manifest_.serviceDescription.targetLatency -
  6760. targetLatencyTolerance);
  6761. } else if (this.manifest_.serviceDescription.minLatency != null) {
  6762. minLatency = this.manifest_.serviceDescription.minLatency;
  6763. }
  6764. maxPlaybackRate =
  6765. this.manifest_.serviceDescription.maxPlaybackRate ||
  6766. this.config_.streaming.liveSync.maxPlaybackRate;
  6767. minPlaybackRate =
  6768. this.manifest_.serviceDescription.minPlaybackRate ||
  6769. this.config_.streaming.liveSync.minPlaybackRate;
  6770. }
  6771. }
  6772. if (!this.currentTargetLatency_ && typeof targetLatency === 'number') {
  6773. this.currentTargetLatency_ = targetLatency;
  6774. }
  6775. const maxAttempts =
  6776. this.config_.streaming.liveSync.dynamicTargetLatency.maxAttempts;
  6777. if (dynamicTargetLatency && this.targetLatencyReached_ &&
  6778. this.currentTargetLatency_ !== null &&
  6779. typeof targetLatency === 'number' &&
  6780. this.rebufferingCount_ < maxAttempts &&
  6781. (Date.now() - this.targetLatencyReached_) > stabilityThreshold * 1000) {
  6782. const dynamicMinLatency =
  6783. this.config_.streaming.liveSync.dynamicTargetLatency.minLatency;
  6784. const latencyIncrement = (targetLatency - dynamicMinLatency) / 2;
  6785. this.currentTargetLatency_ = Math.max(
  6786. this.currentTargetLatency_ - latencyIncrement,
  6787. // current target latency should be within the tolerance of the min
  6788. // latency to not overshoot it
  6789. dynamicMinLatency + targetLatencyTolerance);
  6790. this.targetLatencyReached_ = Date.now();
  6791. }
  6792. if (dynamicTargetLatency && this.currentTargetLatency_ !== null) {
  6793. maxLatency = this.currentTargetLatency_ + targetLatencyTolerance;
  6794. minLatency = this.currentTargetLatency_ - targetLatencyTolerance;
  6795. }
  6796. const latency = seekRange.end - this.video_.currentTime;
  6797. let offset = 0;
  6798. // In src= mode, the seek range isn't updated frequently enough, so we need
  6799. // to fudge the latency number with an offset. The playback rate is used
  6800. // as an offset, since that is the amount we catch up 1 second of
  6801. // accelerated playback.
  6802. if (this.loadMode_ == shaka.Player.LoadMode.SRC_EQUALS) {
  6803. const buffered = this.video_.buffered;
  6804. if (buffered.length > 0) {
  6805. const bufferedEnd = buffered.end(buffered.length - 1);
  6806. offset = Math.max(maxPlaybackRate, bufferedEnd - seekRange.end);
  6807. }
  6808. }
  6809. const panicMode = this.config_.streaming.liveSync.panicMode;
  6810. const panicThreshold =
  6811. this.config_.streaming.liveSync.panicThreshold * 1000;
  6812. const timeSinceLastRebuffer =
  6813. Date.now() - this.bufferObserver_.getLastRebufferTime();
  6814. if (panicMode && !minPlaybackRate) {
  6815. minPlaybackRate = this.config_.streaming.liveSync.minPlaybackRate;
  6816. }
  6817. if (panicMode && minPlaybackRate &&
  6818. timeSinceLastRebuffer <= panicThreshold) {
  6819. if (playbackRate != minPlaybackRate) {
  6820. shaka.log.debug('Time since last rebuffer (' +
  6821. timeSinceLastRebuffer + 's) ' +
  6822. 'is less than the live sync panicThreshold (' + panicThreshold +
  6823. 's). Updating playbackRate to ' + minPlaybackRate);
  6824. this.trickPlay(minPlaybackRate, /* useTrickPlayTrack= */ false);
  6825. }
  6826. } else if (maxLatency != undefined && maxPlaybackRate &&
  6827. (latency - offset) > maxLatency) {
  6828. if (playbackRate != maxPlaybackRate) {
  6829. shaka.log.debug('Latency (' + latency + 's) is greater than ' +
  6830. 'live sync maxLatency (' + maxLatency + 's). ' +
  6831. 'Updating playbackRate to ' + maxPlaybackRate);
  6832. this.trickPlay(maxPlaybackRate, /* useTrickPlayTrack= */ false);
  6833. }
  6834. this.targetLatencyReached_ = null;
  6835. } else if (minLatency != undefined && minPlaybackRate &&
  6836. (latency - offset) < minLatency) {
  6837. if (playbackRate != minPlaybackRate) {
  6838. shaka.log.debug('Latency (' + latency + 's) is smaller than ' +
  6839. 'live sync minLatency (' + minLatency + 's). ' +
  6840. 'Updating playbackRate to ' + minPlaybackRate);
  6841. this.trickPlay(minPlaybackRate, /* useTrickPlayTrack= */ false);
  6842. }
  6843. this.targetLatencyReached_ = null;
  6844. } else if (playbackRate !== this.playRateController_.getDefaultRate()) {
  6845. this.cancelTrickPlay();
  6846. this.targetLatencyReached_ = Date.now();
  6847. }
  6848. }
  6849. /**
  6850. * Callback for video progress events
  6851. *
  6852. * @private
  6853. */
  6854. onVideoProgress_() {
  6855. if (!this.video_) {
  6856. return;
  6857. }
  6858. const isQuartile = (quartilePercent, currentPercent) => {
  6859. const NumberUtils = shaka.util.NumberUtils;
  6860. if ((NumberUtils.isFloatEqual(quartilePercent, currentPercent) ||
  6861. currentPercent > quartilePercent) &&
  6862. this.completionPercent_ < quartilePercent) {
  6863. this.completionPercent_ = quartilePercent;
  6864. return true;
  6865. }
  6866. return false;
  6867. };
  6868. const checkEnded = () => {
  6869. if (this.config_ && this.config_.playRangeEnd != Infinity) {
  6870. // Make sure the video stops when we reach the end.
  6871. // This is required when there is a custom playRangeEnd specified.
  6872. if (this.isEnded()) {
  6873. this.video_.pause();
  6874. }
  6875. }
  6876. };
  6877. const seekRange = this.seekRange();
  6878. const duration = seekRange.end - seekRange.start;
  6879. const completionRatio =
  6880. duration > 0 ? this.video_.currentTime / duration : 0;
  6881. if (isNaN(completionRatio)) {
  6882. return;
  6883. }
  6884. const percent = completionRatio * 100;
  6885. let event;
  6886. if (isQuartile(0, percent)) {
  6887. event = shaka.Player.makeEvent_(shaka.util.FakeEvent.EventName.Started);
  6888. } else if (isQuartile(25, percent)) {
  6889. event = shaka.Player.makeEvent_(
  6890. shaka.util.FakeEvent.EventName.FirstQuartile);
  6891. } else if (isQuartile(50, percent)) {
  6892. event = shaka.Player.makeEvent_(
  6893. shaka.util.FakeEvent.EventName.Midpoint);
  6894. } else if (isQuartile(75, percent)) {
  6895. event = shaka.Player.makeEvent_(
  6896. shaka.util.FakeEvent.EventName.ThirdQuartile);
  6897. } else if (isQuartile(100, percent)) {
  6898. event = shaka.Player.makeEvent_(
  6899. shaka.util.FakeEvent.EventName.Complete);
  6900. checkEnded();
  6901. } else {
  6902. checkEnded();
  6903. }
  6904. if (event) {
  6905. this.dispatchEvent(event);
  6906. }
  6907. }
  6908. /**
  6909. * Callback from Playhead.
  6910. *
  6911. * @private
  6912. */
  6913. onSeek_() {
  6914. if (this.playheadObservers_) {
  6915. this.playheadObservers_.notifyOfSeek();
  6916. }
  6917. if (this.streamingEngine_) {
  6918. this.streamingEngine_.seeked();
  6919. }
  6920. if (this.bufferObserver_) {
  6921. // If we seek into an unbuffered range, we should fire a 'buffering' event
  6922. // immediately. If StreamingEngine can buffer fast enough, we may not
  6923. // update our buffering tracking otherwise.
  6924. this.pollBufferState_();
  6925. }
  6926. }
  6927. /**
  6928. * Update AbrManager with variants while taking into account restrictions,
  6929. * preferences, and ABR.
  6930. *
  6931. * On error, this dispatches an error event and returns false.
  6932. *
  6933. * @return {boolean} True if successful.
  6934. * @private
  6935. */
  6936. updateAbrManagerVariants_() {
  6937. try {
  6938. goog.asserts.assert(this.manifest_, 'Manifest should exist by now!');
  6939. this.manifestFilterer_.checkRestrictedVariants(this.manifest_);
  6940. } catch (e) {
  6941. this.onError_(e);
  6942. return false;
  6943. }
  6944. const playableVariants = shaka.util.StreamUtils.getPlayableVariants(
  6945. this.manifest_.variants);
  6946. // Update the abr manager with newly filtered variants.
  6947. const adaptationSet = this.currentAdaptationSetCriteria_.create(
  6948. playableVariants);
  6949. this.abrManager_.setVariants(Array.from(adaptationSet.values()));
  6950. return true;
  6951. }
  6952. /**
  6953. * Chooses a variant from all possible variants while taking into account
  6954. * restrictions, preferences, and ABR.
  6955. *
  6956. * On error, this dispatches an error event and returns null.
  6957. *
  6958. * @return {?shaka.extern.Variant}
  6959. * @private
  6960. */
  6961. chooseVariant_() {
  6962. if (this.updateAbrManagerVariants_()) {
  6963. return this.abrManager_.chooseVariant();
  6964. } else {
  6965. return null;
  6966. }
  6967. }
  6968. /**
  6969. * Checks to re-enable variants that were temporarily disabled due to network
  6970. * errors. If any variants are enabled this way, a new variant may be chosen
  6971. * for playback.
  6972. * @private
  6973. */
  6974. checkVariants_() {
  6975. goog.asserts.assert(this.manifest_, 'Should have manifest!');
  6976. const now = Date.now() / 1000;
  6977. let hasVariantUpdate = false;
  6978. /** @type {function(shaka.extern.Variant):string} */
  6979. const streamsAsString = (variant) => {
  6980. let str = '';
  6981. if (variant.video) {
  6982. str += 'video:' + variant.video.id;
  6983. }
  6984. if (variant.audio) {
  6985. str += str ? '&' : '';
  6986. str += 'audio:' + variant.audio.id;
  6987. }
  6988. return str;
  6989. };
  6990. let shouldStopTimer = true;
  6991. for (const variant of this.manifest_.variants) {
  6992. if (variant.disabledUntilTime > 0 && variant.disabledUntilTime <= now) {
  6993. variant.disabledUntilTime = 0;
  6994. hasVariantUpdate = true;
  6995. shaka.log.v2('Re-enabled variant with ' + streamsAsString(variant));
  6996. }
  6997. if (variant.disabledUntilTime > 0) {
  6998. shouldStopTimer = false;
  6999. }
  7000. }
  7001. if (shouldStopTimer) {
  7002. this.checkVariantsTimer_.stop();
  7003. }
  7004. if (hasVariantUpdate) {
  7005. // Reconsider re-enabled variant for ABR switching.
  7006. this.chooseVariantAndSwitch_(
  7007. /* clearBuffer= */ false, /* safeMargin= */ undefined,
  7008. /* force= */ false, /* fromAdaptation= */ false);
  7009. }
  7010. }
  7011. /**
  7012. * Choose a text stream from all possible text streams while taking into
  7013. * account user preference.
  7014. *
  7015. * @return {?shaka.extern.Stream}
  7016. * @private
  7017. */
  7018. chooseTextStream_() {
  7019. const subset = shaka.util.StreamUtils.filterStreamsByLanguageAndRole(
  7020. this.manifest_.textStreams,
  7021. this.currentTextLanguage_,
  7022. this.currentTextRole_,
  7023. this.currentTextForced_);
  7024. return subset[0] || null;
  7025. }
  7026. /**
  7027. * Chooses a new Variant. If the new variant differs from the old one, it
  7028. * adds the new one to the switch history and switches to it.
  7029. *
  7030. * Called after a config change, a key status event, or an explicit language
  7031. * change.
  7032. *
  7033. * @param {boolean=} clearBuffer Optional clear buffer or not when
  7034. * switch to new variant
  7035. * Defaults to true if not provided
  7036. * @param {number=} safeMargin Optional amount of buffer (in seconds) to
  7037. * retain when clearing the buffer.
  7038. * Defaults to 0 if not provided. Ignored if clearBuffer is false.
  7039. * @private
  7040. */
  7041. chooseVariantAndSwitch_(clearBuffer = true, safeMargin = 0, force = false,
  7042. fromAdaptation = true) {
  7043. goog.asserts.assert(this.config_, 'Must not be destroyed');
  7044. // Because we're running this after a config change (manual language
  7045. // change) or a key status event, it is always okay to clear the buffer
  7046. // here.
  7047. const chosenVariant = this.chooseVariant_();
  7048. if (chosenVariant) {
  7049. this.switchVariant_(chosenVariant, fromAdaptation,
  7050. clearBuffer, safeMargin, force);
  7051. }
  7052. }
  7053. /**
  7054. * @param {shaka.extern.Variant} variant
  7055. * @param {boolean} fromAdaptation
  7056. * @param {boolean} clearBuffer
  7057. * @param {number} safeMargin
  7058. * @param {boolean=} force
  7059. * @private
  7060. */
  7061. switchVariant_(variant, fromAdaptation, clearBuffer, safeMargin,
  7062. force = false) {
  7063. const currentVariant = this.streamingEngine_.getCurrentVariant();
  7064. if (variant == currentVariant) {
  7065. shaka.log.debug('Variant already selected.');
  7066. // If you want to clear the buffer, we force to reselect the same variant.
  7067. // We don't need to reset the timestampOffset since it's the same variant,
  7068. // so 'adaptation' isn't passed here.
  7069. if (clearBuffer) {
  7070. this.streamingEngine_.switchVariant(variant, clearBuffer, safeMargin,
  7071. /* force= */ true);
  7072. }
  7073. return;
  7074. }
  7075. // Add entries to the history.
  7076. this.addVariantToSwitchHistory_(variant, fromAdaptation);
  7077. this.streamingEngine_.switchVariant(
  7078. variant, clearBuffer, safeMargin, force,
  7079. /* adaptation= */ fromAdaptation);
  7080. let oldTrack = null;
  7081. if (currentVariant) {
  7082. oldTrack = shaka.util.StreamUtils.variantToTrack(currentVariant);
  7083. }
  7084. const newTrack = shaka.util.StreamUtils.variantToTrack(variant);
  7085. newTrack.active = true;
  7086. if (this.lcevcDec_) {
  7087. this.lcevcDec_.updateVariant(variant, this.getManifestType());
  7088. }
  7089. if (fromAdaptation) {
  7090. // Dispatch an 'adaptation' event
  7091. this.onAdaptation_(oldTrack, newTrack);
  7092. } else {
  7093. // Dispatch a 'variantchanged' event
  7094. this.onVariantChanged_(oldTrack, newTrack);
  7095. }
  7096. // Dispatch a 'audiotrackschanged' event if necessary
  7097. this.checkAudioTracksChanged_(oldTrack, newTrack);
  7098. }
  7099. /**
  7100. * @param {AudioTrack} track
  7101. * @private
  7102. */
  7103. switchHtml5Track_(track) {
  7104. goog.asserts.assert(this.video_ && this.video_.audioTracks,
  7105. 'Video and video.audioTracks should not be null!');
  7106. const audioTracks = Array.from(this.video_.audioTracks);
  7107. const currentTrack = audioTracks.find((t) => t.enabled);
  7108. // This will reset the "enabled" of other tracks to false.
  7109. track.enabled = true;
  7110. if (!currentTrack) {
  7111. return;
  7112. }
  7113. // AirPlay does not reset the "enabled" of other tracks to false, so
  7114. // it must be changed by hand.
  7115. if (track.id !== currentTrack.id) {
  7116. currentTrack.enabled = false;
  7117. }
  7118. const oldTrack =
  7119. shaka.util.StreamUtils.html5AudioTrackToTrack(currentTrack);
  7120. const newTrack =
  7121. shaka.util.StreamUtils.html5AudioTrackToTrack(track);
  7122. // Dispatch a 'variantchanged' event
  7123. this.onVariantChanged_(oldTrack, newTrack);
  7124. // Dispatch a 'audiotrackschanged' event if necessary
  7125. this.checkAudioTracksChanged_(oldTrack, newTrack);
  7126. }
  7127. /**
  7128. * Decide during startup if text should be streamed/shown.
  7129. * @private
  7130. */
  7131. setInitialTextState_(initialVariant, initialTextStream) {
  7132. // Check if we should show text (based on difference between audio and text
  7133. // languages).
  7134. if (initialTextStream) {
  7135. goog.asserts.assert(this.config_, 'Must not be destroyed');
  7136. if (shaka.util.StreamUtils.shouldInitiallyShowText(
  7137. initialVariant.audio, initialTextStream, this.config_)) {
  7138. this.isTextVisible_ = true;
  7139. }
  7140. if (this.isTextVisible_) {
  7141. // If the cached value says to show text, then update the text displayer
  7142. // since it defaults to not shown.
  7143. this.textDisplayer_.setTextVisibility(true);
  7144. goog.asserts.assert(this.shouldStreamText_(),
  7145. 'Should be streaming text');
  7146. }
  7147. this.onTextTrackVisibility_();
  7148. } else {
  7149. this.isTextVisible_ = false;
  7150. }
  7151. }
  7152. /**
  7153. * Callback from StreamingEngine.
  7154. *
  7155. * @private
  7156. */
  7157. onManifestUpdate_() {
  7158. if (this.parser_ && this.parser_.update) {
  7159. this.parser_.update();
  7160. }
  7161. }
  7162. /**
  7163. * Callback from StreamingEngine.
  7164. *
  7165. * @param {number} start
  7166. * @param {number} end
  7167. * @param {shaka.util.ManifestParserUtils.ContentType} contentType
  7168. * @param {boolean} isMuxed
  7169. *
  7170. * @private
  7171. */
  7172. onSegmentAppended_(start, end, contentType, isMuxed) {
  7173. const ContentType = shaka.util.ManifestParserUtils.ContentType;
  7174. if (contentType != ContentType.TEXT) {
  7175. // When we append a segment to media source (via streaming engine) we are
  7176. // changing what data we have buffered, so notify the playhead of the
  7177. // change.
  7178. if (this.playhead_) {
  7179. this.playhead_.notifyOfBufferingChange();
  7180. // Skip the initial buffer gap
  7181. const startTime = this.mediaSourceEngine_.bufferStart(contentType);
  7182. if (
  7183. !this.isLive() &&
  7184. // If not paused then GapJumpingController will handle this gap.
  7185. this.video_.paused &&
  7186. !this.video_.seeking &&
  7187. startTime != null &&
  7188. startTime > 0 &&
  7189. this.playhead_.getTime() < startTime
  7190. ) {
  7191. this.playhead_.setStartTime(startTime);
  7192. }
  7193. }
  7194. this.pollBufferState_();
  7195. }
  7196. // Dispatch an event for users to consume, too.
  7197. const data = new Map()
  7198. .set('start', start)
  7199. .set('end', end)
  7200. .set('contentType', contentType)
  7201. .set('isMuxed', isMuxed);
  7202. this.dispatchEvent(shaka.Player.makeEvent_(
  7203. shaka.util.FakeEvent.EventName.SegmentAppended, data));
  7204. }
  7205. /**
  7206. * Callback from AbrManager.
  7207. *
  7208. * @param {shaka.extern.Variant} variant
  7209. * @param {boolean=} clearBuffer
  7210. * @param {number=} safeMargin Optional amount of buffer (in seconds) to
  7211. * retain when clearing the buffer.
  7212. * Defaults to 0 if not provided. Ignored if clearBuffer is false.
  7213. * @private
  7214. */
  7215. switch_(variant, clearBuffer = false, safeMargin = 0) {
  7216. shaka.log.debug('switch_');
  7217. goog.asserts.assert(this.config_.abr.enabled,
  7218. 'AbrManager should not call switch while disabled!');
  7219. if (!this.manifest_) {
  7220. // It could come from a preload manager operation.
  7221. return;
  7222. }
  7223. if (!this.streamingEngine_) {
  7224. // There's no way to change it.
  7225. return;
  7226. }
  7227. if (variant == this.streamingEngine_.getCurrentVariant()) {
  7228. // This isn't a change.
  7229. return;
  7230. }
  7231. this.switchVariant_(variant, /* fromAdaptation= */ true,
  7232. clearBuffer, safeMargin);
  7233. }
  7234. /**
  7235. * Dispatches an 'adaptation' event.
  7236. * @param {?shaka.extern.Track} from
  7237. * @param {shaka.extern.Track} to
  7238. * @private
  7239. */
  7240. onAdaptation_(from, to) {
  7241. // Delay the 'adaptation' event so that StreamingEngine has time to absorb
  7242. // the changes before the user tries to query it.
  7243. const data = new Map()
  7244. .set('oldTrack', from)
  7245. .set('newTrack', to);
  7246. const event = shaka.Player.makeEvent_(
  7247. shaka.util.FakeEvent.EventName.Adaptation, data);
  7248. this.delayDispatchEvent_(event);
  7249. }
  7250. /**
  7251. * Dispatches a 'trackschanged' event.
  7252. * @private
  7253. */
  7254. onTracksChanged_() {
  7255. // Delay the 'trackschanged' event so StreamingEngine has time to absorb the
  7256. // changes before the user tries to query it.
  7257. const event = shaka.Player.makeEvent_(
  7258. shaka.util.FakeEvent.EventName.TracksChanged);
  7259. this.delayDispatchEvent_(event);
  7260. // Also fire 'audiotrackschanged' event.
  7261. this.onAudioTracksChanged_();
  7262. }
  7263. /**
  7264. * Dispatches a 'variantchanged' event.
  7265. * @param {?shaka.extern.Track} from
  7266. * @param {shaka.extern.Track} to
  7267. * @private
  7268. */
  7269. onVariantChanged_(from, to) {
  7270. // Delay the 'variantchanged' event so StreamingEngine has time to absorb
  7271. // the changes before the user tries to query it.
  7272. const data = new Map()
  7273. .set('oldTrack', from)
  7274. .set('newTrack', to);
  7275. const event = shaka.Player.makeEvent_(
  7276. shaka.util.FakeEvent.EventName.VariantChanged, data);
  7277. this.delayDispatchEvent_(event);
  7278. }
  7279. /**
  7280. * Dispatches a 'audiotrackschanged' event if necessary
  7281. * @param {?shaka.extern.Track} from
  7282. * @param {shaka.extern.Track} to
  7283. * @private
  7284. */
  7285. checkAudioTracksChanged_(from, to) {
  7286. let dispatchEvent = false;
  7287. if (!from || from.audioId != to.audioId ||
  7288. from.audioGroupId != to.audioGroupId) {
  7289. dispatchEvent = true;
  7290. }
  7291. if (dispatchEvent) {
  7292. this.onAudioTracksChanged_();
  7293. }
  7294. }
  7295. /** @private */
  7296. onAudioTracksChanged_() {
  7297. // Delay the 'audiotrackschanged' event so StreamingEngine has time to
  7298. // absorb the changes before the user tries to query it.
  7299. const event = shaka.Player.makeEvent_(
  7300. shaka.util.FakeEvent.EventName.AudioTracksChanged);
  7301. this.delayDispatchEvent_(event);
  7302. }
  7303. /**
  7304. * Dispatches a 'textchanged' event.
  7305. * @private
  7306. */
  7307. onTextChanged_() {
  7308. // Delay the 'textchanged' event so StreamingEngine time to absorb the
  7309. // changes before the user tries to query it.
  7310. const event = shaka.Player.makeEvent_(
  7311. shaka.util.FakeEvent.EventName.TextChanged);
  7312. this.delayDispatchEvent_(event);
  7313. }
  7314. /** @private */
  7315. onTextTrackVisibility_() {
  7316. const event = shaka.Player.makeEvent_(
  7317. shaka.util.FakeEvent.EventName.TextTrackVisibility);
  7318. this.delayDispatchEvent_(event);
  7319. }
  7320. /** @private */
  7321. onAbrStatusChanged_() {
  7322. // Restore disabled variants if abr get disabled
  7323. if (!this.config_.abr.enabled) {
  7324. this.restoreDisabledVariants_();
  7325. }
  7326. const data = (new Map()).set('newStatus', this.config_.abr.enabled);
  7327. this.delayDispatchEvent_(shaka.Player.makeEvent_(
  7328. shaka.util.FakeEvent.EventName.AbrStatusChanged, data));
  7329. }
  7330. /**
  7331. * @private
  7332. */
  7333. setTextDisplayerLanguage_() {
  7334. const activeTextTrack = this.getTextTracks().find((t) => t.active);
  7335. if (activeTextTrack &&
  7336. this.textDisplayer_ && this.textDisplayer_.setTextLanguage) {
  7337. this.textDisplayer_.setTextLanguage(activeTextTrack.language);
  7338. }
  7339. }
  7340. /**
  7341. * @param {boolean} updateAbrManager
  7342. * @private
  7343. */
  7344. restoreDisabledVariants_(updateAbrManager=true) {
  7345. if (this.loadMode_ != shaka.Player.LoadMode.MEDIA_SOURCE) {
  7346. return;
  7347. }
  7348. goog.asserts.assert(this.manifest_, 'Should have manifest!');
  7349. shaka.log.v2('Restoring all disabled streams...');
  7350. this.checkVariantsTimer_.stop();
  7351. for (const variant of this.manifest_.variants) {
  7352. variant.disabledUntilTime = 0;
  7353. }
  7354. if (updateAbrManager) {
  7355. this.updateAbrManagerVariants_();
  7356. }
  7357. }
  7358. /**
  7359. * Temporarily disable all variants containing |stream|
  7360. * @param {shaka.extern.Stream} stream
  7361. * @param {number} disableTime
  7362. * @return {boolean}
  7363. */
  7364. disableStream(stream, disableTime) {
  7365. if (!this.config_.abr.enabled ||
  7366. this.loadMode_ === shaka.Player.LoadMode.DESTROYED) {
  7367. return false;
  7368. }
  7369. if (!navigator.onLine) {
  7370. // Don't disable variants if we're completely offline, or else we end up
  7371. // rapidly restricting all of them.
  7372. return false;
  7373. }
  7374. if (disableTime == 0) {
  7375. return false;
  7376. }
  7377. if (!this.manifest_) {
  7378. return false;
  7379. }
  7380. // It only makes sense to disable a stream if we have an alternative else we
  7381. // end up disabling all variants.
  7382. const hasAltStream = this.manifest_.variants.some((variant) => {
  7383. const altStream = variant[stream.type];
  7384. if (altStream && altStream.id !== stream.id &&
  7385. !variant.disabledUntilTime) {
  7386. if (shaka.util.StreamUtils.isAudio(stream)) {
  7387. return stream.language === altStream.language;
  7388. }
  7389. return true;
  7390. }
  7391. return false;
  7392. });
  7393. if (hasAltStream) {
  7394. let didDisableStream = false;
  7395. let isTrickModeVideo = false;
  7396. for (const variant of this.manifest_.variants) {
  7397. const candidate = variant[stream.type];
  7398. if (!candidate) {
  7399. continue;
  7400. }
  7401. if (candidate.id === stream.id) {
  7402. variant.disabledUntilTime = (Date.now() / 1000) + disableTime;
  7403. didDisableStream = true;
  7404. shaka.log.v2(
  7405. 'Disabled stream ' + stream.type + ':' + stream.id +
  7406. ' for ' + disableTime + ' seconds...');
  7407. } else if (candidate.trickModeVideo &&
  7408. candidate.trickModeVideo.id == stream.id) {
  7409. isTrickModeVideo = true;
  7410. }
  7411. }
  7412. if (!didDisableStream && isTrickModeVideo) {
  7413. return false;
  7414. }
  7415. goog.asserts.assert(didDisableStream, 'Must have disabled stream');
  7416. this.checkVariantsTimer_.tickEvery(1);
  7417. // Get the safeMargin to ensure a seamless playback
  7418. const {video} = this.getBufferedInfo();
  7419. const safeMargin =
  7420. video.reduce((size, {start, end}) => size + end - start, 0);
  7421. // Update abr manager variants and switch to recover playback
  7422. this.chooseVariantAndSwitch_(
  7423. /* clearBuffer= */ false, /* safeMargin= */ safeMargin,
  7424. /* force= */ true, /* fromAdaptation= */ false);
  7425. return true;
  7426. }
  7427. shaka.log.warning(
  7428. 'No alternate stream found for active ' + stream.type + ' stream. ' +
  7429. 'Will ignore request to disable stream...');
  7430. return false;
  7431. }
  7432. /**
  7433. * @param {!shaka.util.Error} error
  7434. * @private
  7435. */
  7436. async onError_(error) {
  7437. goog.asserts.assert(error instanceof shaka.util.Error, 'Wrong error type!');
  7438. // Errors dispatched after |destroy| is called are not meaningful and should
  7439. // be safe to ignore.
  7440. if (this.loadMode_ == shaka.Player.LoadMode.DESTROYED) {
  7441. return;
  7442. }
  7443. if (error.severity === shaka.util.Error.Severity.RECOVERABLE) {
  7444. this.stats_.addNonFatalError();
  7445. }
  7446. let fireError = true;
  7447. if (this.fullyLoaded_ && this.manifest_ && this.streamingEngine_ &&
  7448. (error.code == shaka.util.Error.Code.VIDEO_ERROR ||
  7449. error.code == shaka.util.Error.Code.MEDIA_SOURCE_OPERATION_FAILED ||
  7450. error.code == shaka.util.Error.Code.MEDIA_SOURCE_OPERATION_THREW ||
  7451. error.code == shaka.util.Error.Code.TRANSMUXING_FAILED)) {
  7452. if (shaka.util.Platform.isApple() &&
  7453. error.code == shaka.util.Error.Code.VIDEO_ERROR) {
  7454. // Wait until the MSE error occurs
  7455. return;
  7456. }
  7457. try {
  7458. const ret = await this.streamingEngine_.resetMediaSource();
  7459. fireError = !ret;
  7460. if (ret) {
  7461. const event = shaka.Player.makeEvent_(
  7462. shaka.util.FakeEvent.EventName.MediaSourceRecovered);
  7463. this.dispatchEvent(event);
  7464. }
  7465. } catch (e) {
  7466. fireError = true;
  7467. }
  7468. }
  7469. if (!fireError) {
  7470. return;
  7471. }
  7472. // Restore disabled variant if the player experienced a critical error.
  7473. if (error.severity === shaka.util.Error.Severity.CRITICAL) {
  7474. this.restoreDisabledVariants_(/* updateAbrManager= */ false);
  7475. }
  7476. const eventName = shaka.util.FakeEvent.EventName.Error;
  7477. const event = shaka.Player.makeEvent_(
  7478. eventName, (new Map()).set('detail', error));
  7479. this.dispatchEvent(event);
  7480. if (event.defaultPrevented) {
  7481. error.handled = true;
  7482. }
  7483. }
  7484. /**
  7485. * Load a new font on the page. If the font was already loaded, it does
  7486. * nothing.
  7487. *
  7488. * @param {string} name
  7489. * @param {string} url
  7490. * @export
  7491. */
  7492. async addFont(name, url) {
  7493. if ('fonts' in document && 'FontFace' in window ) {
  7494. await document.fonts.ready;
  7495. if (!('entries' in document.fonts)) {
  7496. return;
  7497. }
  7498. const fontFaceSetIteratorToArray = (target) => {
  7499. const iterable = target.entries();
  7500. const results = [];
  7501. let iterator = iterable.next();
  7502. while (iterator.done === false) {
  7503. results.push(iterator.value);
  7504. iterator = iterable.next();
  7505. }
  7506. return results;
  7507. };
  7508. for (const fontFace of fontFaceSetIteratorToArray(document.fonts)) {
  7509. if (fontFace.family == name && fontFace.display == 'swap') {
  7510. // Font already loaded.
  7511. return;
  7512. }
  7513. }
  7514. const fontFace = new FontFace(name, `url(${url})`, {display: 'swap'});
  7515. document.fonts.add(fontFace);
  7516. }
  7517. }
  7518. /**
  7519. * When we fire region events, we need to copy the information out of the
  7520. * region to break the connection with the player's internal data. We do the
  7521. * copy here because this is the transition point between the player and the
  7522. * app.
  7523. *
  7524. * @param {!shaka.util.FakeEvent.EventName} eventName
  7525. * @param {shaka.extern.TimelineRegionInfo} region
  7526. * @param {shaka.util.FakeEventTarget=} eventTarget
  7527. *
  7528. * @private
  7529. */
  7530. onRegionEvent_(eventName, region, eventTarget = this) {
  7531. // Always make a copy to avoid exposing our internal data to the app.
  7532. /** @type {shaka.extern.TimelineRegionInfo} */
  7533. const clone = {
  7534. schemeIdUri: region.schemeIdUri,
  7535. value: region.value,
  7536. startTime: region.startTime,
  7537. endTime: region.endTime,
  7538. id: region.id,
  7539. timescale: region.timescale,
  7540. eventElement: region.eventElement,
  7541. eventNode: region.eventNode,
  7542. };
  7543. const data = (new Map()).set('detail', clone);
  7544. eventTarget.dispatchEvent(shaka.Player.makeEvent_(eventName, data));
  7545. }
  7546. /**
  7547. * When notified of a media quality change we need to emit a
  7548. * MediaQualityChange event to the app.
  7549. *
  7550. * @param {shaka.extern.MediaQualityInfo} mediaQuality
  7551. * @param {number} position
  7552. * @param {boolean} audioTrackChanged This is to specify whether this should
  7553. * trigger a MediaQualityChangedEvent or an AudioTrackChangedEvent. Defaults
  7554. * to false to trigger MediaQualityChangedEvent.
  7555. *
  7556. * @private
  7557. */
  7558. onMediaQualityChange_(mediaQuality, position, audioTrackChanged = false) {
  7559. // Always make a copy to avoid exposing our internal data to the app.
  7560. const clone = {
  7561. bandwidth: mediaQuality.bandwidth,
  7562. audioSamplingRate: mediaQuality.audioSamplingRate,
  7563. codecs: mediaQuality.codecs,
  7564. contentType: mediaQuality.contentType,
  7565. frameRate: mediaQuality.frameRate,
  7566. height: mediaQuality.height,
  7567. mimeType: mediaQuality.mimeType,
  7568. channelsCount: mediaQuality.channelsCount,
  7569. pixelAspectRatio: mediaQuality.pixelAspectRatio,
  7570. width: mediaQuality.width,
  7571. label: mediaQuality.label,
  7572. roles: mediaQuality.roles,
  7573. language: mediaQuality.language,
  7574. };
  7575. const data = new Map()
  7576. .set('mediaQuality', clone)
  7577. .set('position', position);
  7578. this.dispatchEvent(shaka.Player.makeEvent_(
  7579. audioTrackChanged ?
  7580. shaka.util.FakeEvent.EventName.AudioTrackChanged :
  7581. shaka.util.FakeEvent.EventName.MediaQualityChanged,
  7582. data));
  7583. }
  7584. /**
  7585. * Turn the media element's error object into a Shaka Player error object.
  7586. *
  7587. * @param {boolean=} printAllErrors
  7588. * @return {shaka.util.Error}
  7589. * @private
  7590. */
  7591. videoErrorToShakaError_(printAllErrors = true) {
  7592. goog.asserts.assert(this.video_.error,
  7593. 'Video error expected, but missing!');
  7594. if (!this.video_.error) {
  7595. if (printAllErrors) {
  7596. return new shaka.util.Error(
  7597. shaka.util.Error.Severity.CRITICAL,
  7598. shaka.util.Error.Category.MEDIA,
  7599. shaka.util.Error.Code.VIDEO_ERROR);
  7600. }
  7601. return null;
  7602. }
  7603. const code = this.video_.error.code;
  7604. if (!printAllErrors && code == 1 /* MEDIA_ERR_ABORTED */) {
  7605. // Ignore this error code, which should only occur when navigating away or
  7606. // deliberately stopping playback of HTTP content.
  7607. return null;
  7608. }
  7609. // Extra error information from MS Edge:
  7610. let extended = this.video_.error.msExtendedCode;
  7611. if (extended) {
  7612. // Convert to unsigned:
  7613. if (extended < 0) {
  7614. extended += Math.pow(2, 32);
  7615. }
  7616. // Format as hex:
  7617. extended = extended.toString(16);
  7618. }
  7619. // Extra error information from Chrome:
  7620. const message = this.video_.error.message;
  7621. return new shaka.util.Error(
  7622. shaka.util.Error.Severity.CRITICAL,
  7623. shaka.util.Error.Category.MEDIA,
  7624. shaka.util.Error.Code.VIDEO_ERROR,
  7625. code, extended, message);
  7626. }
  7627. /**
  7628. * @param {!Event} event
  7629. * @private
  7630. */
  7631. onVideoError_(event) {
  7632. const error = this.videoErrorToShakaError_(/* printAllErrors= */ false);
  7633. if (!error) {
  7634. return;
  7635. }
  7636. this.onError_(error);
  7637. }
  7638. /**
  7639. * @param {!Object<string, string>} keyStatusMap A map of hex key IDs to
  7640. * statuses.
  7641. * @private
  7642. */
  7643. onKeyStatus_(keyStatusMap) {
  7644. goog.asserts.assert(this.streamingEngine_, 'Cannot be called in src= mode');
  7645. const event = shaka.Player.makeEvent_(
  7646. shaka.util.FakeEvent.EventName.KeyStatusChanged);
  7647. this.dispatchEvent(event);
  7648. let keyIds = Object.keys(keyStatusMap);
  7649. if (keyIds.length == 0) {
  7650. shaka.log.warning(
  7651. 'Got a key status event without any key statuses, so we don\'t ' +
  7652. 'know the real key statuses. If we don\'t have all the keys, ' +
  7653. 'you\'ll need to set restrictions so we don\'t select those tracks.');
  7654. }
  7655. // Non-standard version of global key status. Modify it to match standard
  7656. // behavior.
  7657. if (keyIds.length == 1 && keyIds[0] == '') {
  7658. keyIds = ['00'];
  7659. keyStatusMap = {'00': keyStatusMap['']};
  7660. }
  7661. // If EME is using a synthetic key ID, the only key ID is '00' (a single 0
  7662. // byte). In this case, it is only used to report global success/failure.
  7663. // See note about old platforms in: https://bit.ly/2tpez5Z
  7664. const isGlobalStatus = keyIds.length == 1 && keyIds[0] == '00';
  7665. if (isGlobalStatus) {
  7666. shaka.log.warning(
  7667. 'Got a synthetic key status event, so we don\'t know the real key ' +
  7668. 'statuses. If we don\'t have all the keys, you\'ll need to set ' +
  7669. 'restrictions so we don\'t select those tracks.');
  7670. }
  7671. const restrictedStatuses = shaka.media.ManifestFilterer.restrictedStatuses;
  7672. let tracksChanged = false;
  7673. goog.asserts.assert(this.drmEngine_, 'drmEngine should be non-null here.');
  7674. // Only filter tracks for keys if we have some key statuses to look at.
  7675. if (keyIds.length) {
  7676. const currentKeySystem = this.keySystem();
  7677. const clearKeys = shaka.util.MapUtils.asMap(this.config_.drm.clearKeys);
  7678. for (const variant of this.manifest_.variants) {
  7679. const streams = shaka.util.StreamUtils.getVariantStreams(variant);
  7680. for (const stream of streams) {
  7681. const originalAllowed = variant.allowedByKeySystem;
  7682. // Only update if we have key IDs for the stream. If the keys aren't
  7683. // all present, then the track should be restricted.
  7684. if (stream.keyIds.size) {
  7685. // If we are not using clearkeys, and the stream has drmInfos we
  7686. // only want to check the keyIds of the keySystem we are using.
  7687. // Other keySystems might have other keyIds that might not be
  7688. // valid in this case. This can happen in HLS if the manifest
  7689. // has Widevine with keyIds and PlayReady without keyIds and we are
  7690. // using PlayReady.
  7691. if (stream.drmInfos.length && !clearKeys.size) {
  7692. for (const drmInfo of stream.drmInfos) {
  7693. if (drmInfo.keyIds.size &&
  7694. drmInfo.keySystem == currentKeySystem) {
  7695. variant.allowedByKeySystem = true;
  7696. for (const keyId of drmInfo.keyIds) {
  7697. const keyStatus =
  7698. keyStatusMap[isGlobalStatus ? '00' : keyId];
  7699. if (keyStatus || this.drmEngine_.hasManifestInitData()) {
  7700. variant.allowedByKeySystem =
  7701. variant.allowedByKeySystem &&
  7702. !!keyStatus &&
  7703. !restrictedStatuses.includes(keyStatus);
  7704. } // if (keyStatus || this.drmEngine_.hasManifestInitData())
  7705. } // for (const keyId of drmInfo.keyIds)
  7706. } // if (drmInfo.keyIds.size && ...
  7707. } // for (const drmInfo of stream.drmInfos
  7708. } else {
  7709. variant.allowedByKeySystem = true;
  7710. for (const keyId of stream.keyIds) {
  7711. const keyStatus = keyStatusMap[isGlobalStatus ? '00' : keyId];
  7712. if (keyStatus || this.drmEngine_.hasManifestInitData()) {
  7713. variant.allowedByKeySystem = variant.allowedByKeySystem &&
  7714. !!keyStatus && !restrictedStatuses.includes(keyStatus);
  7715. }
  7716. } // for (const keyId of stream.keyIds)
  7717. } // if (stream.drmInfos.length && !clearKeys.size)
  7718. } // if (stream.keyIds.size)
  7719. if (originalAllowed != variant.allowedByKeySystem) {
  7720. tracksChanged = true;
  7721. }
  7722. } // for (const stream of streams)
  7723. } // for (const variant of this.manifest_.variants)
  7724. } // if (keyIds.size)
  7725. if (tracksChanged) {
  7726. this.onTracksChanged_();
  7727. const variantsUpdated = this.updateAbrManagerVariants_();
  7728. if (!variantsUpdated) {
  7729. return;
  7730. }
  7731. }
  7732. const currentVariant = this.streamingEngine_.getCurrentVariant();
  7733. if (currentVariant && !currentVariant.allowedByKeySystem) {
  7734. shaka.log.debug('Choosing new streams after key status changed');
  7735. this.chooseVariantAndSwitch_();
  7736. }
  7737. }
  7738. /**
  7739. * @return {boolean} true if we should stream text right now.
  7740. * @private
  7741. */
  7742. shouldStreamText_() {
  7743. return this.config_.streaming.alwaysStreamText || this.isTextTrackVisible();
  7744. }
  7745. /**
  7746. * Applies playRangeStart and playRangeEnd to the given timeline. This will
  7747. * only affect non-live content.
  7748. *
  7749. * @param {shaka.media.PresentationTimeline} timeline
  7750. * @param {number} playRangeStart
  7751. * @param {number} playRangeEnd
  7752. *
  7753. * @private
  7754. */
  7755. static applyPlayRange_(timeline, playRangeStart, playRangeEnd) {
  7756. if (playRangeStart > 0) {
  7757. if (timeline.isLive()) {
  7758. shaka.log.warning(
  7759. '|playRangeStart| has been configured for live content. ' +
  7760. 'Ignoring the setting.');
  7761. } else {
  7762. timeline.setUserSeekStart(playRangeStart);
  7763. }
  7764. }
  7765. // If the playback has been configured to end before the end of the
  7766. // presentation, update the duration unless it's live content.
  7767. const fullDuration = timeline.getDuration();
  7768. if (playRangeEnd < fullDuration) {
  7769. if (timeline.isLive()) {
  7770. shaka.log.warning(
  7771. '|playRangeEnd| has been configured for live content. ' +
  7772. 'Ignoring the setting.');
  7773. } else {
  7774. timeline.setDuration(playRangeEnd);
  7775. }
  7776. }
  7777. }
  7778. /**
  7779. * Fire an event, but wait a little bit so that the immediate execution can
  7780. * complete before the event is handled.
  7781. *
  7782. * @param {!shaka.util.FakeEvent} event
  7783. * @private
  7784. */
  7785. async delayDispatchEvent_(event) {
  7786. // Wait until the next interpreter cycle.
  7787. await Promise.resolve();
  7788. // Only dispatch the event if we are still alive.
  7789. if (this.loadMode_ != shaka.Player.LoadMode.DESTROYED) {
  7790. this.dispatchEvent(event);
  7791. }
  7792. }
  7793. /**
  7794. * Get the normalized languages for a group of tracks.
  7795. *
  7796. * @param {!Array<?shaka.extern.Track>} tracks
  7797. * @return {!Set<string>}
  7798. * @private
  7799. */
  7800. static getLanguagesFrom_(tracks) {
  7801. const languages = new Set();
  7802. for (const track of tracks) {
  7803. if (track.language) {
  7804. languages.add(shaka.util.LanguageUtils.normalize(track.language));
  7805. } else {
  7806. languages.add('und');
  7807. }
  7808. }
  7809. return languages;
  7810. }
  7811. /**
  7812. * Get all permutations of normalized languages and role for a group of
  7813. * tracks.
  7814. *
  7815. * @param {!Array<?shaka.extern.Track>} tracks
  7816. * @return {!Array<shaka.extern.LanguageRole>}
  7817. * @private
  7818. */
  7819. static getLanguageAndRolesFrom_(tracks) {
  7820. /** @type {!Map<string, !Set>} */
  7821. const languageToRoles = new Map();
  7822. /** @type {!Map<string, !Map<string, string>>} */
  7823. const languageRoleToLabel = new Map();
  7824. for (const track of tracks) {
  7825. let language = 'und';
  7826. let roles = [];
  7827. if (track.language) {
  7828. language = shaka.util.LanguageUtils.normalize(track.language);
  7829. }
  7830. if (track.type == 'variant') {
  7831. roles = track.audioRoles;
  7832. } else {
  7833. roles = track.roles;
  7834. }
  7835. if (!roles || !roles.length) {
  7836. // We must have an empty role so that we will still get a language-role
  7837. // entry from our Map.
  7838. roles = [''];
  7839. }
  7840. if (!languageToRoles.has(language)) {
  7841. languageToRoles.set(language, new Set());
  7842. }
  7843. for (const role of roles) {
  7844. languageToRoles.get(language).add(role);
  7845. if (track.label) {
  7846. if (!languageRoleToLabel.has(language)) {
  7847. languageRoleToLabel.set(language, new Map());
  7848. }
  7849. languageRoleToLabel.get(language).set(role, track.label);
  7850. }
  7851. }
  7852. }
  7853. // Flatten our map to an array of language-role pairs.
  7854. const pairings = [];
  7855. languageToRoles.forEach((roles, language) => {
  7856. for (const role of roles) {
  7857. let label = null;
  7858. if (languageRoleToLabel.has(language) &&
  7859. languageRoleToLabel.get(language).has(role)) {
  7860. label = languageRoleToLabel.get(language).get(role);
  7861. }
  7862. pairings.push({language, role, label});
  7863. }
  7864. });
  7865. return pairings;
  7866. }
  7867. /**
  7868. * Assuming the player is playing content with media source, check if the
  7869. * player has buffered enough content to make it to the end of the
  7870. * presentation.
  7871. *
  7872. * @return {boolean}
  7873. * @private
  7874. */
  7875. isBufferedToEndMS_() {
  7876. goog.asserts.assert(
  7877. this.video_,
  7878. 'We need a video element to get buffering information');
  7879. goog.asserts.assert(
  7880. this.mediaSourceEngine_,
  7881. 'We need a media source engine to get buffering information');
  7882. goog.asserts.assert(
  7883. this.manifest_,
  7884. 'We need a manifest to get buffering information');
  7885. // This is a strong guarantee that we are buffered to the end, because it
  7886. // means the playhead is already at that end.
  7887. if (this.isEnded()) {
  7888. return true;
  7889. }
  7890. // This means that MediaSource has buffered the final segment in all
  7891. // SourceBuffers and is no longer accepting additional segments.
  7892. if (this.mediaSourceEngine_.ended()) {
  7893. return true;
  7894. }
  7895. // Live streams are "buffered to the end" when they have buffered to the
  7896. // live edge or beyond (into the region covered by the presentation delay).
  7897. if (this.manifest_.presentationTimeline.isLive()) {
  7898. const liveEdge =
  7899. this.manifest_.presentationTimeline.getSegmentAvailabilityEnd();
  7900. const bufferEnd =
  7901. shaka.media.TimeRangesUtils.bufferEnd(this.video_.buffered);
  7902. if (bufferEnd != null && bufferEnd >= liveEdge) {
  7903. return true;
  7904. }
  7905. }
  7906. return false;
  7907. }
  7908. /**
  7909. * Assuming the player is playing content with src=, check if the player has
  7910. * buffered enough content to make it to the end of the presentation.
  7911. *
  7912. * @return {boolean}
  7913. * @private
  7914. */
  7915. isBufferedToEndSrc_() {
  7916. goog.asserts.assert(
  7917. this.video_,
  7918. 'We need a video element to get buffering information');
  7919. // This is a strong guarantee that we are buffered to the end, because it
  7920. // means the playhead is already at that end.
  7921. if (this.isEnded()) {
  7922. return true;
  7923. }
  7924. // If we have buffered to the duration of the content, it means we will have
  7925. // enough content to buffer to the end of the presentation.
  7926. const bufferEnd =
  7927. shaka.media.TimeRangesUtils.bufferEnd(this.video_.buffered);
  7928. // Because Safari's native HLS reports slightly inaccurate values for
  7929. // bufferEnd here, we use a fudge factor. Without this, we can end up in a
  7930. // buffering state at the end of the stream. See issue #2117.
  7931. const fudge = 1; // 1000 ms
  7932. return bufferEnd != null && bufferEnd >= this.video_.duration - fudge;
  7933. }
  7934. /**
  7935. * Create an error for when we purposely interrupt a load operation.
  7936. *
  7937. * @return {!shaka.util.Error}
  7938. * @private
  7939. */
  7940. createAbortLoadError_() {
  7941. return new shaka.util.Error(
  7942. shaka.util.Error.Severity.CRITICAL,
  7943. shaka.util.Error.Category.PLAYER,
  7944. shaka.util.Error.Code.LOAD_INTERRUPTED);
  7945. }
  7946. /**
  7947. * Indicate if we are using remote playback.
  7948. *
  7949. * @return {boolean}
  7950. * @export
  7951. */
  7952. isRemotePlayback() {
  7953. if (!this.video_ || !this.video_.remote) {
  7954. return false;
  7955. }
  7956. return this.video_.remote.state != 'disconnected';
  7957. }
  7958. /**
  7959. * Indicate if the video has ended.
  7960. *
  7961. * @return {boolean}
  7962. * @export
  7963. */
  7964. isEnded() {
  7965. if (!this.video_ || this.video_.ended) {
  7966. return true;
  7967. }
  7968. return this.fullyLoaded_ && !this.isLive() &&
  7969. this.video_.currentTime >= this.seekRange().end;
  7970. }
  7971. };
  7972. /**
  7973. * In order to know what method of loading the player used for some content, we
  7974. * have this enum. It lets us know if content has not been loaded, loaded with
  7975. * media source, or loaded with src equals.
  7976. *
  7977. * This enum has a low resolution, because it is only meant to express the
  7978. * outer limits of the various states that the player is in. For example, when
  7979. * someone calls a public method on player, it should not matter if they have
  7980. * initialized drm engine, it should only matter if they finished loading
  7981. * content.
  7982. *
  7983. * @enum {number}
  7984. * @export
  7985. */
  7986. shaka.Player.LoadMode = {
  7987. 'DESTROYED': 0,
  7988. 'NOT_LOADED': 1,
  7989. 'MEDIA_SOURCE': 2,
  7990. 'SRC_EQUALS': 3,
  7991. };
  7992. /**
  7993. * The typical buffering threshold. When we have less than this buffered (in
  7994. * seconds), we enter a buffering state. This specific value is based on manual
  7995. * testing and evaluation across a variety of platforms.
  7996. *
  7997. * To make the buffering logic work in all cases, this "typical" threshold will
  7998. * be overridden if the rebufferingGoal configuration is too low.
  7999. *
  8000. * @const {number}
  8001. * @private
  8002. */
  8003. shaka.Player.TYPICAL_BUFFERING_THRESHOLD_ = 0.5;
  8004. /**
  8005. * @define {string} A version number taken from git at compile time.
  8006. * @export
  8007. */
  8008. // eslint-disable-next-line no-useless-concat
  8009. shaka.Player.version = 'v4.14.9' + '-uncompiled'; // x-release-please-version
  8010. // Initialize the deprecation system using the version string we just set
  8011. // on the player.
  8012. shaka.Deprecate.init(shaka.Player.version);
  8013. /** @private {!Map<string, function(): *>} */
  8014. shaka.Player.supportPlugins_ = new Map();
  8015. /** @private {?shaka.extern.IAdManager.Factory} */
  8016. shaka.Player.adManagerFactory_ = null;
  8017. /**
  8018. * @const {string}
  8019. */
  8020. shaka.Player.TextTrackLabel = 'Shaka Player TextTrack';