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