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