Source: lib/player.js

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