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