Source: lib/hls/hls_parser.js

  1. /*! @license
  2. * Shaka Player
  3. * Copyright 2016 Google LLC
  4. * SPDX-License-Identifier: Apache-2.0
  5. */
  6. goog.provide('shaka.hls.HlsParser');
  7. goog.require('goog.Uri');
  8. goog.require('goog.asserts');
  9. goog.require('shaka.abr.Ewma');
  10. goog.require('shaka.hls.ManifestTextParser');
  11. goog.require('shaka.hls.Playlist');
  12. goog.require('shaka.hls.PlaylistType');
  13. goog.require('shaka.hls.Tag');
  14. goog.require('shaka.hls.Utils');
  15. goog.require('shaka.log');
  16. goog.require('shaka.media.InitSegmentReference');
  17. goog.require('shaka.media.ManifestParser');
  18. goog.require('shaka.media.PresentationTimeline');
  19. goog.require('shaka.media.QualityObserver');
  20. goog.require('shaka.media.SegmentIndex');
  21. goog.require('shaka.media.SegmentReference');
  22. goog.require('shaka.net.DataUriPlugin');
  23. goog.require('shaka.net.NetworkingEngine');
  24. goog.require('shaka.net.NetworkingEngine.PendingRequest');
  25. goog.require('shaka.util.ArrayUtils');
  26. goog.require('shaka.util.BufferUtils');
  27. goog.require('shaka.util.DrmUtils');
  28. goog.require('shaka.util.ContentSteeringManager');
  29. goog.require('shaka.util.Error');
  30. goog.require('shaka.util.EventManager');
  31. goog.require('shaka.util.FakeEvent');
  32. goog.require('shaka.util.LanguageUtils');
  33. goog.require('shaka.util.ManifestParserUtils');
  34. goog.require('shaka.util.MimeUtils');
  35. goog.require('shaka.util.Networking');
  36. goog.require('shaka.util.OperationManager');
  37. goog.require('shaka.util.Pssh');
  38. goog.require('shaka.media.SegmentUtils');
  39. goog.require('shaka.util.Timer');
  40. goog.require('shaka.util.TsParser');
  41. goog.require('shaka.util.TXml');
  42. goog.require('shaka.util.Platform');
  43. goog.require('shaka.util.StreamUtils');
  44. goog.require('shaka.util.Uint8ArrayUtils');
  45. goog.requireType('shaka.hls.Segment');
  46. /**
  47. * HLS parser.
  48. *
  49. * @implements {shaka.extern.ManifestParser}
  50. * @export
  51. */
  52. shaka.hls.HlsParser = class {
  53. /**
  54. * Creates an Hls Parser object.
  55. */
  56. constructor() {
  57. /** @private {?shaka.extern.ManifestParser.PlayerInterface} */
  58. this.playerInterface_ = null;
  59. /** @private {?shaka.extern.ManifestConfiguration} */
  60. this.config_ = null;
  61. /** @private {number} */
  62. this.globalId_ = 1;
  63. /** @private {!Map.<string, string>} */
  64. this.globalVariables_ = new Map();
  65. /**
  66. * A map from group id to stream infos created from the media tags.
  67. * @private {!Map.<string, !Array.<?shaka.hls.HlsParser.StreamInfo>>}
  68. */
  69. this.groupIdToStreamInfosMap_ = new Map();
  70. /**
  71. * For media playlist lazy-loading to work in livestreams, we have to assume
  72. * that each stream of a type (video, audio, etc) has the same mappings of
  73. * sequence number to start time.
  74. * This map stores those relationships.
  75. * Only used during livestreams; we do not assume that VOD content is
  76. * aligned in that way.
  77. * @private {!Map.<string, !Map.<number, number>>}
  78. */
  79. this.mediaSequenceToStartTimeByType_ = new Map();
  80. // Set initial maps.
  81. const ContentType = shaka.util.ManifestParserUtils.ContentType;
  82. this.mediaSequenceToStartTimeByType_.set(ContentType.VIDEO, new Map());
  83. this.mediaSequenceToStartTimeByType_.set(ContentType.AUDIO, new Map());
  84. this.mediaSequenceToStartTimeByType_.set(ContentType.TEXT, new Map());
  85. this.mediaSequenceToStartTimeByType_.set(ContentType.IMAGE, new Map());
  86. /**
  87. * The values are strings of the form "<VIDEO URI> - <AUDIO URI>",
  88. * where the URIs are the verbatim media playlist URIs as they appeared in
  89. * the master playlist.
  90. *
  91. * Used to avoid duplicates that vary only in their text stream.
  92. *
  93. * @private {!Set.<string>}
  94. */
  95. this.variantUriSet_ = new Set();
  96. /**
  97. * A map from (verbatim) media playlist URI to stream infos representing the
  98. * playlists.
  99. *
  100. * On update, used to iterate through and update from media playlists.
  101. *
  102. * On initial parse, used to iterate through and determine minimum
  103. * timestamps, offsets, and to handle TS rollover.
  104. *
  105. * During parsing, used to avoid duplicates in the async methods
  106. * createStreamInfoFromMediaTags_, createStreamInfoFromImageTag_ and
  107. * createStreamInfoFromVariantTags_.
  108. *
  109. * @private {!Map.<string, shaka.hls.HlsParser.StreamInfo>}
  110. */
  111. this.uriToStreamInfosMap_ = new Map();
  112. /** @private {?shaka.media.PresentationTimeline} */
  113. this.presentationTimeline_ = null;
  114. /**
  115. * The master playlist URI, after redirects.
  116. *
  117. * @private {string}
  118. */
  119. this.masterPlaylistUri_ = '';
  120. /** @private {shaka.hls.ManifestTextParser} */
  121. this.manifestTextParser_ = new shaka.hls.ManifestTextParser();
  122. /**
  123. * The minimum sequence number for generated segments, when ignoring
  124. * EXT-X-PROGRAM-DATE-TIME.
  125. *
  126. * @private {number}
  127. */
  128. this.minSequenceNumber_ = -1;
  129. /**
  130. * The lowest time value for any of the streams, as defined by the
  131. * EXT-X-PROGRAM-DATE-TIME value. Measured in seconds since January 1, 1970.
  132. *
  133. * @private {number}
  134. */
  135. this.lowestSyncTime_ = Infinity;
  136. /**
  137. * Flag to indicate if any of the media playlists use
  138. * EXT-X-PROGRAM-DATE-TIME.
  139. *
  140. * @private {boolean}
  141. */
  142. this.usesProgramDateTime_ = false;
  143. /**
  144. * Whether the streams have previously been "finalized"; that is to say,
  145. * whether we have loaded enough streams to know information about the asset
  146. * such as timing information, live status, etc.
  147. *
  148. * @private {boolean}
  149. */
  150. this.streamsFinalized_ = false;
  151. /**
  152. * Whether the manifest informs about the codec to use.
  153. *
  154. * @private
  155. */
  156. this.codecInfoInManifest_ = false;
  157. /**
  158. * This timer is used to trigger the start of a manifest update. A manifest
  159. * update is async. Once the update is finished, the timer will be restarted
  160. * to trigger the next update. The timer will only be started if the content
  161. * is live content.
  162. *
  163. * @private {shaka.util.Timer}
  164. */
  165. this.updatePlaylistTimer_ = new shaka.util.Timer(() => {
  166. if (this.mediaElement_ && !this.config_.continueLoadingWhenPaused) {
  167. this.eventManager_.unlisten(this.mediaElement_, 'timeupdate');
  168. if (this.mediaElement_.paused) {
  169. this.eventManager_.listenOnce(
  170. this.mediaElement_, 'timeupdate', () => this.onUpdate_());
  171. return;
  172. }
  173. }
  174. this.onUpdate_();
  175. });
  176. /** @private {shaka.hls.HlsParser.PresentationType_} */
  177. this.presentationType_ = shaka.hls.HlsParser.PresentationType_.VOD;
  178. /** @private {?shaka.extern.Manifest} */
  179. this.manifest_ = null;
  180. /** @private {number} */
  181. this.maxTargetDuration_ = 0;
  182. /** @private {number} */
  183. this.lastTargetDuration_ = Infinity;
  184. /** Partial segments target duration.
  185. * @private {number}
  186. */
  187. this.partialTargetDuration_ = 0;
  188. /** @private {number} */
  189. this.presentationDelay_ = 0;
  190. /** @private {number} */
  191. this.lowLatencyPresentationDelay_ = 0;
  192. /** @private {shaka.util.OperationManager} */
  193. this.operationManager_ = new shaka.util.OperationManager();
  194. /** A map from closed captions' group id, to a map of closed captions info.
  195. * {group id -> {closed captions channel id -> language}}
  196. * @private {Map.<string, Map.<string, string>>}
  197. */
  198. this.groupIdToClosedCaptionsMap_ = new Map();
  199. /** @private {Map.<string, string>} */
  200. this.groupIdToCodecsMap_ = new Map();
  201. /** A cache mapping EXT-X-MAP tag info to the InitSegmentReference created
  202. * from the tag.
  203. * The key is a string combining the EXT-X-MAP tag's absolute uri, and
  204. * its BYTERANGE if available.
  205. * {!Map.<string, !shaka.media.InitSegmentReference>} */
  206. this.mapTagToInitSegmentRefMap_ = new Map();
  207. /** @private {Map.<string, !shaka.extern.aesKey>} */
  208. this.aesKeyInfoMap_ = new Map();
  209. /** @private {Map.<string, !Promise.<shaka.extern.Response>>} */
  210. this.aesKeyMap_ = new Map();
  211. /** @private {Map.<string, !Promise.<shaka.extern.Response>>} */
  212. this.identityKeyMap_ = new Map();
  213. /** @private {Map.<!shaka.media.InitSegmentReference, ?string>} */
  214. this.identityKidMap_ = new Map();
  215. /** @private {boolean} */
  216. this.lowLatencyMode_ = false;
  217. /** @private {boolean} */
  218. this.lowLatencyByterangeOptimization_ = false;
  219. /**
  220. * An ewma that tracks how long updates take.
  221. * This is to mitigate issues caused by slow parsing on embedded devices.
  222. * @private {!shaka.abr.Ewma}
  223. */
  224. this.averageUpdateDuration_ = new shaka.abr.Ewma(5);
  225. /** @private {?shaka.util.ContentSteeringManager} */
  226. this.contentSteeringManager_ = null;
  227. /** @private {boolean} */
  228. this.needsClosedCaptionsDetection_ = true;
  229. /** @private {Set.<string>} */
  230. this.dateRangeIdsEmitted_ = new Set();
  231. /** @private {shaka.util.EventManager} */
  232. this.eventManager_ = new shaka.util.EventManager();
  233. /** @private {HTMLMediaElement} */
  234. this.mediaElement_ = null;
  235. /** @private {?number} */
  236. this.startTime_ = null;
  237. /** @private {function():boolean} */
  238. this.isPreloadFn_ = () => false;
  239. }
  240. /**
  241. * @param {shaka.extern.ManifestConfiguration} config
  242. * @param {(function():boolean)=} isPreloadFn
  243. * @override
  244. * @exportInterface
  245. */
  246. configure(config, isPreloadFn) {
  247. this.config_ = config;
  248. if (isPreloadFn) {
  249. this.isPreloadFn_ = isPreloadFn;
  250. }
  251. if (this.contentSteeringManager_) {
  252. this.contentSteeringManager_.configure(this.config_);
  253. }
  254. }
  255. /**
  256. * @override
  257. * @exportInterface
  258. */
  259. async start(uri, playerInterface) {
  260. goog.asserts.assert(this.config_, 'Must call configure() before start()!');
  261. this.playerInterface_ = playerInterface;
  262. this.lowLatencyMode_ = playerInterface.isLowLatencyMode();
  263. const response = await this.requestManifest_([uri]).promise;
  264. // Record the master playlist URI after redirects.
  265. this.masterPlaylistUri_ = response.uri;
  266. goog.asserts.assert(response.data, 'Response data should be non-null!');
  267. await this.parseManifest_(response.data, uri);
  268. goog.asserts.assert(this.manifest_, 'Manifest should be non-null');
  269. return this.manifest_;
  270. }
  271. /**
  272. * @override
  273. * @exportInterface
  274. */
  275. stop() {
  276. // Make sure we don't update the manifest again. Even if the timer is not
  277. // running, this is safe to call.
  278. if (this.updatePlaylistTimer_) {
  279. this.updatePlaylistTimer_.stop();
  280. this.updatePlaylistTimer_ = null;
  281. }
  282. /** @type {!Array.<!Promise>} */
  283. const pending = [];
  284. if (this.operationManager_) {
  285. pending.push(this.operationManager_.destroy());
  286. this.operationManager_ = null;
  287. }
  288. this.playerInterface_ = null;
  289. this.config_ = null;
  290. this.variantUriSet_.clear();
  291. this.manifest_ = null;
  292. this.uriToStreamInfosMap_.clear();
  293. this.groupIdToStreamInfosMap_.clear();
  294. this.groupIdToCodecsMap_.clear();
  295. this.globalVariables_.clear();
  296. this.mapTagToInitSegmentRefMap_.clear();
  297. this.aesKeyInfoMap_.clear();
  298. this.aesKeyMap_.clear();
  299. this.identityKeyMap_.clear();
  300. this.identityKidMap_.clear();
  301. this.dateRangeIdsEmitted_.clear();
  302. if (this.contentSteeringManager_) {
  303. this.contentSteeringManager_.destroy();
  304. }
  305. if (this.eventManager_) {
  306. this.eventManager_.release();
  307. this.eventManager_ = null;
  308. }
  309. return Promise.all(pending);
  310. }
  311. /**
  312. * @override
  313. * @exportInterface
  314. */
  315. async update() {
  316. if (!this.isLive_()) {
  317. return;
  318. }
  319. /** @type {!Array.<!Promise>} */
  320. const updates = [];
  321. const streamInfos = Array.from(this.uriToStreamInfosMap_.values());
  322. // This is necessary to calculate correctly the update time.
  323. this.lastTargetDuration_ = Infinity;
  324. this.manifest_.gapCount = 0;
  325. // Only update active streams.
  326. const activeStreamInfos = streamInfos.filter((s) => s.stream.segmentIndex);
  327. for (const streamInfo of activeStreamInfos) {
  328. updates.push(this.updateStream_(streamInfo));
  329. }
  330. await Promise.all(updates);
  331. // Now that streams have been updated, notify the presentation timeline.
  332. this.notifySegmentsForStreams_(activeStreamInfos.map((s) => s.stream));
  333. // If any hasEndList is false, the stream is still live.
  334. const stillLive = activeStreamInfos.some((s) => s.hasEndList == false);
  335. if (activeStreamInfos.length && !stillLive) {
  336. // Convert the presentation to VOD and set the duration.
  337. const PresentationType = shaka.hls.HlsParser.PresentationType_;
  338. this.setPresentationType_(PresentationType.VOD);
  339. // The duration is the minimum of the end times of all active streams.
  340. // Non-active streams are not guaranteed to have useful maxTimestamp
  341. // values, due to the lazy-loading system, so they are ignored.
  342. const maxTimestamps = activeStreamInfos.map((s) => s.maxTimestamp);
  343. // The duration is the minimum of the end times of all streams.
  344. this.presentationTimeline_.setDuration(Math.min(...maxTimestamps));
  345. this.playerInterface_.updateDuration();
  346. }
  347. if (stillLive) {
  348. this.determineDuration_();
  349. }
  350. // Check if any playlist does not have the first reference (due to a
  351. // problem in the live encoder for example), and disable the stream if
  352. // necessary.
  353. for (const streamInfo of activeStreamInfos) {
  354. if (streamInfo.stream.segmentIndex &&
  355. !streamInfo.stream.segmentIndex.earliestReference()) {
  356. this.playerInterface_.disableStream(streamInfo.stream);
  357. }
  358. }
  359. }
  360. /**
  361. * @param {!shaka.hls.HlsParser.StreamInfo} streamInfo
  362. * @return {!Map.<number, number>}
  363. * @private
  364. */
  365. getMediaSequenceToStartTimeFor_(streamInfo) {
  366. if (this.isLive_()) {
  367. return this.mediaSequenceToStartTimeByType_.get(streamInfo.type);
  368. } else {
  369. return streamInfo.mediaSequenceToStartTime;
  370. }
  371. }
  372. /**
  373. * Updates a stream.
  374. *
  375. * @param {!shaka.hls.HlsParser.StreamInfo} streamInfo
  376. * @return {!Promise}
  377. * @private
  378. */
  379. async updateStream_(streamInfo) {
  380. const manifestUris = [];
  381. for (const uri of streamInfo.getUris()) {
  382. const uriObj = new goog.Uri(uri);
  383. const queryData = uriObj.getQueryData();
  384. if (streamInfo.canBlockReload) {
  385. if (streamInfo.nextMediaSequence >= 0) {
  386. // Indicates that the server must hold the request until a Playlist
  387. // contains a Media Segment with Media Sequence
  388. queryData.add('_HLS_msn', String(streamInfo.nextMediaSequence));
  389. }
  390. if (streamInfo.nextPart >= 0) {
  391. // Indicates, in combination with _HLS_msn, that the server must hold
  392. // the request until a Playlist contains Partial Segment N of Media
  393. // Sequence Number M or later.
  394. queryData.add('_HLS_part', String(streamInfo.nextPart));
  395. }
  396. }
  397. if (streamInfo.canSkipSegments) {
  398. // Enable delta updates. This will replace older segments with
  399. // 'EXT-X-SKIP' tag in the media playlist.
  400. queryData.add('_HLS_skip', 'YES');
  401. }
  402. if (queryData.getCount()) {
  403. uriObj.setQueryData(queryData);
  404. }
  405. manifestUris.push(uriObj.toString());
  406. }
  407. let response;
  408. try {
  409. response = await this.requestManifest_(
  410. manifestUris, /* isPlaylist= */ true).promise;
  411. } catch (e) {
  412. if (this.playerInterface_) {
  413. this.playerInterface_.disableStream(streamInfo.stream);
  414. }
  415. throw e;
  416. }
  417. if (!streamInfo.stream.segmentIndex) {
  418. // The stream was closed since the update was first requested.
  419. return;
  420. }
  421. /** @type {shaka.hls.Playlist} */
  422. const playlist = this.manifestTextParser_.parsePlaylist(response.data);
  423. if (playlist.type != shaka.hls.PlaylistType.MEDIA) {
  424. throw new shaka.util.Error(
  425. shaka.util.Error.Severity.CRITICAL,
  426. shaka.util.Error.Category.MANIFEST,
  427. shaka.util.Error.Code.HLS_INVALID_PLAYLIST_HIERARCHY);
  428. }
  429. // Record the final URI after redirects.
  430. const responseUri = response.uri;
  431. if (responseUri != response.originalUri &&
  432. !streamInfo.getUris().includes(responseUri)) {
  433. streamInfo.redirectUris.push(responseUri);
  434. }
  435. /** @type {!Array.<!shaka.hls.Tag>} */
  436. const variablesTags = shaka.hls.Utils.filterTagsByName(playlist.tags,
  437. 'EXT-X-DEFINE');
  438. const mediaVariables = this.parseMediaVariables_(
  439. variablesTags, responseUri);
  440. const stream = streamInfo.stream;
  441. const mediaSequenceToStartTime =
  442. this.getMediaSequenceToStartTimeFor_(streamInfo);
  443. const {keyIds, drmInfos} = await this.parseDrmInfo_(
  444. playlist, stream.mimeType, streamInfo.getUris, mediaVariables);
  445. const keysAreEqual =
  446. (a, b) => a.size === b.size && [...a].every((value) => b.has(value));
  447. if (!keysAreEqual(stream.keyIds, keyIds)) {
  448. stream.keyIds = keyIds;
  449. stream.drmInfos = drmInfos;
  450. this.playerInterface_.newDrmInfo(stream);
  451. }
  452. const {segments, bandwidth} = this.createSegments_(
  453. playlist, mediaSequenceToStartTime, mediaVariables,
  454. streamInfo.getUris, streamInfo.type);
  455. if (bandwidth) {
  456. stream.bandwidth = bandwidth;
  457. }
  458. const qualityInfo =
  459. shaka.media.QualityObserver.createQualityInfo(stream);
  460. for (const segment of segments) {
  461. if (segment.initSegmentReference) {
  462. segment.initSegmentReference.mediaQuality = qualityInfo;
  463. }
  464. }
  465. stream.segmentIndex.mergeAndEvict(
  466. segments, this.presentationTimeline_.getSegmentAvailabilityStart());
  467. if (segments.length) {
  468. const mediaSequenceNumber = shaka.hls.Utils.getFirstTagWithNameAsNumber(
  469. playlist.tags, 'EXT-X-MEDIA-SEQUENCE', 0);
  470. const skipTag = shaka.hls.Utils.getFirstTagWithName(
  471. playlist.tags, 'EXT-X-SKIP');
  472. const skippedSegments =
  473. skipTag ? Number(skipTag.getAttributeValue('SKIPPED-SEGMENTS')) : 0;
  474. const {nextMediaSequence, nextPart} =
  475. this.getNextMediaSequenceAndPart_(mediaSequenceNumber, segments);
  476. streamInfo.nextMediaSequence = nextMediaSequence + skippedSegments;
  477. streamInfo.nextPart = nextPart;
  478. const playlistStartTime = mediaSequenceToStartTime.get(
  479. mediaSequenceNumber);
  480. stream.segmentIndex.evict(playlistStartTime);
  481. }
  482. const oldSegment = stream.segmentIndex.earliestReference();
  483. if (oldSegment) {
  484. streamInfo.minTimestamp = oldSegment.startTime;
  485. const newestSegment = segments[segments.length - 1];
  486. goog.asserts.assert(newestSegment, 'Should have segments!');
  487. streamInfo.maxTimestamp = newestSegment.endTime;
  488. }
  489. // Once the last segment has been added to the playlist,
  490. // #EXT-X-ENDLIST tag will be appended.
  491. // If that happened, treat the rest of the EVENT presentation as VOD.
  492. const endListTag =
  493. shaka.hls.Utils.getFirstTagWithName(playlist.tags, 'EXT-X-ENDLIST');
  494. if (endListTag) {
  495. // Flag this for later. We don't convert the whole presentation into VOD
  496. // until we've seen the ENDLIST tag for all active playlists.
  497. streamInfo.hasEndList = true;
  498. }
  499. this.determineLastTargetDuration_(playlist);
  500. this.processDateRangeTags_(
  501. playlist.tags, stream.type, mediaVariables, streamInfo.getUris);
  502. }
  503. /**
  504. * @override
  505. * @exportInterface
  506. */
  507. onExpirationUpdated(sessionId, expiration) {
  508. // No-op
  509. }
  510. /**
  511. * @override
  512. * @exportInterface
  513. */
  514. onInitialVariantChosen(variant) {
  515. // No-op
  516. }
  517. /**
  518. * @override
  519. * @exportInterface
  520. */
  521. banLocation(uri) {
  522. if (this.contentSteeringManager_) {
  523. this.contentSteeringManager_.banLocation(uri);
  524. }
  525. }
  526. /**
  527. * @override
  528. * @exportInterface
  529. */
  530. setMediaElement(mediaElement) {
  531. this.mediaElement_ = mediaElement;
  532. }
  533. /**
  534. * Align the streams by sequence number by dropping early segments. Then
  535. * offset the streams to begin at presentation time 0.
  536. * @param {!Array.<!shaka.hls.HlsParser.StreamInfo>} streamInfos
  537. * @param {boolean=} force
  538. * @private
  539. */
  540. syncStreamsWithSequenceNumber_(streamInfos, force = false) {
  541. // We assume that, when this is first called, we have enough info to
  542. // determine how to use the program date times (e.g. we have both a video
  543. // and an audio, and all other videos and audios match those).
  544. // Thus, we only need to calculate this once.
  545. const updateMinSequenceNumber = this.minSequenceNumber_ == -1;
  546. // Sync using media sequence number. Find the highest starting sequence
  547. // number among all streams. Later, we will drop any references to
  548. // earlier segments in other streams, then offset everything back to 0.
  549. for (const streamInfo of streamInfos) {
  550. const segmentIndex = streamInfo.stream.segmentIndex;
  551. goog.asserts.assert(segmentIndex,
  552. 'Only loaded streams should be synced');
  553. const mediaSequenceToStartTime =
  554. this.getMediaSequenceToStartTimeFor_(streamInfo);
  555. const segment0 = segmentIndex.earliestReference();
  556. if (segment0) {
  557. // This looks inefficient, but iteration order is insertion order.
  558. // So the very first entry should be the one we want.
  559. // We assert that this holds true so that we are alerted by debug
  560. // builds and tests if it changes. We still do a loop, though, so
  561. // that the code functions correctly in production no matter what.
  562. if (goog.DEBUG) {
  563. const firstSequenceStartTime =
  564. mediaSequenceToStartTime.values().next().value;
  565. if (firstSequenceStartTime != segment0.startTime) {
  566. shaka.log.warning(
  567. 'Sequence number map is not ordered as expected!');
  568. }
  569. }
  570. for (const [sequence, start] of mediaSequenceToStartTime) {
  571. if (start == segment0.startTime) {
  572. if (updateMinSequenceNumber) {
  573. this.minSequenceNumber_ = Math.max(
  574. this.minSequenceNumber_, sequence);
  575. }
  576. // Even if we already have decided on a value for
  577. // |this.minSequenceNumber_|, we still need to determine the first
  578. // sequence number for the stream, to offset it in the code below.
  579. streamInfo.firstSequenceNumber = sequence;
  580. break;
  581. }
  582. }
  583. }
  584. }
  585. if (this.minSequenceNumber_ < 0) {
  586. // Nothing to sync.
  587. return;
  588. }
  589. shaka.log.debug('Syncing HLS streams against base sequence number:',
  590. this.minSequenceNumber_);
  591. for (const streamInfo of streamInfos) {
  592. if (!this.ignoreManifestProgramDateTimeFor_(streamInfo.type) && !force) {
  593. continue;
  594. }
  595. const segmentIndex = streamInfo.stream.segmentIndex;
  596. if (segmentIndex) {
  597. // Drop any earlier references.
  598. const numSegmentsToDrop =
  599. this.minSequenceNumber_ - streamInfo.firstSequenceNumber;
  600. if (numSegmentsToDrop > 0) {
  601. segmentIndex.dropFirstReferences(numSegmentsToDrop);
  602. // Now adjust timestamps back to begin at 0.
  603. const segmentN = segmentIndex.earliestReference();
  604. if (segmentN) {
  605. const streamOffset = -segmentN.startTime;
  606. // Modify all SegmentReferences equally.
  607. streamInfo.stream.segmentIndex.offset(streamOffset);
  608. // Update other parts of streamInfo the same way.
  609. this.offsetStreamInfo_(streamInfo, streamOffset);
  610. }
  611. }
  612. }
  613. }
  614. }
  615. /**
  616. * Synchronize streams by the EXT-X-PROGRAM-DATE-TIME tags attached to their
  617. * segments. Also normalizes segment times so that the earliest segment in
  618. * any stream is at time 0.
  619. * @param {!Array.<!shaka.hls.HlsParser.StreamInfo>} streamInfos
  620. * @private
  621. */
  622. syncStreamsWithProgramDateTime_(streamInfos) {
  623. // We assume that, when this is first called, we have enough info to
  624. // determine how to use the program date times (e.g. we have both a video
  625. // and an audio, and all other videos and audios match those).
  626. // Thus, we only need to calculate this once.
  627. if (this.lowestSyncTime_ == Infinity) {
  628. for (const streamInfo of streamInfos) {
  629. const segmentIndex = streamInfo.stream.segmentIndex;
  630. goog.asserts.assert(segmentIndex,
  631. 'Only loaded streams should be synced');
  632. const segment0 = segmentIndex.earliestReference();
  633. if (segment0 != null && segment0.syncTime != null) {
  634. this.lowestSyncTime_ =
  635. Math.min(this.lowestSyncTime_, segment0.syncTime);
  636. }
  637. }
  638. }
  639. const lowestSyncTime = this.lowestSyncTime_;
  640. if (lowestSyncTime == Infinity) {
  641. // Nothing to sync.
  642. return;
  643. }
  644. shaka.log.debug('Syncing HLS streams against base time:', lowestSyncTime);
  645. for (const streamInfo of this.uriToStreamInfosMap_.values()) {
  646. if (this.ignoreManifestProgramDateTimeFor_(streamInfo.type)) {
  647. continue;
  648. }
  649. const segmentIndex = streamInfo.stream.segmentIndex;
  650. if (segmentIndex != null) {
  651. // A segment's startTime should be based on its syncTime vs the lowest
  652. // syncTime across all streams. The earliest segment sync time from
  653. // any stream will become presentation time 0. If two streams start
  654. // e.g. 6 seconds apart in syncTime, then their first segments will
  655. // also start 6 seconds apart in presentation time.
  656. const segment0 = segmentIndex.earliestReference();
  657. if (!segment0) {
  658. continue;
  659. }
  660. if (segment0.syncTime == null) {
  661. shaka.log.alwaysError('Missing EXT-X-PROGRAM-DATE-TIME for stream',
  662. streamInfo.getUris(),
  663. 'Expect AV sync issues!');
  664. } else {
  665. // Stream metadata are offset by a fixed amount based on the
  666. // first segment.
  667. const segment0TargetTime = segment0.syncTime - lowestSyncTime;
  668. const streamOffset = segment0TargetTime - segment0.startTime;
  669. this.offsetStreamInfo_(streamInfo, streamOffset);
  670. // This is computed across all segments separately to manage
  671. // accumulated drift in durations.
  672. for (const segment of segmentIndex) {
  673. segment.syncAgainst(lowestSyncTime);
  674. }
  675. }
  676. }
  677. }
  678. }
  679. /**
  680. * @param {!shaka.hls.HlsParser.StreamInfo} streamInfo
  681. * @param {number} offset
  682. * @private
  683. */
  684. offsetStreamInfo_(streamInfo, offset) {
  685. // Adjust our accounting of the minimum timestamp.
  686. streamInfo.minTimestamp += offset;
  687. // Adjust our accounting of the maximum timestamp.
  688. streamInfo.maxTimestamp += offset;
  689. goog.asserts.assert(streamInfo.maxTimestamp >= 0,
  690. 'Negative maxTimestamp after adjustment!');
  691. // Update our map from sequence number to start time.
  692. const mediaSequenceToStartTime =
  693. this.getMediaSequenceToStartTimeFor_(streamInfo);
  694. for (const [key, value] of mediaSequenceToStartTime) {
  695. mediaSequenceToStartTime.set(key, value + offset);
  696. }
  697. shaka.log.debug('Offset', offset, 'applied to',
  698. streamInfo.getUris());
  699. }
  700. /**
  701. * Parses the manifest.
  702. *
  703. * @param {BufferSource} data
  704. * @param {string} uri
  705. * @return {!Promise}
  706. * @private
  707. */
  708. async parseManifest_(data, uri) {
  709. const Utils = shaka.hls.Utils;
  710. const ContentType = shaka.util.ManifestParserUtils.ContentType;
  711. goog.asserts.assert(this.masterPlaylistUri_,
  712. 'Master playlist URI must be set before calling parseManifest_!');
  713. const playlist = this.manifestTextParser_.parsePlaylist(data);
  714. /** @type {!Array.<!shaka.hls.Tag>} */
  715. const variablesTags = Utils.filterTagsByName(playlist.tags, 'EXT-X-DEFINE');
  716. /** @type {!Array.<!shaka.extern.Variant>} */
  717. let variants = [];
  718. /** @type {!Array.<!shaka.extern.Stream>} */
  719. let textStreams = [];
  720. /** @type {!Array.<!shaka.extern.Stream>} */
  721. let imageStreams = [];
  722. // This assert is our own sanity check.
  723. goog.asserts.assert(this.presentationTimeline_ == null,
  724. 'Presentation timeline created early!');
  725. // We don't know if the presentation is VOD or live until we parse at least
  726. // one media playlist, so make a VOD-style presentation timeline for now
  727. // and change the type later if we discover this is live.
  728. // Since the player will load the first variant chosen early in the process,
  729. // there isn't a window during playback where the live-ness is unknown.
  730. this.presentationTimeline_ = new shaka.media.PresentationTimeline(
  731. /* presentationStartTime= */ null, /* delay= */ 0);
  732. this.presentationTimeline_.setStatic(true);
  733. const getUris = () => {
  734. return [uri];
  735. };
  736. /** @type {?string} */
  737. let mediaPlaylistType = null;
  738. /** @type {!Map.<string, string>} */
  739. let mediaVariables = new Map();
  740. // Parsing a media playlist results in a single-variant stream.
  741. if (playlist.type == shaka.hls.PlaylistType.MEDIA) {
  742. this.needsClosedCaptionsDetection_ = false;
  743. /** @type {!Array.<!shaka.hls.Tag>} */
  744. const variablesTags = shaka.hls.Utils.filterTagsByName(playlist.tags,
  745. 'EXT-X-DEFINE');
  746. mediaVariables = this.parseMediaVariables_(
  747. variablesTags, this.masterPlaylistUri_);
  748. // By default we assume it is video, but in a later step the correct type
  749. // is obtained.
  750. mediaPlaylistType = ContentType.VIDEO;
  751. // These values can be obtained later so these default values are good.
  752. const codecs = '';
  753. const languageValue = '';
  754. const channelsCount = null;
  755. const sampleRate = null;
  756. const closedCaptions = new Map();
  757. const spatialAudio = false;
  758. const characteristics = null;
  759. const forced = false; // Only relevant for text.
  760. const primary = true; // This is the only stream!
  761. const name = 'Media Playlist';
  762. // Make the stream info, with those values.
  763. const streamInfo = await this.convertParsedPlaylistIntoStreamInfo_(
  764. this.globalId_++, mediaVariables, playlist, getUris, uri, codecs,
  765. mediaPlaylistType, languageValue, primary, name, channelsCount,
  766. closedCaptions, characteristics, forced, sampleRate, spatialAudio);
  767. this.uriToStreamInfosMap_.set(uri, streamInfo);
  768. if (streamInfo.stream) {
  769. const qualityInfo =
  770. shaka.media.QualityObserver.createQualityInfo(streamInfo.stream);
  771. streamInfo.stream.segmentIndex.forEachTopLevelReference(
  772. (reference) => {
  773. if (reference.initSegmentReference) {
  774. reference.initSegmentReference.mediaQuality = qualityInfo;
  775. }
  776. });
  777. }
  778. mediaPlaylistType = streamInfo.stream.type;
  779. // Wrap the stream from that stream info with a variant.
  780. variants.push({
  781. id: 0,
  782. language: this.getLanguage_(languageValue),
  783. disabledUntilTime: 0,
  784. primary: true,
  785. audio: mediaPlaylistType == 'audio' ? streamInfo.stream : null,
  786. video: mediaPlaylistType == 'video' ? streamInfo.stream : null,
  787. bandwidth: streamInfo.stream.bandwidth || 0,
  788. allowedByApplication: true,
  789. allowedByKeySystem: true,
  790. decodingInfos: [],
  791. });
  792. } else {
  793. this.parseMasterVariables_(variablesTags);
  794. /** @type {!Array.<!shaka.hls.Tag>} */
  795. const mediaTags = Utils.filterTagsByName(
  796. playlist.tags, 'EXT-X-MEDIA');
  797. /** @type {!Array.<!shaka.hls.Tag>} */
  798. const variantTags = Utils.filterTagsByName(
  799. playlist.tags, 'EXT-X-STREAM-INF');
  800. /** @type {!Array.<!shaka.hls.Tag>} */
  801. const imageTags = Utils.filterTagsByName(
  802. playlist.tags, 'EXT-X-IMAGE-STREAM-INF');
  803. /** @type {!Array.<!shaka.hls.Tag>} */
  804. const iFrameTags = Utils.filterTagsByName(
  805. playlist.tags, 'EXT-X-I-FRAME-STREAM-INF');
  806. /** @type {!Array.<!shaka.hls.Tag>} */
  807. const sessionKeyTags = Utils.filterTagsByName(
  808. playlist.tags, 'EXT-X-SESSION-KEY');
  809. /** @type {!Array.<!shaka.hls.Tag>} */
  810. const sessionDataTags = Utils.filterTagsByName(
  811. playlist.tags, 'EXT-X-SESSION-DATA');
  812. /** @type {!Array.<!shaka.hls.Tag>} */
  813. const contentSteeringTags = Utils.filterTagsByName(
  814. playlist.tags, 'EXT-X-CONTENT-STEERING');
  815. this.processSessionData_(sessionDataTags);
  816. await this.processContentSteering_(contentSteeringTags);
  817. this.parseCodecs_(variantTags);
  818. this.parseClosedCaptions_(mediaTags);
  819. const iFrameStreams = this.parseIFrames_(iFrameTags);
  820. variants = await this.createVariantsForTags_(
  821. variantTags, sessionKeyTags, mediaTags, getUris,
  822. this.globalVariables_, iFrameStreams);
  823. textStreams = this.parseTexts_(mediaTags);
  824. imageStreams = await this.parseImages_(imageTags, iFrameTags);
  825. }
  826. // Make sure that the parser has not been destroyed.
  827. if (!this.playerInterface_) {
  828. throw new shaka.util.Error(
  829. shaka.util.Error.Severity.CRITICAL,
  830. shaka.util.Error.Category.PLAYER,
  831. shaka.util.Error.Code.OPERATION_ABORTED);
  832. }
  833. this.determineStartTime_(playlist);
  834. // Single-variant streams aren't lazy-loaded, so for them we already have
  835. // enough info here to determine the presentation type and duration.
  836. if (playlist.type == shaka.hls.PlaylistType.MEDIA) {
  837. if (this.isLive_()) {
  838. this.changePresentationTimelineToLive_(playlist);
  839. const delay = this.getUpdatePlaylistDelay_();
  840. this.updatePlaylistTimer_.tickAfter(/* seconds= */ delay);
  841. }
  842. const streamInfos = Array.from(this.uriToStreamInfosMap_.values());
  843. this.finalizeStreams_(streamInfos);
  844. this.determineDuration_();
  845. goog.asserts.assert(mediaPlaylistType,
  846. 'mediaPlaylistType should be non-null');
  847. this.processDateRangeTags_(
  848. playlist.tags, mediaPlaylistType, mediaVariables, getUris);
  849. }
  850. this.manifest_ = {
  851. presentationTimeline: this.presentationTimeline_,
  852. variants,
  853. textStreams,
  854. imageStreams,
  855. offlineSessionIds: [],
  856. minBufferTime: 0,
  857. sequenceMode: this.config_.hls.sequenceMode,
  858. ignoreManifestTimestampsInSegmentsMode:
  859. this.config_.hls.ignoreManifestTimestampsInSegmentsMode,
  860. type: shaka.media.ManifestParser.HLS,
  861. serviceDescription: null,
  862. nextUrl: null,
  863. periodCount: 1,
  864. gapCount: 0,
  865. isLowLatency: false,
  866. startTime: this.startTime_,
  867. };
  868. // If there is no 'CODECS' attribute in the manifest and codec guessing is
  869. // disabled, we need to create the segment indexes now so that missing info
  870. // can be parsed from the media data and added to the stream objects.
  871. if (!this.codecInfoInManifest_ && this.config_.hls.disableCodecGuessing) {
  872. const createIndexes = [];
  873. for (const variant of this.manifest_.variants) {
  874. if (variant.audio && variant.audio.codecs === '') {
  875. createIndexes.push(variant.audio.createSegmentIndex());
  876. }
  877. if (variant.video && variant.video.codecs === '') {
  878. createIndexes.push(variant.video.createSegmentIndex());
  879. }
  880. }
  881. await Promise.all(createIndexes);
  882. }
  883. this.playerInterface_.makeTextStreamsForClosedCaptions(this.manifest_);
  884. if (variants.length == 1) {
  885. const createSegmentIndexPromises = [];
  886. const variant = variants[0];
  887. for (const stream of [variant.video, variant.audio]) {
  888. if (stream && !stream.segmentIndex) {
  889. createSegmentIndexPromises.push(stream.createSegmentIndex());
  890. }
  891. }
  892. if (createSegmentIndexPromises.length > 0) {
  893. await Promise.all(createSegmentIndexPromises);
  894. }
  895. }
  896. }
  897. /**
  898. * @param {!Array.<!shaka.media.SegmentReference>} segments
  899. * @return {!Promise.<shaka.media.SegmentUtils.BasicInfo>}
  900. * @private
  901. */
  902. async getBasicInfoFromSegments_(segments) {
  903. const HlsParser = shaka.hls.HlsParser;
  904. const defaultBasicInfo = shaka.media.SegmentUtils.getBasicInfoFromMimeType(
  905. this.config_.hls.mediaPlaylistFullMimeType);
  906. if (!segments.length) {
  907. return defaultBasicInfo;
  908. }
  909. const {segment, segmentIndex} = this.getAvailableSegment_(segments);
  910. const segmentUris = segment.getUris();
  911. const segmentUri = segmentUris[0];
  912. const parsedUri = new goog.Uri(segmentUri);
  913. const extension = parsedUri.getPath().split('.').pop();
  914. const rawMimeType = HlsParser.RAW_FORMATS_TO_MIME_TYPES_[extension];
  915. if (rawMimeType) {
  916. return shaka.media.SegmentUtils.getBasicInfoFromMimeType(
  917. rawMimeType);
  918. }
  919. const requestType = shaka.net.NetworkingEngine.RequestType.SEGMENT;
  920. let initData = null;
  921. let initMimeType = null;
  922. const initSegmentRef = segment.initSegmentReference;
  923. if (initSegmentRef) {
  924. const initSegmentRequest = shaka.util.Networking.createSegmentRequest(
  925. initSegmentRef.getUris(), initSegmentRef.getStartByte(),
  926. initSegmentRef.getEndByte(), this.config_.retryParameters);
  927. const initType =
  928. shaka.net.NetworkingEngine.AdvancedRequestType.INIT_SEGMENT;
  929. const initResponse = await this.makeNetworkRequest_(
  930. initSegmentRequest, requestType, {type: initType}).promise;
  931. initData = initResponse.data;
  932. if (initSegmentRef.aesKey) {
  933. initData = await shaka.media.SegmentUtils.aesDecrypt(
  934. initData, initSegmentRef.aesKey, 0);
  935. }
  936. initMimeType = initResponse.headers['content-type'];
  937. if (initMimeType) {
  938. // Split the MIME type in case the server sent additional parameters.
  939. initMimeType = initMimeType.split(';')[0].toLowerCase();
  940. }
  941. }
  942. const segmentRequest = shaka.util.Networking.createSegmentRequest(
  943. segment.getUris(), segment.getStartByte(), segment.getEndByte(),
  944. this.config_.retryParameters);
  945. const type = shaka.net.NetworkingEngine.AdvancedRequestType.MEDIA_SEGMENT;
  946. const response = await this.makeNetworkRequest_(
  947. segmentRequest, requestType, {type}).promise;
  948. let data = response.data;
  949. if (segment.aesKey) {
  950. data = await shaka.media.SegmentUtils.aesDecrypt(
  951. data, segment.aesKey, segmentIndex);
  952. }
  953. let contentMimeType = response.headers['content-type'];
  954. if (contentMimeType) {
  955. // Split the MIME type in case the server sent additional parameters.
  956. contentMimeType = contentMimeType.split(';')[0].toLowerCase();
  957. }
  958. const validMp4Extensions = [
  959. 'mp4',
  960. 'mp4a',
  961. 'm4s',
  962. 'm4i',
  963. 'm4a',
  964. 'm4f',
  965. 'cmfa',
  966. 'mp4v',
  967. 'm4v',
  968. 'cmfv',
  969. 'fmp4',
  970. ];
  971. const validMp4MimeType = [
  972. 'audio/mp4',
  973. 'video/mp4',
  974. 'video/iso.segment',
  975. ];
  976. if (shaka.util.TsParser.probe(
  977. shaka.util.BufferUtils.toUint8(data))) {
  978. const basicInfo =
  979. shaka.media.SegmentUtils.getBasicInfoFromTs(data);
  980. if (basicInfo) {
  981. return basicInfo;
  982. }
  983. } else if (validMp4Extensions.includes(extension) ||
  984. validMp4MimeType.includes(contentMimeType) ||
  985. (initMimeType && validMp4MimeType.includes(initMimeType))) {
  986. const basicInfo = shaka.media.SegmentUtils.getBasicInfoFromMp4(
  987. initData, data);
  988. if (basicInfo) {
  989. return basicInfo;
  990. }
  991. }
  992. if (contentMimeType) {
  993. return shaka.media.SegmentUtils.getBasicInfoFromMimeType(
  994. contentMimeType);
  995. }
  996. if (initMimeType) {
  997. return shaka.media.SegmentUtils.getBasicInfoFromMimeType(
  998. initMimeType);
  999. }
  1000. return defaultBasicInfo;
  1001. }
  1002. /** @private */
  1003. determineDuration_() {
  1004. goog.asserts.assert(this.presentationTimeline_,
  1005. 'Presentation timeline not created!');
  1006. if (this.isLive_()) {
  1007. // The spec says nothing much about seeking in live content, but Safari's
  1008. // built-in HLS implementation does not allow it. Therefore we will set
  1009. // the availability window equal to the presentation delay. The player
  1010. // will be able to buffer ahead three segments, but the seek window will
  1011. // be zero-sized.
  1012. const PresentationType = shaka.hls.HlsParser.PresentationType_;
  1013. if (this.presentationType_ == PresentationType.LIVE) {
  1014. let segmentAvailabilityDuration = this.getLiveDuration_() || 0;
  1015. // The app can override that with a longer duration, to allow seeking.
  1016. if (!isNaN(this.config_.availabilityWindowOverride)) {
  1017. segmentAvailabilityDuration = this.config_.availabilityWindowOverride;
  1018. }
  1019. this.presentationTimeline_.setSegmentAvailabilityDuration(
  1020. segmentAvailabilityDuration);
  1021. }
  1022. } else {
  1023. // Use the minimum duration as the presentation duration.
  1024. this.presentationTimeline_.setDuration(this.getMinDuration_());
  1025. }
  1026. if (!this.presentationTimeline_.isStartTimeLocked()) {
  1027. for (const streamInfo of this.uriToStreamInfosMap_.values()) {
  1028. if (!streamInfo.stream.segmentIndex) {
  1029. continue; // Not active.
  1030. }
  1031. if (streamInfo.type != 'audio' && streamInfo.type != 'video') {
  1032. continue;
  1033. }
  1034. const firstReference =
  1035. streamInfo.stream.segmentIndex.earliestReference();
  1036. if (firstReference && firstReference.syncTime) {
  1037. const syncTime = firstReference.syncTime;
  1038. this.presentationTimeline_.setInitialProgramDateTime(syncTime);
  1039. }
  1040. }
  1041. }
  1042. // This is the first point where we have a meaningful presentation start
  1043. // time, and we need to tell PresentationTimeline that so that it can
  1044. // maintain consistency from here on.
  1045. this.presentationTimeline_.lockStartTime();
  1046. // This asserts that the live edge is being calculated from segment times.
  1047. // For VOD and event streams, this check should still pass.
  1048. goog.asserts.assert(
  1049. !this.presentationTimeline_.usingPresentationStartTime(),
  1050. 'We should not be using the presentation start time in HLS!');
  1051. }
  1052. /**
  1053. * Get the variables of each variant tag, and store in a map.
  1054. * @param {!Array.<!shaka.hls.Tag>} tags Variant tags from the playlist.
  1055. * @private
  1056. */
  1057. parseMasterVariables_(tags) {
  1058. const queryParams = new goog.Uri(this.masterPlaylistUri_).getQueryData();
  1059. for (const variableTag of tags) {
  1060. const name = variableTag.getAttributeValue('NAME');
  1061. const value = variableTag.getAttributeValue('VALUE');
  1062. const queryParam = variableTag.getAttributeValue('QUERYPARAM');
  1063. if (name && value) {
  1064. if (!this.globalVariables_.has(name)) {
  1065. this.globalVariables_.set(name, value);
  1066. }
  1067. }
  1068. if (queryParam) {
  1069. const queryParamValue = queryParams.get(queryParam)[0];
  1070. if (queryParamValue && !this.globalVariables_.has(queryParamValue)) {
  1071. this.globalVariables_.set(queryParam, queryParamValue);
  1072. }
  1073. }
  1074. }
  1075. }
  1076. /**
  1077. * Get the variables of each variant tag, and store in a map.
  1078. * @param {!Array.<!shaka.hls.Tag>} tags Variant tags from the playlist.
  1079. * @param {string} uri Media playlist URI.
  1080. * @return {!Map.<string, string>}
  1081. * @private
  1082. */
  1083. parseMediaVariables_(tags, uri) {
  1084. const queryParams = new goog.Uri(uri).getQueryData();
  1085. const mediaVariables = new Map();
  1086. for (const variableTag of tags) {
  1087. const name = variableTag.getAttributeValue('NAME');
  1088. const value = variableTag.getAttributeValue('VALUE');
  1089. const queryParam = variableTag.getAttributeValue('QUERYPARAM');
  1090. const mediaImport = variableTag.getAttributeValue('IMPORT');
  1091. if (name && value) {
  1092. if (!mediaVariables.has(name)) {
  1093. mediaVariables.set(name, value);
  1094. }
  1095. }
  1096. if (queryParam) {
  1097. const queryParamValue = queryParams.get(queryParam)[0];
  1098. if (queryParamValue && !mediaVariables.has(queryParamValue)) {
  1099. mediaVariables.set(queryParam, queryParamValue);
  1100. }
  1101. }
  1102. if (mediaImport) {
  1103. const globalValue = this.globalVariables_.get(mediaImport);
  1104. if (globalValue) {
  1105. mediaVariables.set(mediaImport, globalValue);
  1106. }
  1107. }
  1108. }
  1109. return mediaVariables;
  1110. }
  1111. /**
  1112. * Get the codecs of each variant tag, and store in a map from
  1113. * audio/video/subtitle group id to the codecs arraylist.
  1114. * @param {!Array.<!shaka.hls.Tag>} tags Variant tags from the playlist.
  1115. * @private
  1116. */
  1117. parseCodecs_(tags) {
  1118. const ContentType = shaka.util.ManifestParserUtils.ContentType;
  1119. for (const variantTag of tags) {
  1120. const audioGroupId = variantTag.getAttributeValue('AUDIO');
  1121. const videoGroupId = variantTag.getAttributeValue('VIDEO');
  1122. const subGroupId = variantTag.getAttributeValue('SUBTITLES');
  1123. const allCodecs = this.getCodecsForVariantTag_(variantTag);
  1124. if (subGroupId) {
  1125. const textCodecs = shaka.util.ManifestParserUtils.guessCodecsSafe(
  1126. ContentType.TEXT, allCodecs);
  1127. goog.asserts.assert(textCodecs != null, 'Text codecs should be valid.');
  1128. this.groupIdToCodecsMap_.set(subGroupId, textCodecs);
  1129. shaka.util.ArrayUtils.remove(allCodecs, textCodecs);
  1130. }
  1131. if (audioGroupId) {
  1132. let codecs = shaka.util.ManifestParserUtils.guessCodecsSafe(
  1133. ContentType.AUDIO, allCodecs);
  1134. if (!codecs) {
  1135. codecs = this.config_.hls.defaultAudioCodec;
  1136. }
  1137. this.groupIdToCodecsMap_.set(audioGroupId, codecs);
  1138. }
  1139. if (videoGroupId) {
  1140. let codecs = shaka.util.ManifestParserUtils.guessCodecsSafe(
  1141. ContentType.VIDEO, allCodecs);
  1142. if (!codecs) {
  1143. codecs = this.config_.hls.defaultVideoCodec;
  1144. }
  1145. this.groupIdToCodecsMap_.set(videoGroupId, codecs);
  1146. }
  1147. }
  1148. }
  1149. /**
  1150. * Process EXT-X-SESSION-DATA tags.
  1151. *
  1152. * @param {!Array.<!shaka.hls.Tag>} tags
  1153. * @private
  1154. */
  1155. processSessionData_(tags) {
  1156. for (const tag of tags) {
  1157. const id = tag.getAttributeValue('DATA-ID');
  1158. const uri = tag.getAttributeValue('URI');
  1159. const language = tag.getAttributeValue('LANGUAGE');
  1160. const value = tag.getAttributeValue('VALUE');
  1161. const data = (new Map()).set('id', id);
  1162. if (uri) {
  1163. data.set('uri', shaka.hls.Utils.constructSegmentUris(
  1164. [this.masterPlaylistUri_], uri, this.globalVariables_)[0]);
  1165. }
  1166. if (language) {
  1167. data.set('language', language);
  1168. }
  1169. if (value) {
  1170. data.set('value', value);
  1171. }
  1172. const event = new shaka.util.FakeEvent('sessiondata', data);
  1173. if (this.playerInterface_) {
  1174. this.playerInterface_.onEvent(event);
  1175. }
  1176. }
  1177. }
  1178. /**
  1179. * Process EXT-X-CONTENT-STEERING tags.
  1180. *
  1181. * @param {!Array.<!shaka.hls.Tag>} tags
  1182. * @return {!Promise}
  1183. * @private
  1184. */
  1185. async processContentSteering_(tags) {
  1186. if (!this.playerInterface_ || !this.config_) {
  1187. return;
  1188. }
  1189. let contentSteeringPromise;
  1190. for (const tag of tags) {
  1191. const defaultPathwayId = tag.getAttributeValue('PATHWAY-ID');
  1192. const uri = tag.getAttributeValue('SERVER-URI');
  1193. if (!defaultPathwayId || !uri) {
  1194. continue;
  1195. }
  1196. this.contentSteeringManager_ =
  1197. new shaka.util.ContentSteeringManager(this.playerInterface_);
  1198. this.contentSteeringManager_.configure(this.config_);
  1199. this.contentSteeringManager_.setBaseUris([this.masterPlaylistUri_]);
  1200. this.contentSteeringManager_.setManifestType(
  1201. shaka.media.ManifestParser.HLS);
  1202. this.contentSteeringManager_.setDefaultPathwayId(defaultPathwayId);
  1203. contentSteeringPromise =
  1204. this.contentSteeringManager_.requestInfo(uri);
  1205. break;
  1206. }
  1207. await contentSteeringPromise;
  1208. }
  1209. /**
  1210. * Parse Subtitles and Closed Captions from 'EXT-X-MEDIA' tags.
  1211. * Create text streams for Subtitles, but not Closed Captions.
  1212. *
  1213. * @param {!Array.<!shaka.hls.Tag>} mediaTags Media tags from the playlist.
  1214. * @return {!Array.<!shaka.extern.Stream>}
  1215. * @private
  1216. */
  1217. parseTexts_(mediaTags) {
  1218. // Create text stream for each Subtitle media tag.
  1219. const subtitleTags =
  1220. shaka.hls.Utils.filterTagsByType(mediaTags, 'SUBTITLES');
  1221. const textStreams = subtitleTags.map((tag) => {
  1222. const disableText = this.config_.disableText;
  1223. if (disableText) {
  1224. return null;
  1225. }
  1226. try {
  1227. return this.createStreamInfoFromMediaTags_([tag], new Map()).stream;
  1228. } catch (e) {
  1229. if (this.config_.hls.ignoreTextStreamFailures) {
  1230. return null;
  1231. }
  1232. throw e;
  1233. }
  1234. });
  1235. const type = shaka.util.ManifestParserUtils.ContentType.TEXT;
  1236. // Set the codecs for text streams.
  1237. for (const tag of subtitleTags) {
  1238. const groupId = tag.getRequiredAttrValue('GROUP-ID');
  1239. const codecs = this.groupIdToCodecsMap_.get(groupId);
  1240. if (codecs) {
  1241. const textStreamInfos = this.groupIdToStreamInfosMap_.get(groupId);
  1242. if (textStreamInfos) {
  1243. for (const textStreamInfo of textStreamInfos) {
  1244. textStreamInfo.stream.codecs = codecs;
  1245. textStreamInfo.stream.mimeType =
  1246. this.guessMimeTypeBeforeLoading_(type, codecs) ||
  1247. this.guessMimeTypeFallback_(type);
  1248. this.setFullTypeForStream_(textStreamInfo.stream);
  1249. }
  1250. }
  1251. }
  1252. }
  1253. // Do not create text streams for Closed captions.
  1254. return textStreams.filter((s) => s);
  1255. }
  1256. /**
  1257. * @param {!shaka.extern.Stream} stream
  1258. * @private
  1259. */
  1260. setFullTypeForStream_(stream) {
  1261. const combinations = new Set([shaka.util.MimeUtils.getFullType(
  1262. stream.mimeType, stream.codecs)]);
  1263. if (stream.segmentIndex) {
  1264. stream.segmentIndex.forEachTopLevelReference((reference) => {
  1265. if (reference.mimeType) {
  1266. combinations.add(shaka.util.MimeUtils.getFullType(
  1267. reference.mimeType, stream.codecs));
  1268. }
  1269. });
  1270. }
  1271. stream.fullMimeTypes = combinations;
  1272. }
  1273. /**
  1274. * @param {!Array.<!shaka.hls.Tag>} imageTags from the playlist.
  1275. * @param {!Array.<!shaka.hls.Tag>} iFrameTags from the playlist.
  1276. * @return {!Promise.<!Array.<!shaka.extern.Stream>>}
  1277. * @private
  1278. */
  1279. async parseImages_(imageTags, iFrameTags) {
  1280. // Create image stream for each image tag.
  1281. const imageStreamPromises = imageTags.map(async (tag) => {
  1282. const disableThumbnails = this.config_.disableThumbnails;
  1283. if (disableThumbnails) {
  1284. return null;
  1285. }
  1286. try {
  1287. const streamInfo = await this.createStreamInfoFromImageTag_(tag);
  1288. return streamInfo.stream;
  1289. } catch (e) {
  1290. if (this.config_.hls.ignoreImageStreamFailures) {
  1291. return null;
  1292. }
  1293. throw e;
  1294. }
  1295. }).concat(iFrameTags.map((tag) => {
  1296. const disableThumbnails = this.config_.disableThumbnails;
  1297. if (disableThumbnails) {
  1298. return null;
  1299. }
  1300. try {
  1301. const streamInfo = this.createStreamInfoFromIframeTag_(tag);
  1302. const ContentType = shaka.util.ManifestParserUtils.ContentType;
  1303. if (streamInfo.stream.type !== ContentType.IMAGE) {
  1304. return null;
  1305. }
  1306. return streamInfo.stream;
  1307. } catch (e) {
  1308. if (this.config_.hls.ignoreImageStreamFailures) {
  1309. return null;
  1310. }
  1311. throw e;
  1312. }
  1313. }));
  1314. const imageStreams = await Promise.all(imageStreamPromises);
  1315. return imageStreams.filter((s) => s);
  1316. }
  1317. /**
  1318. * @param {!Array.<!shaka.hls.Tag>} mediaTags Media tags from the playlist.
  1319. * @param {!Map.<string, string>} groupIdPathwayIdMapping
  1320. * @private
  1321. */
  1322. createStreamInfosFromMediaTags_(mediaTags, groupIdPathwayIdMapping) {
  1323. // Filter out subtitles and media tags without uri.
  1324. mediaTags = mediaTags.filter((tag) => {
  1325. const uri = tag.getAttributeValue('URI') || '';
  1326. const type = tag.getAttributeValue('TYPE');
  1327. return type != 'SUBTITLES' && uri != '';
  1328. });
  1329. const groupedTags = {};
  1330. for (const tag of mediaTags) {
  1331. const key = tag.getTagKey(!this.contentSteeringManager_);
  1332. if (!groupedTags[key]) {
  1333. groupedTags[key] = [tag];
  1334. } else {
  1335. groupedTags[key].push(tag);
  1336. }
  1337. }
  1338. for (const key in groupedTags) {
  1339. // Create stream info for each audio / video media grouped tag.
  1340. this.createStreamInfoFromMediaTags_(
  1341. groupedTags[key], groupIdPathwayIdMapping);
  1342. }
  1343. }
  1344. /**
  1345. * @param {!Array.<!shaka.hls.Tag>} iFrameTags from the playlist.
  1346. * @return {!Array.<!shaka.extern.Stream>}
  1347. * @private
  1348. */
  1349. parseIFrames_(iFrameTags) {
  1350. // Create iFrame stream for each iFrame tag.
  1351. const iFrameStreams = iFrameTags.map((tag) => {
  1352. const streamInfo = this.createStreamInfoFromIframeTag_(tag);
  1353. const ContentType = shaka.util.ManifestParserUtils.ContentType;
  1354. if (streamInfo.stream.type !== ContentType.VIDEO) {
  1355. return null;
  1356. }
  1357. return streamInfo.stream;
  1358. });
  1359. // Filter mjpg iFrames
  1360. return iFrameStreams.filter((s) => s);
  1361. }
  1362. /**
  1363. * @param {!Array.<!shaka.hls.Tag>} tags Variant tags from the playlist.
  1364. * @param {!Array.<!shaka.hls.Tag>} sessionKeyTags EXT-X-SESSION-KEY tags
  1365. * from the playlist.
  1366. * @param {!Array.<!shaka.hls.Tag>} mediaTags EXT-X-MEDIA tags from the
  1367. * playlist.
  1368. * @param {function():!Array.<string>} getUris
  1369. * @param {?Map.<string, string>} variables
  1370. * @param {!Array.<!shaka.extern.Stream>} iFrameStreams
  1371. * @return {!Promise.<!Array.<!shaka.extern.Variant>>}
  1372. * @private
  1373. */
  1374. async createVariantsForTags_(tags, sessionKeyTags, mediaTags, getUris,
  1375. variables, iFrameStreams) {
  1376. // EXT-X-SESSION-KEY processing
  1377. const drmInfos = [];
  1378. const keyIds = new Set();
  1379. if (sessionKeyTags.length > 0) {
  1380. for (const drmTag of sessionKeyTags) {
  1381. const method = drmTag.getRequiredAttrValue('METHOD');
  1382. // According to the HLS spec, KEYFORMAT is optional and implicitly
  1383. // defaults to "identity".
  1384. // https://datatracker.ietf.org/doc/html/draft-pantos-hls-rfc8216bis-11#section-4.4.4.4
  1385. const keyFormat =
  1386. drmTag.getAttributeValue('KEYFORMAT') || 'identity';
  1387. let drmInfo = null;
  1388. if (method == 'NONE') {
  1389. continue;
  1390. } else if (this.isAesMethod_(method)) {
  1391. const keyUris = shaka.hls.Utils.constructSegmentUris(
  1392. getUris(), drmTag.getRequiredAttrValue('URI'), variables);
  1393. const keyMapKey = keyUris.sort().join('');
  1394. if (!this.aesKeyMap_.has(keyMapKey)) {
  1395. const requestType = shaka.net.NetworkingEngine.RequestType.KEY;
  1396. const request = shaka.net.NetworkingEngine.makeRequest(
  1397. keyUris, this.config_.retryParameters);
  1398. const keyResponse = this.makeNetworkRequest_(request, requestType)
  1399. .promise;
  1400. this.aesKeyMap_.set(keyMapKey, keyResponse);
  1401. }
  1402. continue;
  1403. } else if (keyFormat == 'identity') {
  1404. // eslint-disable-next-line no-await-in-loop
  1405. drmInfo = await this.identityDrmParser_(
  1406. drmTag, /* mimeType= */ '', getUris,
  1407. /* initSegmentRef= */ null, variables);
  1408. } else {
  1409. const drmParser =
  1410. shaka.hls.HlsParser.KEYFORMATS_TO_DRM_PARSERS_[keyFormat];
  1411. drmInfo = drmParser ?
  1412. drmParser(drmTag, /* mimeType= */ '') : null;
  1413. }
  1414. if (drmInfo) {
  1415. if (drmInfo.keyIds) {
  1416. for (const keyId of drmInfo.keyIds) {
  1417. keyIds.add(keyId);
  1418. }
  1419. }
  1420. drmInfos.push(drmInfo);
  1421. } else {
  1422. shaka.log.warning('Unsupported HLS KEYFORMAT', keyFormat);
  1423. }
  1424. }
  1425. }
  1426. const groupedTags = {};
  1427. for (const tag of tags) {
  1428. const key = tag.getTagKey(!this.contentSteeringManager_);
  1429. if (!groupedTags[key]) {
  1430. groupedTags[key] = [tag];
  1431. } else {
  1432. groupedTags[key].push(tag);
  1433. }
  1434. }
  1435. const allVariants = [];
  1436. // Create variants for each group of variant tag.
  1437. for (const key in groupedTags) {
  1438. const tags = groupedTags[key];
  1439. const firstTag = tags[0];
  1440. const frameRate = firstTag.getAttributeValue('FRAME-RATE');
  1441. const bandwidth =
  1442. Number(firstTag.getAttributeValue('AVERAGE-BANDWIDTH')) ||
  1443. Number(firstTag.getRequiredAttrValue('BANDWIDTH'));
  1444. const resolution = firstTag.getAttributeValue('RESOLUTION');
  1445. const [width, height] = resolution ? resolution.split('x') : [null, null];
  1446. const videoRange = firstTag.getAttributeValue('VIDEO-RANGE');
  1447. let videoLayout = firstTag.getAttributeValue('REQ-VIDEO-LAYOUT');
  1448. if (videoLayout && videoLayout.includes(',')) {
  1449. // If multiple video layout strings are present, pick the first valid
  1450. // one.
  1451. const layoutStrings = videoLayout.split(',').filter((layoutString) => {
  1452. return layoutString == 'CH-STEREO' || layoutString == 'CH-MONO';
  1453. });
  1454. videoLayout = layoutStrings[0];
  1455. }
  1456. // According to the HLS spec:
  1457. // By default a video variant is monoscopic, so an attribute
  1458. // consisting entirely of REQ-VIDEO-LAYOUT="CH-MONO" is unnecessary
  1459. // and SHOULD NOT be present.
  1460. videoLayout = videoLayout || 'CH-MONO';
  1461. const streamInfos = this.createStreamInfosForVariantTags_(tags,
  1462. mediaTags, resolution, frameRate);
  1463. goog.asserts.assert(streamInfos.audio.length ||
  1464. streamInfos.video.length, 'We should have created a stream!');
  1465. allVariants.push(...this.createVariants_(
  1466. streamInfos.audio,
  1467. streamInfos.video,
  1468. bandwidth,
  1469. width,
  1470. height,
  1471. frameRate,
  1472. videoRange,
  1473. videoLayout,
  1474. drmInfos,
  1475. keyIds,
  1476. iFrameStreams));
  1477. }
  1478. return allVariants.filter((variant) => variant != null);
  1479. }
  1480. /**
  1481. * Create audio and video streamInfos from an 'EXT-X-STREAM-INF' tag and its
  1482. * related media tags.
  1483. *
  1484. * @param {!Array.<!shaka.hls.Tag>} tags
  1485. * @param {!Array.<!shaka.hls.Tag>} mediaTags
  1486. * @param {?string} resolution
  1487. * @param {?string} frameRate
  1488. * @return {!shaka.hls.HlsParser.StreamInfos}
  1489. * @private
  1490. */
  1491. createStreamInfosForVariantTags_(tags, mediaTags, resolution, frameRate) {
  1492. const ContentType = shaka.util.ManifestParserUtils.ContentType;
  1493. /** @type {shaka.hls.HlsParser.StreamInfos} */
  1494. const res = {
  1495. audio: [],
  1496. video: [],
  1497. };
  1498. const groupIdPathwayIdMapping = new Map();
  1499. const globalGroupIds = [];
  1500. let isAudioGroup = false;
  1501. let isVideoGroup = false;
  1502. for (const tag of tags) {
  1503. const audioGroupId = tag.getAttributeValue('AUDIO');
  1504. const videoGroupId = tag.getAttributeValue('VIDEO');
  1505. goog.asserts.assert(audioGroupId == null || videoGroupId == null,
  1506. 'Unexpected: both video and audio described by media tags!');
  1507. const groupId = audioGroupId || videoGroupId;
  1508. if (!groupId) {
  1509. continue;
  1510. }
  1511. if (!globalGroupIds.includes(groupId)) {
  1512. globalGroupIds.push(groupId);
  1513. }
  1514. const pathwayId = tag.getAttributeValue('PATHWAY-ID');
  1515. if (pathwayId) {
  1516. groupIdPathwayIdMapping.set(groupId, pathwayId);
  1517. }
  1518. if (audioGroupId) {
  1519. isAudioGroup = true;
  1520. } else if (videoGroupId) {
  1521. isVideoGroup = true;
  1522. }
  1523. // Make an educated guess about the stream type.
  1524. shaka.log.debug('Guessing stream type for', tag.toString());
  1525. }
  1526. if (globalGroupIds.length && mediaTags.length) {
  1527. const mediaTagsForVariant = mediaTags.filter((tag) => {
  1528. return globalGroupIds.includes(tag.getRequiredAttrValue('GROUP-ID'));
  1529. });
  1530. this.createStreamInfosFromMediaTags_(
  1531. mediaTagsForVariant, groupIdPathwayIdMapping);
  1532. }
  1533. const globalGroupId = globalGroupIds.sort().join(',');
  1534. const streamInfos =
  1535. (globalGroupId && this.groupIdToStreamInfosMap_.has(globalGroupId)) ?
  1536. this.groupIdToStreamInfosMap_.get(globalGroupId) : [];
  1537. if (isAudioGroup) {
  1538. res.audio.push(...streamInfos);
  1539. } else if (isVideoGroup) {
  1540. res.video.push(...streamInfos);
  1541. }
  1542. let type;
  1543. let ignoreStream = false;
  1544. // The Microsoft HLS manifest generators will make audio-only variants
  1545. // that link to their URI both directly and through an audio tag.
  1546. // In that case, ignore the local URI and use the version in the
  1547. // AUDIO tag, so you inherit its language.
  1548. // As an example, see the manifest linked in issue #860.
  1549. const allStreamUris = tags.map((tag) => tag.getRequiredAttrValue('URI'));
  1550. const hasSameUri = res.audio.find((audio) => {
  1551. return audio && audio.getUris().find((uri) => {
  1552. return allStreamUris.includes(uri);
  1553. });
  1554. });
  1555. /** @type {!Array.<string>} */
  1556. let allCodecs = this.getCodecsForVariantTag_(tags[0]);
  1557. const videoCodecs = shaka.util.ManifestParserUtils.guessCodecsSafe(
  1558. ContentType.VIDEO, allCodecs);
  1559. const audioCodecs = shaka.util.ManifestParserUtils.guessCodecsSafe(
  1560. ContentType.AUDIO, allCodecs);
  1561. if (audioCodecs && !videoCodecs) {
  1562. // There are no associated media tags, and there's only audio codec,
  1563. // and no video codec, so it should be audio.
  1564. type = ContentType.AUDIO;
  1565. shaka.log.debug('Guessing audio-only.');
  1566. ignoreStream = res.audio.length > 0;
  1567. } else if (!res.audio.length && !res.video.length &&
  1568. audioCodecs && videoCodecs) {
  1569. // There are both audio and video codecs, so assume multiplexed content.
  1570. // Note that the default used when CODECS is missing assumes multiple
  1571. // (and therefore multiplexed).
  1572. // Recombine the codec strings into one so that MediaSource isn't
  1573. // lied to later. (That would trigger an error in Chrome.)
  1574. shaka.log.debug('Guessing multiplexed audio+video.');
  1575. type = ContentType.VIDEO;
  1576. allCodecs = [[videoCodecs, audioCodecs].join(',')];
  1577. } else if (res.audio.length && hasSameUri) {
  1578. shaka.log.debug('Guessing audio-only.');
  1579. type = ContentType.AUDIO;
  1580. ignoreStream = true;
  1581. } else if (res.video.length && !res.audio.length) {
  1582. // There are associated video streams. Assume this is audio.
  1583. shaka.log.debug('Guessing audio-only.');
  1584. type = ContentType.AUDIO;
  1585. } else {
  1586. shaka.log.debug('Guessing video-only.');
  1587. type = ContentType.VIDEO;
  1588. }
  1589. if (!ignoreStream) {
  1590. let language = null;
  1591. let name = null;
  1592. let channelsCount = null;
  1593. let spatialAudio = false;
  1594. let characteristics = null;
  1595. let sampleRate = null;
  1596. if (!streamInfos.length) {
  1597. const mediaTag = mediaTags.find((tag) => {
  1598. const uri = tag.getAttributeValue('URI') || '';
  1599. const type = tag.getAttributeValue('TYPE');
  1600. const groupId = tag.getRequiredAttrValue('GROUP-ID');
  1601. return type != 'SUBTITLES' && uri == '' &&
  1602. globalGroupIds.includes(groupId);
  1603. });
  1604. if (mediaTag) {
  1605. language = mediaTag.getAttributeValue('LANGUAGE');
  1606. name = mediaTag.getAttributeValue('NAME');
  1607. channelsCount = this.getChannelsCount_(mediaTag);
  1608. spatialAudio = this.isSpatialAudio_(mediaTag);
  1609. characteristics = mediaTag.getAttributeValue('CHARACTERISTICS');
  1610. sampleRate = this.getSampleRate_(mediaTag);
  1611. }
  1612. }
  1613. const streamInfo = this.createStreamInfoFromVariantTags_(
  1614. tags, allCodecs, type, language, name, channelsCount,
  1615. characteristics, sampleRate, spatialAudio);
  1616. if (globalGroupId) {
  1617. streamInfo.stream.groupId = globalGroupId;
  1618. }
  1619. res[streamInfo.stream.type] = [streamInfo];
  1620. }
  1621. return res;
  1622. }
  1623. /**
  1624. * Get the codecs from the 'EXT-X-STREAM-INF' tag.
  1625. *
  1626. * @param {!shaka.hls.Tag} tag
  1627. * @return {!Array.<string>} codecs
  1628. * @private
  1629. */
  1630. getCodecsForVariantTag_(tag) {
  1631. let codecsString = tag.getAttributeValue('CODECS') || '';
  1632. const supplementalCodecsString =
  1633. tag.getAttributeValue('SUPPLEMENTAL-CODECS');
  1634. this.codecInfoInManifest_ = codecsString.length > 0;
  1635. if (!this.codecInfoInManifest_ && !this.config_.hls.disableCodecGuessing) {
  1636. // These are the default codecs to assume if none are specified.
  1637. const defaultCodecsArray = [];
  1638. if (!this.config_.disableVideo) {
  1639. defaultCodecsArray.push(this.config_.hls.defaultVideoCodec);
  1640. }
  1641. if (!this.config_.disableAudio) {
  1642. defaultCodecsArray.push(this.config_.hls.defaultAudioCodec);
  1643. }
  1644. codecsString = defaultCodecsArray.join(',');
  1645. }
  1646. // Strip out internal whitespace while splitting on commas:
  1647. /** @type {!Array.<string>} */
  1648. const codecs = codecsString.split(/\s*,\s*/);
  1649. if (supplementalCodecsString) {
  1650. const supplementalCodecs = supplementalCodecsString.split(/\s*,\s*/)
  1651. .map((codec) => {
  1652. return codec.split('/')[0];
  1653. });
  1654. codecs.push(...supplementalCodecs);
  1655. }
  1656. return shaka.media.SegmentUtils.codecsFiltering(codecs);
  1657. }
  1658. /**
  1659. * Get the channel count information for an HLS audio track.
  1660. * CHANNELS specifies an ordered, "/" separated list of parameters.
  1661. * If the type is audio, the first parameter will be a decimal integer
  1662. * specifying the number of independent, simultaneous audio channels.
  1663. * No other channels parameters are currently defined.
  1664. *
  1665. * @param {!shaka.hls.Tag} tag
  1666. * @return {?number}
  1667. * @private
  1668. */
  1669. getChannelsCount_(tag) {
  1670. const channels = tag.getAttributeValue('CHANNELS');
  1671. if (!channels) {
  1672. return null;
  1673. }
  1674. const channelcountstring = channels.split('/')[0];
  1675. const count = parseInt(channelcountstring, 10);
  1676. return count;
  1677. }
  1678. /**
  1679. * Get the sample rate information for an HLS audio track.
  1680. *
  1681. * @param {!shaka.hls.Tag} tag
  1682. * @return {?number}
  1683. * @private
  1684. */
  1685. getSampleRate_(tag) {
  1686. const sampleRate = tag.getAttributeValue('SAMPLE-RATE');
  1687. if (!sampleRate) {
  1688. return null;
  1689. }
  1690. return parseInt(sampleRate, 10);
  1691. }
  1692. /**
  1693. * Get the spatial audio information for an HLS audio track.
  1694. * In HLS the channels field indicates the number of audio channels that the
  1695. * stream has (eg: 2). In the case of Dolby Atmos, the complexity is
  1696. * expressed with the number of channels followed by the word JOC
  1697. * (eg: 16/JOC), so 16 would be the number of channels (eg: 7.3.6 layout),
  1698. * and JOC indicates that the stream has spatial audio.
  1699. * @see https://developer.apple.com/documentation/http_live_streaming/hls_authoring_specification_for_apple_devices/hls_authoring_specification_for_apple_devices_appendixes
  1700. *
  1701. * @param {!shaka.hls.Tag} tag
  1702. * @return {boolean}
  1703. * @private
  1704. */
  1705. isSpatialAudio_(tag) {
  1706. const channels = tag.getAttributeValue('CHANNELS');
  1707. if (!channels) {
  1708. return false;
  1709. }
  1710. return channels.includes('/JOC');
  1711. }
  1712. /**
  1713. * Get the closed captions map information for the EXT-X-STREAM-INF tag, to
  1714. * create the stream info.
  1715. * @param {!shaka.hls.Tag} tag
  1716. * @param {string} type
  1717. * @return {Map.<string, string>} closedCaptions
  1718. * @private
  1719. */
  1720. getClosedCaptions_(tag, type) {
  1721. const ContentType = shaka.util.ManifestParserUtils.ContentType;
  1722. // The attribute of closed captions is optional, and the value may be
  1723. // 'NONE'.
  1724. const closedCaptionsAttr = tag.getAttributeValue('CLOSED-CAPTIONS');
  1725. // EXT-X-STREAM-INF tags may have CLOSED-CAPTIONS attributes.
  1726. // The value can be either a quoted-string or an enumerated-string with
  1727. // the value NONE. If the value is a quoted-string, it MUST match the
  1728. // value of the GROUP-ID attribute of an EXT-X-MEDIA tag elsewhere in the
  1729. // Playlist whose TYPE attribute is CLOSED-CAPTIONS.
  1730. if (type == ContentType.VIDEO ) {
  1731. if (this.config_.disableText) {
  1732. this.needsClosedCaptionsDetection_ = false;
  1733. return null;
  1734. }
  1735. if (closedCaptionsAttr) {
  1736. if (closedCaptionsAttr != 'NONE') {
  1737. return this.groupIdToClosedCaptionsMap_.get(closedCaptionsAttr);
  1738. }
  1739. this.needsClosedCaptionsDetection_ = false;
  1740. } else if (!closedCaptionsAttr && this.groupIdToClosedCaptionsMap_.size) {
  1741. for (const key of this.groupIdToClosedCaptionsMap_.keys()) {
  1742. return this.groupIdToClosedCaptionsMap_.get(key);
  1743. }
  1744. }
  1745. }
  1746. return null;
  1747. }
  1748. /**
  1749. * Get the normalized language value.
  1750. *
  1751. * @param {?string} languageValue
  1752. * @return {string}
  1753. * @private
  1754. */
  1755. getLanguage_(languageValue) {
  1756. const LanguageUtils = shaka.util.LanguageUtils;
  1757. return LanguageUtils.normalize(languageValue || 'und');
  1758. }
  1759. /**
  1760. * Get the type value.
  1761. * Shaka recognizes the content types 'audio', 'video', 'text', and 'image'.
  1762. * The HLS 'subtitles' type needs to be mapped to 'text'.
  1763. * @param {!shaka.hls.Tag} tag
  1764. * @return {string}
  1765. * @private
  1766. */
  1767. getType_(tag) {
  1768. let type = tag.getRequiredAttrValue('TYPE').toLowerCase();
  1769. if (type == 'subtitles') {
  1770. type = shaka.util.ManifestParserUtils.ContentType.TEXT;
  1771. }
  1772. return type;
  1773. }
  1774. /**
  1775. * @param {!Array.<shaka.hls.HlsParser.StreamInfo>} audioInfos
  1776. * @param {!Array.<shaka.hls.HlsParser.StreamInfo>} videoInfos
  1777. * @param {number} bandwidth
  1778. * @param {?string} width
  1779. * @param {?string} height
  1780. * @param {?string} frameRate
  1781. * @param {?string} videoRange
  1782. * @param {?string} videoLayout
  1783. * @param {!Array.<shaka.extern.DrmInfo>} drmInfos
  1784. * @param {!Set.<string>} keyIds
  1785. * @param {!Array.<!shaka.extern.Stream>} iFrameStreams
  1786. * @return {!Array.<!shaka.extern.Variant>}
  1787. * @private
  1788. */
  1789. createVariants_(
  1790. audioInfos, videoInfos, bandwidth, width, height, frameRate, videoRange,
  1791. videoLayout, drmInfos, keyIds, iFrameStreams) {
  1792. const ContentType = shaka.util.ManifestParserUtils.ContentType;
  1793. const DrmUtils = shaka.util.DrmUtils;
  1794. for (const info of videoInfos) {
  1795. this.addVideoAttributes_(
  1796. info.stream, width, height, frameRate, videoRange, videoLayout,
  1797. /** colorGamut= */ null);
  1798. }
  1799. // In case of audio-only or video-only content or the audio/video is
  1800. // disabled by the config, we create an array of one item containing
  1801. // a null. This way, the double-loop works for all kinds of content.
  1802. // NOTE: we currently don't have support for audio-only content.
  1803. const disableAudio = this.config_.disableAudio;
  1804. if (!audioInfos.length || disableAudio) {
  1805. audioInfos = [null];
  1806. }
  1807. const disableVideo = this.config_.disableVideo;
  1808. if (!videoInfos.length || disableVideo) {
  1809. videoInfos = [null];
  1810. }
  1811. const variants = [];
  1812. for (const audioInfo of audioInfos) {
  1813. for (const videoInfo of videoInfos) {
  1814. const audioStream = audioInfo ? audioInfo.stream : null;
  1815. if (audioStream) {
  1816. audioStream.drmInfos = drmInfos;
  1817. audioStream.keyIds = keyIds;
  1818. }
  1819. const videoStream = videoInfo ? videoInfo.stream : null;
  1820. if (videoStream) {
  1821. videoStream.drmInfos = drmInfos;
  1822. videoStream.keyIds = keyIds;
  1823. shaka.util.StreamUtils.setBetterIFrameStream(
  1824. videoStream, iFrameStreams);
  1825. }
  1826. if (videoStream && !audioStream) {
  1827. videoStream.bandwidth = bandwidth;
  1828. }
  1829. if (!videoStream && audioStream) {
  1830. audioStream.bandwidth = bandwidth;
  1831. }
  1832. const audioDrmInfos = audioInfo ? audioInfo.stream.drmInfos : null;
  1833. const videoDrmInfos = videoInfo ? videoInfo.stream.drmInfos : null;
  1834. const videoStreamUri =
  1835. videoInfo ? videoInfo.getUris().sort().join(',') : '';
  1836. const audioStreamUri =
  1837. audioInfo ? audioInfo.getUris().sort().join(',') : '';
  1838. const variantUriKey = videoStreamUri + ' - ' + audioStreamUri;
  1839. if (audioStream && videoStream) {
  1840. if (!DrmUtils.areDrmCompatible(audioDrmInfos, videoDrmInfos)) {
  1841. shaka.log.warning(
  1842. 'Incompatible DRM info in HLS variant. Skipping.');
  1843. continue;
  1844. }
  1845. }
  1846. if (this.variantUriSet_.has(variantUriKey)) {
  1847. // This happens when two variants only differ in their text streams.
  1848. shaka.log.debug(
  1849. 'Skipping variant which only differs in text streams.');
  1850. continue;
  1851. }
  1852. // Since both audio and video are of the same type, this assertion will
  1853. // catch certain mistakes at runtime that the compiler would miss.
  1854. goog.asserts.assert(!audioStream ||
  1855. audioStream.type == ContentType.AUDIO, 'Audio parameter mismatch!');
  1856. goog.asserts.assert(!videoStream ||
  1857. videoStream.type == ContentType.VIDEO, 'Video parameter mismatch!');
  1858. const variant = {
  1859. id: this.globalId_++,
  1860. language: audioStream ? audioStream.language : 'und',
  1861. disabledUntilTime: 0,
  1862. primary: (!!audioStream && audioStream.primary) ||
  1863. (!!videoStream && videoStream.primary),
  1864. audio: audioStream,
  1865. video: videoStream,
  1866. bandwidth,
  1867. allowedByApplication: true,
  1868. allowedByKeySystem: true,
  1869. decodingInfos: [],
  1870. };
  1871. variants.push(variant);
  1872. this.variantUriSet_.add(variantUriKey);
  1873. }
  1874. }
  1875. return variants;
  1876. }
  1877. /**
  1878. * Parses an array of EXT-X-MEDIA tags, then stores the values of all tags
  1879. * with TYPE="CLOSED-CAPTIONS" into a map of group id to closed captions.
  1880. *
  1881. * @param {!Array.<!shaka.hls.Tag>} mediaTags
  1882. * @private
  1883. */
  1884. parseClosedCaptions_(mediaTags) {
  1885. const closedCaptionsTags =
  1886. shaka.hls.Utils.filterTagsByType(mediaTags, 'CLOSED-CAPTIONS');
  1887. this.needsClosedCaptionsDetection_ = closedCaptionsTags.length == 0;
  1888. for (const tag of closedCaptionsTags) {
  1889. goog.asserts.assert(tag.name == 'EXT-X-MEDIA',
  1890. 'Should only be called on media tags!');
  1891. const languageValue = tag.getAttributeValue('LANGUAGE');
  1892. let language = this.getLanguage_(languageValue);
  1893. if (!languageValue) {
  1894. const nameValue = tag.getAttributeValue('NAME');
  1895. if (nameValue) {
  1896. language = nameValue;
  1897. }
  1898. }
  1899. // The GROUP-ID value is a quoted-string that specifies the group to which
  1900. // the Rendition belongs.
  1901. const groupId = tag.getRequiredAttrValue('GROUP-ID');
  1902. // The value of INSTREAM-ID is a quoted-string that specifies a Rendition
  1903. // within the segments in the Media Playlist. This attribute is REQUIRED
  1904. // if the TYPE attribute is CLOSED-CAPTIONS.
  1905. // We need replace SERVICE string by our internal svc string.
  1906. const instreamId = tag.getRequiredAttrValue('INSTREAM-ID')
  1907. .replace('SERVICE', 'svc');
  1908. if (!this.groupIdToClosedCaptionsMap_.get(groupId)) {
  1909. this.groupIdToClosedCaptionsMap_.set(groupId, new Map());
  1910. }
  1911. this.groupIdToClosedCaptionsMap_.get(groupId).set(instreamId, language);
  1912. }
  1913. }
  1914. /**
  1915. * Parse EXT-X-MEDIA media tag into a Stream object.
  1916. *
  1917. * @param {!Array.<!shaka.hls.Tag>} tags
  1918. * @param {!Map.<string, string>} groupIdPathwayIdMapping
  1919. * @return {!shaka.hls.HlsParser.StreamInfo}
  1920. * @private
  1921. */
  1922. createStreamInfoFromMediaTags_(tags, groupIdPathwayIdMapping) {
  1923. const verbatimMediaPlaylistUris = [];
  1924. const globalGroupIds = [];
  1925. const groupIdUriMappping = new Map();
  1926. for (const tag of tags) {
  1927. goog.asserts.assert(tag.name == 'EXT-X-MEDIA',
  1928. 'Should only be called on media tags!');
  1929. const uri = tag.getRequiredAttrValue('URI');
  1930. const groupId = tag.getRequiredAttrValue('GROUP-ID');
  1931. verbatimMediaPlaylistUris.push(uri);
  1932. globalGroupIds.push(groupId);
  1933. groupIdUriMappping.set(groupId, uri);
  1934. }
  1935. const globalGroupId = globalGroupIds.sort().join(',');
  1936. const firstTag = tags[0];
  1937. let codecs = '';
  1938. /** @type {string} */
  1939. const type = this.getType_(firstTag);
  1940. if (type == shaka.util.ManifestParserUtils.ContentType.TEXT) {
  1941. codecs = firstTag.getAttributeValue('CODECS') || '';
  1942. } else {
  1943. for (const groupId of globalGroupIds) {
  1944. if (this.groupIdToCodecsMap_.has(groupId)) {
  1945. codecs = this.groupIdToCodecsMap_.get(groupId);
  1946. break;
  1947. }
  1948. }
  1949. }
  1950. // Check if the stream has already been created as part of another Variant
  1951. // and return it if it has.
  1952. const key = verbatimMediaPlaylistUris.sort().join(',');
  1953. if (this.uriToStreamInfosMap_.has(key)) {
  1954. return this.uriToStreamInfosMap_.get(key);
  1955. }
  1956. const streamId = this.globalId_++;
  1957. if (this.contentSteeringManager_) {
  1958. for (const [groupId, uri] of groupIdUriMappping) {
  1959. const pathwayId = groupIdPathwayIdMapping.get(groupId);
  1960. if (pathwayId) {
  1961. this.contentSteeringManager_.addLocation(streamId, pathwayId, uri);
  1962. }
  1963. }
  1964. }
  1965. const language = firstTag.getAttributeValue('LANGUAGE');
  1966. const name = firstTag.getAttributeValue('NAME');
  1967. // NOTE: According to the HLS spec, "DEFAULT=YES" requires "AUTOSELECT=YES".
  1968. // However, we don't bother to validate "AUTOSELECT", since we don't
  1969. // actually use it in our streaming model, and we treat everything as
  1970. // "AUTOSELECT=YES". A value of "AUTOSELECT=NO" would imply that it may
  1971. // only be selected explicitly by the user, and we don't have a way to
  1972. // represent that in our model.
  1973. const defaultAttrValue = firstTag.getAttributeValue('DEFAULT');
  1974. const primary = defaultAttrValue == 'YES';
  1975. const channelsCount =
  1976. type == 'audio' ? this.getChannelsCount_(firstTag) : null;
  1977. const spatialAudio =
  1978. type == 'audio' ? this.isSpatialAudio_(firstTag) : false;
  1979. const characteristics = firstTag.getAttributeValue('CHARACTERISTICS');
  1980. const forcedAttrValue = firstTag.getAttributeValue('FORCED');
  1981. const forced = forcedAttrValue == 'YES';
  1982. const sampleRate = type == 'audio' ? this.getSampleRate_(firstTag) : null;
  1983. // TODO: Should we take into account some of the currently ignored
  1984. // attributes: INSTREAM-ID, Attribute descriptions: https://bit.ly/2lpjOhj
  1985. const streamInfo = this.createStreamInfo_(
  1986. streamId, verbatimMediaPlaylistUris, codecs, type, language,
  1987. primary, name, channelsCount, /* closedCaptions= */ null,
  1988. characteristics, forced, sampleRate, spatialAudio);
  1989. if (streamInfo.stream) {
  1990. streamInfo.stream.groupId = globalGroupId;
  1991. }
  1992. if (this.groupIdToStreamInfosMap_.has(globalGroupId)) {
  1993. this.groupIdToStreamInfosMap_.get(globalGroupId).push(streamInfo);
  1994. } else {
  1995. this.groupIdToStreamInfosMap_.set(globalGroupId, [streamInfo]);
  1996. }
  1997. this.uriToStreamInfosMap_.set(key, streamInfo);
  1998. return streamInfo;
  1999. }
  2000. /**
  2001. * Parse EXT-X-IMAGE-STREAM-INF media tag into a Stream object.
  2002. *
  2003. * @param {shaka.hls.Tag} tag
  2004. * @return {!Promise.<!shaka.hls.HlsParser.StreamInfo>}
  2005. * @private
  2006. */
  2007. async createStreamInfoFromImageTag_(tag) {
  2008. goog.asserts.assert(tag.name == 'EXT-X-IMAGE-STREAM-INF',
  2009. 'Should only be called on image tags!');
  2010. /** @type {string} */
  2011. const type = shaka.util.ManifestParserUtils.ContentType.IMAGE;
  2012. const verbatimImagePlaylistUri = tag.getRequiredAttrValue('URI');
  2013. const codecs = tag.getAttributeValue('CODECS', 'jpeg') || '';
  2014. // Check if the stream has already been created as part of another Variant
  2015. // and return it if it has.
  2016. if (this.uriToStreamInfosMap_.has(verbatimImagePlaylistUri)) {
  2017. return this.uriToStreamInfosMap_.get(verbatimImagePlaylistUri);
  2018. }
  2019. const language = tag.getAttributeValue('LANGUAGE');
  2020. const name = tag.getAttributeValue('NAME');
  2021. const characteristics = tag.getAttributeValue('CHARACTERISTICS');
  2022. const streamInfo = this.createStreamInfo_(
  2023. this.globalId_++, [verbatimImagePlaylistUri], codecs, type, language,
  2024. /* primary= */ false, name, /* channelsCount= */ null,
  2025. /* closedCaptions= */ null, characteristics, /* forced= */ false,
  2026. /* sampleRate= */ null, /* spatialAudio= */ false);
  2027. // Parse misc attributes.
  2028. const resolution = tag.getAttributeValue('RESOLUTION');
  2029. if (resolution) {
  2030. // The RESOLUTION tag represents the resolution of a single thumbnail, not
  2031. // of the entire sheet at once (like we expect in the output).
  2032. // So multiply by the layout size.
  2033. // Since we need to have generated the segment index for this, we can't
  2034. // lazy-load in this situation.
  2035. await streamInfo.stream.createSegmentIndex();
  2036. const reference = streamInfo.stream.segmentIndex.earliestReference();
  2037. const layout = reference.getTilesLayout();
  2038. if (layout) {
  2039. streamInfo.stream.width =
  2040. Number(resolution.split('x')[0]) * Number(layout.split('x')[0]);
  2041. streamInfo.stream.height =
  2042. Number(resolution.split('x')[1]) * Number(layout.split('x')[1]);
  2043. // TODO: What happens if there are multiple grids, with different
  2044. // layout sizes, inside this image stream?
  2045. }
  2046. }
  2047. const bandwidth = tag.getAttributeValue('BANDWIDTH');
  2048. if (bandwidth) {
  2049. streamInfo.stream.bandwidth = Number(bandwidth);
  2050. }
  2051. this.uriToStreamInfosMap_.set(verbatimImagePlaylistUri, streamInfo);
  2052. return streamInfo;
  2053. }
  2054. /**
  2055. * Parse EXT-X-I-FRAME-STREAM-INF media tag into a Stream object.
  2056. *
  2057. * @param {shaka.hls.Tag} tag
  2058. * @return {!shaka.hls.HlsParser.StreamInfo}
  2059. * @private
  2060. */
  2061. createStreamInfoFromIframeTag_(tag) {
  2062. goog.asserts.assert(tag.name == 'EXT-X-I-FRAME-STREAM-INF',
  2063. 'Should only be called on iframe tags!');
  2064. /** @type {string} */
  2065. let type = shaka.util.ManifestParserUtils.ContentType.VIDEO;
  2066. const verbatimIFramePlaylistUri = tag.getRequiredAttrValue('URI');
  2067. const codecs = tag.getAttributeValue('CODECS') || '';
  2068. if (codecs == 'mjpg') {
  2069. type = shaka.util.ManifestParserUtils.ContentType.IMAGE;
  2070. }
  2071. // Check if the stream has already been created as part of another Variant
  2072. // and return it if it has.
  2073. if (this.uriToStreamInfosMap_.has(verbatimIFramePlaylistUri)) {
  2074. return this.uriToStreamInfosMap_.get(verbatimIFramePlaylistUri);
  2075. }
  2076. const language = tag.getAttributeValue('LANGUAGE');
  2077. const name = tag.getAttributeValue('NAME');
  2078. const characteristics = tag.getAttributeValue('CHARACTERISTICS');
  2079. const streamInfo = this.createStreamInfo_(
  2080. this.globalId_++, [verbatimIFramePlaylistUri], codecs, type, language,
  2081. /* primary= */ false, name, /* channelsCount= */ null,
  2082. /* closedCaptions= */ null, characteristics, /* forced= */ false,
  2083. /* sampleRate= */ null, /* spatialAudio= */ false);
  2084. // Parse misc attributes.
  2085. const resolution = tag.getAttributeValue('RESOLUTION');
  2086. const [width, height] = resolution ? resolution.split('x') : [null, null];
  2087. streamInfo.stream.width = Number(width) || undefined;
  2088. streamInfo.stream.height = Number(height) || undefined;
  2089. const bandwidth = tag.getAttributeValue('BANDWIDTH');
  2090. if (bandwidth) {
  2091. streamInfo.stream.bandwidth = Number(bandwidth);
  2092. }
  2093. this.uriToStreamInfosMap_.set(verbatimIFramePlaylistUri, streamInfo);
  2094. return streamInfo;
  2095. }
  2096. /**
  2097. * Parse an EXT-X-STREAM-INF media tag into a Stream object.
  2098. *
  2099. * @param {!Array.<!shaka.hls.Tag>} tags
  2100. * @param {!Array.<string>} allCodecs
  2101. * @param {string} type
  2102. * @param {?string} language
  2103. * @param {?string} name
  2104. * @param {?number} channelsCount
  2105. * @param {?string} characteristics
  2106. * @param {?number} sampleRate
  2107. * @param {boolean} spatialAudio
  2108. * @return {!shaka.hls.HlsParser.StreamInfo}
  2109. * @private
  2110. */
  2111. createStreamInfoFromVariantTags_(tags, allCodecs, type, language, name,
  2112. channelsCount, characteristics, sampleRate, spatialAudio) {
  2113. const streamId = this.globalId_++;
  2114. const verbatimMediaPlaylistUris = [];
  2115. for (const tag of tags) {
  2116. goog.asserts.assert(tag.name == 'EXT-X-STREAM-INF',
  2117. 'Should only be called on variant tags!');
  2118. const uri = tag.getRequiredAttrValue('URI');
  2119. const pathwayId = tag.getAttributeValue('PATHWAY-ID');
  2120. if (this.contentSteeringManager_ && pathwayId) {
  2121. this.contentSteeringManager_.addLocation(streamId, pathwayId, uri);
  2122. }
  2123. verbatimMediaPlaylistUris.push(uri);
  2124. }
  2125. const key = verbatimMediaPlaylistUris.sort().join(',');
  2126. if (this.uriToStreamInfosMap_.has(key)) {
  2127. return this.uriToStreamInfosMap_.get(key);
  2128. }
  2129. const closedCaptions = this.getClosedCaptions_(tags[0], type);
  2130. const codecs = shaka.util.ManifestParserUtils.guessCodecs(type, allCodecs);
  2131. const streamInfo = this.createStreamInfo_(
  2132. streamId, verbatimMediaPlaylistUris, codecs, type, language,
  2133. /* primary= */ false, name, channelsCount, closedCaptions,
  2134. characteristics, /* forced= */ false, sampleRate,
  2135. /* spatialAudio= */ false);
  2136. this.uriToStreamInfosMap_.set(key, streamInfo);
  2137. return streamInfo;
  2138. }
  2139. /**
  2140. * @param {number} streamId
  2141. * @param {!Array.<string>} verbatimMediaPlaylistUris
  2142. * @param {string} codecs
  2143. * @param {string} type
  2144. * @param {?string} languageValue
  2145. * @param {boolean} primary
  2146. * @param {?string} name
  2147. * @param {?number} channelsCount
  2148. * @param {Map.<string, string>} closedCaptions
  2149. * @param {?string} characteristics
  2150. * @param {boolean} forced
  2151. * @param {?number} sampleRate
  2152. * @param {boolean} spatialAudio
  2153. * @return {!shaka.hls.HlsParser.StreamInfo}
  2154. * @private
  2155. */
  2156. createStreamInfo_(streamId, verbatimMediaPlaylistUris, codecs, type,
  2157. languageValue, primary, name, channelsCount, closedCaptions,
  2158. characteristics, forced, sampleRate, spatialAudio) {
  2159. // TODO: Refactor, too many parameters
  2160. // This stream is lazy-loaded inside the createSegmentIndex function.
  2161. // So we start out with a stream object that does not contain the actual
  2162. // segment index, then download when createSegmentIndex is called.
  2163. const stream = this.makeStreamObject_(streamId, codecs, type,
  2164. languageValue, primary, name, channelsCount, closedCaptions,
  2165. characteristics, forced, sampleRate, spatialAudio);
  2166. const redirectUris = [];
  2167. const getUris = () => {
  2168. if (this.contentSteeringManager_ &&
  2169. verbatimMediaPlaylistUris.length > 1) {
  2170. return this.contentSteeringManager_.getLocations(streamId);
  2171. }
  2172. return redirectUris.concat(shaka.hls.Utils.constructUris(
  2173. [this.masterPlaylistUri_], verbatimMediaPlaylistUris,
  2174. this.globalVariables_));
  2175. };
  2176. const streamInfo = {
  2177. stream,
  2178. type,
  2179. redirectUris,
  2180. getUris,
  2181. // These values are filled out or updated after lazy-loading:
  2182. minTimestamp: 0,
  2183. maxTimestamp: 0,
  2184. mediaSequenceToStartTime: new Map(),
  2185. canSkipSegments: false,
  2186. canBlockReload: false,
  2187. hasEndList: false,
  2188. firstSequenceNumber: -1,
  2189. nextMediaSequence: -1,
  2190. nextPart: -1,
  2191. loadedOnce: false,
  2192. };
  2193. /** @param {!shaka.net.NetworkingEngine.PendingRequest} pendingRequest */
  2194. const downloadSegmentIndex = async (pendingRequest) => {
  2195. const ContentType = shaka.util.ManifestParserUtils.ContentType;
  2196. try {
  2197. const uris = streamInfo.getUris();
  2198. // Download the actual manifest.
  2199. const response = await pendingRequest.promise;
  2200. if (pendingRequest.aborted) {
  2201. return;
  2202. }
  2203. // Record the final URI after redirects.
  2204. const responseUri = response.uri;
  2205. if (responseUri != response.originalUri &&
  2206. !uris.includes(responseUri)) {
  2207. redirectUris.push(responseUri);
  2208. }
  2209. // Record the redirected, final URI of this media playlist when we parse
  2210. // it.
  2211. /** @type {!shaka.hls.Playlist} */
  2212. const playlist = this.manifestTextParser_.parsePlaylist(response.data);
  2213. if (playlist.type != shaka.hls.PlaylistType.MEDIA) {
  2214. throw new shaka.util.Error(
  2215. shaka.util.Error.Severity.CRITICAL,
  2216. shaka.util.Error.Category.MANIFEST,
  2217. shaka.util.Error.Code.HLS_INVALID_PLAYLIST_HIERARCHY);
  2218. }
  2219. /** @type {!Array.<!shaka.hls.Tag>} */
  2220. const variablesTags = shaka.hls.Utils.filterTagsByName(playlist.tags,
  2221. 'EXT-X-DEFINE');
  2222. const mediaVariables =
  2223. this.parseMediaVariables_(variablesTags, responseUri);
  2224. const mimeType = undefined;
  2225. let requestBasicInfo = false;
  2226. // If no codec info was provided in the manifest and codec guessing is
  2227. // disabled we try to get necessary info from the media data.
  2228. if ((!this.codecInfoInManifest_ &&
  2229. this.config_.hls.disableCodecGuessing) ||
  2230. (this.needsClosedCaptionsDetection_ && type == ContentType.VIDEO &&
  2231. !this.config_.hls.disableClosedCaptionsDetection)) {
  2232. if (playlist.segments.length > 0) {
  2233. this.needsClosedCaptionsDetection_ = false;
  2234. requestBasicInfo = true;
  2235. }
  2236. }
  2237. const allowOverrideMimeType = !this.codecInfoInManifest_ &&
  2238. this.config_.hls.disableCodecGuessing;
  2239. const wasLive = this.isLive_();
  2240. const realStreamInfo = await this.convertParsedPlaylistIntoStreamInfo_(
  2241. streamId, mediaVariables, playlist, getUris, responseUri, codecs,
  2242. type, languageValue, primary, name, channelsCount, closedCaptions,
  2243. characteristics, forced, sampleRate, spatialAudio, mimeType,
  2244. requestBasicInfo, allowOverrideMimeType);
  2245. if (pendingRequest.aborted) {
  2246. return;
  2247. }
  2248. const realStream = realStreamInfo.stream;
  2249. this.determineStartTime_(playlist);
  2250. if (this.isLive_() && !wasLive) {
  2251. // Now that we know that the presentation is live, convert the
  2252. // timeline to live.
  2253. this.changePresentationTimelineToLive_(playlist);
  2254. }
  2255. // Copy values from the real stream info to our initial one.
  2256. streamInfo.minTimestamp = realStreamInfo.minTimestamp;
  2257. streamInfo.maxTimestamp = realStreamInfo.maxTimestamp;
  2258. streamInfo.canSkipSegments = realStreamInfo.canSkipSegments;
  2259. streamInfo.canBlockReload = realStreamInfo.canBlockReload;
  2260. streamInfo.hasEndList = realStreamInfo.hasEndList;
  2261. streamInfo.mediaSequenceToStartTime =
  2262. realStreamInfo.mediaSequenceToStartTime;
  2263. streamInfo.nextMediaSequence = realStreamInfo.nextMediaSequence;
  2264. streamInfo.nextPart = realStreamInfo.nextPart;
  2265. streamInfo.loadedOnce = true;
  2266. stream.segmentIndex = realStream.segmentIndex;
  2267. stream.encrypted = realStream.encrypted;
  2268. stream.drmInfos = realStream.drmInfos;
  2269. stream.keyIds = realStream.keyIds;
  2270. stream.mimeType = realStream.mimeType;
  2271. stream.bandwidth = stream.bandwidth || realStream.bandwidth;
  2272. stream.codecs = stream.codecs || realStream.codecs;
  2273. stream.closedCaptions =
  2274. stream.closedCaptions || realStream.closedCaptions;
  2275. stream.width = stream.width || realStream.width;
  2276. stream.height = stream.height || realStream.height;
  2277. stream.hdr = stream.hdr || realStream.hdr;
  2278. stream.colorGamut = stream.colorGamut || realStream.colorGamut;
  2279. stream.frameRate = stream.frameRate || realStream.frameRate;
  2280. if (stream.language == 'und' && realStream.language != 'und') {
  2281. stream.language = realStream.language;
  2282. }
  2283. stream.language = stream.language || realStream.language;
  2284. stream.channelsCount = stream.channelsCount || realStream.channelsCount;
  2285. stream.audioSamplingRate =
  2286. stream.audioSamplingRate || realStream.audioSamplingRate;
  2287. this.setFullTypeForStream_(stream);
  2288. // Since we lazy-loaded this content, the player may need to create new
  2289. // sessions for the DRM info in this stream.
  2290. if (stream.drmInfos.length) {
  2291. this.playerInterface_.newDrmInfo(stream);
  2292. }
  2293. let closedCaptionsUpdated = false;
  2294. if ((!closedCaptions && stream.closedCaptions) ||
  2295. (closedCaptions && stream.closedCaptions &&
  2296. closedCaptions.size != stream.closedCaptions.size)) {
  2297. closedCaptionsUpdated = true;
  2298. }
  2299. if (this.manifest_ && closedCaptionsUpdated) {
  2300. this.playerInterface_.makeTextStreamsForClosedCaptions(
  2301. this.manifest_);
  2302. }
  2303. if (type == ContentType.VIDEO || type == ContentType.AUDIO) {
  2304. for (const otherStreamInfo of this.uriToStreamInfosMap_.values()) {
  2305. if (!otherStreamInfo.loadedOnce && otherStreamInfo.type == type) {
  2306. // To aid manifest filtering, assume before loading that all video
  2307. // renditions have the same MIME type. (And likewise for audio.)
  2308. otherStreamInfo.stream.mimeType = realStream.mimeType;
  2309. this.setFullTypeForStream_(otherStreamInfo.stream);
  2310. }
  2311. }
  2312. }
  2313. if (type == ContentType.TEXT) {
  2314. const firstSegment = realStream.segmentIndex.earliestReference();
  2315. if (firstSegment && firstSegment.initSegmentReference) {
  2316. stream.mimeType = 'application/mp4';
  2317. this.setFullTypeForStream_(stream);
  2318. }
  2319. }
  2320. const qualityInfo =
  2321. shaka.media.QualityObserver.createQualityInfo(stream);
  2322. stream.segmentIndex.forEachTopLevelReference((reference) => {
  2323. if (reference.initSegmentReference) {
  2324. reference.initSegmentReference.mediaQuality = qualityInfo;
  2325. }
  2326. });
  2327. // Add finishing touches to the stream that can only be done once we
  2328. // have more full context on the media as a whole.
  2329. if (this.hasEnoughInfoToFinalizeStreams_()) {
  2330. if (!this.streamsFinalized_) {
  2331. // Mark this manifest as having been finalized, so we don't go
  2332. // through this whole process of finishing touches a second time.
  2333. this.streamsFinalized_ = true;
  2334. // Finalize all of the currently-loaded streams.
  2335. const streamInfos = Array.from(this.uriToStreamInfosMap_.values());
  2336. const activeStreamInfos =
  2337. streamInfos.filter((s) => s.stream.segmentIndex);
  2338. this.finalizeStreams_(activeStreamInfos);
  2339. // With the addition of this new stream, we now have enough info to
  2340. // figure out how long the streams should be. So process all streams
  2341. // we have downloaded up until this point.
  2342. this.determineDuration_();
  2343. // Finally, start the update timer, if this asset has been
  2344. // determined to be a livestream.
  2345. const delay = this.getUpdatePlaylistDelay_();
  2346. if (delay > 0) {
  2347. this.updatePlaylistTimer_.tickAfter(/* seconds= */ delay);
  2348. }
  2349. } else {
  2350. // We don't need to go through the full process; just finalize this
  2351. // single stream.
  2352. this.finalizeStreams_([streamInfo]);
  2353. }
  2354. }
  2355. this.processDateRangeTags_(
  2356. playlist.tags, stream.type, mediaVariables, getUris);
  2357. if (this.manifest_) {
  2358. this.manifest_.startTime = this.startTime_;
  2359. }
  2360. } catch (e) {
  2361. stream.closeSegmentIndex();
  2362. if (e.code === shaka.util.Error.Code.OPERATION_ABORTED) {
  2363. return;
  2364. }
  2365. const handled = this.playerInterface_.disableStream(stream);
  2366. if (!handled) {
  2367. throw e;
  2368. }
  2369. }
  2370. };
  2371. /** @type {Promise} */
  2372. let creationPromise = null;
  2373. /** @type {!shaka.net.NetworkingEngine.PendingRequest} */
  2374. let pendingRequest;
  2375. const safeCreateSegmentIndex = () => {
  2376. // An operation is already in progress. The second and subsequent
  2377. // callers receive the same Promise as the first caller, and only one
  2378. // download operation will occur.
  2379. if (creationPromise) {
  2380. return creationPromise;
  2381. }
  2382. // Create a new PendingRequest to be able to cancel this specific
  2383. // download.
  2384. pendingRequest = this.requestManifest_(streamInfo.getUris(),
  2385. /* isPlaylist= */ true);
  2386. // Create a Promise tied to the outcome of downloadSegmentIndex(). If
  2387. // downloadSegmentIndex is rejected, creationPromise will also be
  2388. // rejected.
  2389. creationPromise = new Promise((resolve) => {
  2390. resolve(downloadSegmentIndex(pendingRequest));
  2391. });
  2392. return creationPromise;
  2393. };
  2394. stream.createSegmentIndex = safeCreateSegmentIndex;
  2395. stream.closeSegmentIndex = () => {
  2396. // If we're mid-creation, cancel it.
  2397. if (creationPromise && !stream.segmentIndex) {
  2398. pendingRequest.abort();
  2399. }
  2400. // If we have a segment index, release it.
  2401. if (stream.segmentIndex) {
  2402. stream.segmentIndex.release();
  2403. stream.segmentIndex = null;
  2404. }
  2405. // Clear the creation Promise so that a new operation can begin.
  2406. creationPromise = null;
  2407. };
  2408. return streamInfo;
  2409. }
  2410. /**
  2411. * @return {number}
  2412. * @private
  2413. */
  2414. getMinDuration_() {
  2415. let minDuration = Infinity;
  2416. for (const streamInfo of this.uriToStreamInfosMap_.values()) {
  2417. if (streamInfo.stream.segmentIndex && streamInfo.stream.type != 'text') {
  2418. // Since everything is already offset to 0 (either by sync or by being
  2419. // VOD), only maxTimestamp is necessary to compute the duration.
  2420. minDuration = Math.min(minDuration, streamInfo.maxTimestamp);
  2421. }
  2422. }
  2423. return minDuration;
  2424. }
  2425. /**
  2426. * @return {number}
  2427. * @private
  2428. */
  2429. getLiveDuration_() {
  2430. let maxTimestamp = Infinity;
  2431. let minTimestamp = Infinity;
  2432. for (const streamInfo of this.uriToStreamInfosMap_.values()) {
  2433. if (streamInfo.stream.segmentIndex && streamInfo.stream.type != 'text') {
  2434. maxTimestamp = Math.min(maxTimestamp, streamInfo.maxTimestamp);
  2435. minTimestamp = Math.min(minTimestamp, streamInfo.minTimestamp);
  2436. }
  2437. }
  2438. return maxTimestamp - minTimestamp;
  2439. }
  2440. /**
  2441. * @param {!Array.<!shaka.extern.Stream>} streams
  2442. * @private
  2443. */
  2444. notifySegmentsForStreams_(streams) {
  2445. const references = [];
  2446. for (const stream of streams) {
  2447. if (!stream.segmentIndex) {
  2448. // The stream was closed since the list of streams was built.
  2449. continue;
  2450. }
  2451. stream.segmentIndex.forEachTopLevelReference((reference) => {
  2452. references.push(reference);
  2453. });
  2454. }
  2455. this.presentationTimeline_.notifySegments(references);
  2456. }
  2457. /**
  2458. * @param {!Array.<!shaka.hls.HlsParser.StreamInfo>} streamInfos
  2459. * @private
  2460. */
  2461. finalizeStreams_(streamInfos) {
  2462. if (!this.isLive_()) {
  2463. const minDuration = this.getMinDuration_();
  2464. for (const streamInfo of streamInfos) {
  2465. streamInfo.stream.segmentIndex.fit(/* periodStart= */ 0, minDuration);
  2466. }
  2467. }
  2468. this.notifySegmentsForStreams_(streamInfos.map((s) => s.stream));
  2469. const liveWithNoProgramaDateTime =
  2470. this.isLive_() && !this.usesProgramDateTime_;
  2471. if (this.config_.hls.ignoreManifestProgramDateTime ||
  2472. liveWithNoProgramaDateTime) {
  2473. this.syncStreamsWithSequenceNumber_(
  2474. streamInfos, liveWithNoProgramaDateTime);
  2475. } else {
  2476. this.syncStreamsWithProgramDateTime_(streamInfos);
  2477. if (this.config_.hls.ignoreManifestProgramDateTimeForTypes.length > 0) {
  2478. this.syncStreamsWithSequenceNumber_(streamInfos);
  2479. }
  2480. }
  2481. }
  2482. /**
  2483. * @param {string} type
  2484. * @return {boolean}
  2485. * @private
  2486. */
  2487. ignoreManifestProgramDateTimeFor_(type) {
  2488. if (this.config_.hls.ignoreManifestProgramDateTime) {
  2489. return true;
  2490. }
  2491. const forTypes = this.config_.hls.ignoreManifestProgramDateTimeForTypes;
  2492. return forTypes.includes(type);
  2493. }
  2494. /**
  2495. * There are some values on streams that can only be set once we know about
  2496. * both the video and audio content, if present.
  2497. * This checks if there is at least one video downloaded (if the media has
  2498. * video), and that there is at least one audio downloaded (if the media has
  2499. * audio).
  2500. * @return {boolean}
  2501. * @private
  2502. */
  2503. hasEnoughInfoToFinalizeStreams_() {
  2504. if (!this.manifest_) {
  2505. return false;
  2506. }
  2507. const videos = [];
  2508. const audios = [];
  2509. for (const variant of this.manifest_.variants) {
  2510. if (variant.video) {
  2511. videos.push(variant.video);
  2512. }
  2513. if (variant.audio) {
  2514. audios.push(variant.audio);
  2515. }
  2516. }
  2517. if (videos.length > 0 && !videos.some((stream) => stream.segmentIndex)) {
  2518. return false;
  2519. }
  2520. if (audios.length > 0 && !audios.some((stream) => stream.segmentIndex)) {
  2521. return false;
  2522. }
  2523. return true;
  2524. }
  2525. /**
  2526. * @param {number} streamId
  2527. * @param {!shaka.hls.Playlist} playlist
  2528. * @param {function():!Array.<string>} getUris
  2529. * @param {string} responseUri
  2530. * @param {string} codecs
  2531. * @param {string} type
  2532. * @param {?string} languageValue
  2533. * @param {boolean} primary
  2534. * @param {?string} name
  2535. * @param {?number} channelsCount
  2536. * @param {Map.<string, string>} closedCaptions
  2537. * @param {?string} characteristics
  2538. * @param {boolean} forced
  2539. * @param {?number} sampleRate
  2540. * @param {boolean} spatialAudio
  2541. * @param {(string|undefined)} mimeType
  2542. * @param {boolean=} requestBasicInfo
  2543. * @param {boolean=} allowOverrideMimeType
  2544. * @return {!Promise.<!shaka.hls.HlsParser.StreamInfo>}
  2545. * @private
  2546. */
  2547. async convertParsedPlaylistIntoStreamInfo_(streamId, variables, playlist,
  2548. getUris, responseUri, codecs, type, languageValue, primary, name,
  2549. channelsCount, closedCaptions, characteristics, forced, sampleRate,
  2550. spatialAudio, mimeType = undefined, requestBasicInfo = true,
  2551. allowOverrideMimeType = true) {
  2552. const playlistSegments = playlist.segments || [];
  2553. const allAreMissing = playlistSegments.every((seg) => {
  2554. if (shaka.hls.Utils.getFirstTagWithName(seg.tags, 'EXT-X-GAP')) {
  2555. return true;
  2556. }
  2557. return false;
  2558. });
  2559. if (!playlistSegments.length || allAreMissing) {
  2560. throw new shaka.util.Error(
  2561. shaka.util.Error.Severity.CRITICAL,
  2562. shaka.util.Error.Category.MANIFEST,
  2563. shaka.util.Error.Code.HLS_EMPTY_MEDIA_PLAYLIST);
  2564. }
  2565. this.determinePresentationType_(playlist);
  2566. if (this.isLive_()) {
  2567. this.determineLastTargetDuration_(playlist);
  2568. }
  2569. const mediaSequenceToStartTime = this.isLive_() ?
  2570. this.mediaSequenceToStartTimeByType_.get(type) : new Map();
  2571. const {segments, bandwidth} = this.createSegments_(
  2572. playlist, mediaSequenceToStartTime, variables, getUris, type);
  2573. let width = null;
  2574. let height = null;
  2575. let videoRange = null;
  2576. let colorGamut = null;
  2577. let frameRate = null;
  2578. if (segments.length > 0 && requestBasicInfo) {
  2579. const basicInfo = await this.getBasicInfoFromSegments_(segments);
  2580. type = basicInfo.type;
  2581. languageValue = basicInfo.language;
  2582. channelsCount = basicInfo.channelCount;
  2583. sampleRate = basicInfo.sampleRate;
  2584. if (!this.config_.disableText) {
  2585. closedCaptions = basicInfo.closedCaptions;
  2586. }
  2587. height = basicInfo.height;
  2588. width = basicInfo.width;
  2589. videoRange = basicInfo.videoRange;
  2590. colorGamut = basicInfo.colorGamut;
  2591. frameRate = basicInfo.frameRate;
  2592. if (allowOverrideMimeType) {
  2593. mimeType = basicInfo.mimeType;
  2594. codecs = basicInfo.codecs;
  2595. }
  2596. }
  2597. if (!mimeType) {
  2598. mimeType = await this.guessMimeType_(type, codecs, segments);
  2599. }
  2600. const {drmInfos, keyIds, encrypted, aesEncrypted} =
  2601. await this.parseDrmInfo_(playlist, mimeType, getUris, variables);
  2602. if (encrypted && !drmInfos.length && !aesEncrypted) {
  2603. throw new shaka.util.Error(
  2604. shaka.util.Error.Severity.CRITICAL,
  2605. shaka.util.Error.Category.MANIFEST,
  2606. shaka.util.Error.Code.HLS_KEYFORMATS_NOT_SUPPORTED);
  2607. }
  2608. const stream = this.makeStreamObject_(streamId, codecs, type,
  2609. languageValue, primary, name, channelsCount, closedCaptions,
  2610. characteristics, forced, sampleRate, spatialAudio);
  2611. stream.encrypted = encrypted;
  2612. stream.drmInfos = drmInfos;
  2613. stream.keyIds = keyIds;
  2614. stream.mimeType = mimeType;
  2615. if (bandwidth) {
  2616. stream.bandwidth = bandwidth;
  2617. }
  2618. this.setFullTypeForStream_(stream);
  2619. if (type == shaka.util.ManifestParserUtils.ContentType.VIDEO &&
  2620. (width || height || videoRange || colorGamut)) {
  2621. this.addVideoAttributes_(stream, width, height,
  2622. frameRate, videoRange, /* videoLayout= */ null, colorGamut);
  2623. }
  2624. // This new calculation is necessary for Low Latency streams.
  2625. if (this.isLive_()) {
  2626. this.determineLastTargetDuration_(playlist);
  2627. }
  2628. const firstStartTime = segments[0].startTime;
  2629. const lastSegment = segments[segments.length - 1];
  2630. const lastEndTime = lastSegment.endTime;
  2631. /** @type {!shaka.media.SegmentIndex} */
  2632. const segmentIndex = new shaka.media.SegmentIndex(segments);
  2633. stream.segmentIndex = segmentIndex;
  2634. const serverControlTag = shaka.hls.Utils.getFirstTagWithName(
  2635. playlist.tags, 'EXT-X-SERVER-CONTROL');
  2636. const canSkipSegments = serverControlTag ?
  2637. serverControlTag.getAttribute('CAN-SKIP-UNTIL') != null : false;
  2638. const canBlockReload = serverControlTag ?
  2639. serverControlTag.getAttribute('CAN-BLOCK-RELOAD') != null : false;
  2640. const mediaSequenceNumber = shaka.hls.Utils.getFirstTagWithNameAsNumber(
  2641. playlist.tags, 'EXT-X-MEDIA-SEQUENCE', 0);
  2642. const {nextMediaSequence, nextPart} =
  2643. this.getNextMediaSequenceAndPart_(mediaSequenceNumber, segments);
  2644. return {
  2645. stream,
  2646. type,
  2647. redirectUris: [],
  2648. getUris,
  2649. minTimestamp: firstStartTime,
  2650. maxTimestamp: lastEndTime,
  2651. canSkipSegments,
  2652. canBlockReload,
  2653. hasEndList: false,
  2654. firstSequenceNumber: -1,
  2655. nextMediaSequence,
  2656. nextPart,
  2657. mediaSequenceToStartTime,
  2658. loadedOnce: false,
  2659. };
  2660. }
  2661. /**
  2662. * Get the next msn and part
  2663. *
  2664. * @param {number} mediaSequenceNumber
  2665. * @param {!Array.<!shaka.media.SegmentReference>} segments
  2666. * @return {{nextMediaSequence: number, nextPart:number}}}
  2667. * @private
  2668. */
  2669. getNextMediaSequenceAndPart_(mediaSequenceNumber, segments) {
  2670. const currentMediaSequence = mediaSequenceNumber + segments.length - 1;
  2671. let nextMediaSequence = currentMediaSequence;
  2672. let nextPart = -1;
  2673. if (!segments.length) {
  2674. nextMediaSequence++;
  2675. return {
  2676. nextMediaSequence,
  2677. nextPart,
  2678. };
  2679. }
  2680. const lastSegment = segments[segments.length - 1];
  2681. const partialReferences = lastSegment.partialReferences;
  2682. if (!lastSegment.partialReferences.length) {
  2683. nextMediaSequence++;
  2684. if (lastSegment.hasByterangeOptimization()) {
  2685. nextPart = 0;
  2686. }
  2687. return {
  2688. nextMediaSequence,
  2689. nextPart,
  2690. };
  2691. }
  2692. nextPart = partialReferences.length - 1;
  2693. const lastPartialReference =
  2694. partialReferences[partialReferences.length - 1];
  2695. if (!lastPartialReference.isPreload()) {
  2696. nextMediaSequence++;
  2697. nextPart = 0;
  2698. }
  2699. return {
  2700. nextMediaSequence,
  2701. nextPart,
  2702. };
  2703. }
  2704. /**
  2705. * Creates a stream object with the given parameters.
  2706. * The parameters that are passed into here are only the things that can be
  2707. * known without downloading the media playlist; other values must be set
  2708. * manually on the object after creation.
  2709. * @param {number} id
  2710. * @param {string} codecs
  2711. * @param {string} type
  2712. * @param {?string} languageValue
  2713. * @param {boolean} primary
  2714. * @param {?string} name
  2715. * @param {?number} channelsCount
  2716. * @param {Map.<string, string>} closedCaptions
  2717. * @param {?string} characteristics
  2718. * @param {boolean} forced
  2719. * @param {?number} sampleRate
  2720. * @param {boolean} spatialAudio
  2721. * @return {!shaka.extern.Stream}
  2722. * @private
  2723. */
  2724. makeStreamObject_(id, codecs, type, languageValue, primary, name,
  2725. channelsCount, closedCaptions, characteristics, forced, sampleRate,
  2726. spatialAudio) {
  2727. // Fill out a "best-guess" mimeType, for now. It will be replaced once the
  2728. // stream is lazy-loaded.
  2729. const mimeType = this.guessMimeTypeBeforeLoading_(type, codecs) ||
  2730. this.guessMimeTypeFallback_(type);
  2731. const roles = [];
  2732. if (characteristics) {
  2733. for (const characteristic of characteristics.split(',')) {
  2734. roles.push(characteristic);
  2735. }
  2736. }
  2737. let kind = undefined;
  2738. let accessibilityPurpose = null;
  2739. if (type == shaka.util.ManifestParserUtils.ContentType.TEXT) {
  2740. if (roles.includes('public.accessibility.transcribes-spoken-dialog') &&
  2741. roles.includes('public.accessibility.describes-music-and-sound')) {
  2742. kind = shaka.util.ManifestParserUtils.TextStreamKind.CLOSED_CAPTION;
  2743. } else {
  2744. kind = shaka.util.ManifestParserUtils.TextStreamKind.SUBTITLE;
  2745. }
  2746. } else {
  2747. if (roles.includes('public.accessibility.describes-video')) {
  2748. accessibilityPurpose =
  2749. shaka.media.ManifestParser.AccessibilityPurpose.VISUALLY_IMPAIRED;
  2750. }
  2751. }
  2752. // If there are no roles, and we have defaulted to the subtitle "kind" for
  2753. // this track, add the implied subtitle role.
  2754. if (!roles.length &&
  2755. kind === shaka.util.ManifestParserUtils.TextStreamKind.SUBTITLE) {
  2756. roles.push(shaka.util.ManifestParserUtils.TextStreamKind.SUBTITLE);
  2757. }
  2758. const stream = {
  2759. id: this.globalId_++,
  2760. originalId: name,
  2761. groupId: null,
  2762. createSegmentIndex: () => Promise.resolve(),
  2763. segmentIndex: null,
  2764. mimeType,
  2765. codecs,
  2766. kind: (type == shaka.util.ManifestParserUtils.ContentType.TEXT) ?
  2767. shaka.util.ManifestParserUtils.TextStreamKind.SUBTITLE : undefined,
  2768. encrypted: false,
  2769. drmInfos: [],
  2770. keyIds: new Set(),
  2771. language: this.getLanguage_(languageValue),
  2772. originalLanguage: languageValue,
  2773. label: name, // For historical reasons, since before "originalId".
  2774. type,
  2775. primary,
  2776. // TODO: trick mode
  2777. trickModeVideo: null,
  2778. emsgSchemeIdUris: null,
  2779. frameRate: undefined,
  2780. pixelAspectRatio: undefined,
  2781. width: undefined,
  2782. height: undefined,
  2783. bandwidth: undefined,
  2784. roles,
  2785. forced,
  2786. channelsCount,
  2787. audioSamplingRate: sampleRate,
  2788. spatialAudio,
  2789. closedCaptions,
  2790. hdr: undefined,
  2791. colorGamut: undefined,
  2792. videoLayout: undefined,
  2793. tilesLayout: undefined,
  2794. accessibilityPurpose: accessibilityPurpose,
  2795. external: false,
  2796. fastSwitching: false,
  2797. fullMimeTypes: new Set(),
  2798. };
  2799. this.setFullTypeForStream_(stream);
  2800. return stream;
  2801. }
  2802. /**
  2803. * @param {!shaka.hls.Playlist} playlist
  2804. * @param {string} mimeType
  2805. * @param {function():!Array.<string>} getUris
  2806. * @param {?Map.<string, string>=} variables
  2807. * @return {Promise.<{
  2808. * drmInfos: !Array.<shaka.extern.DrmInfo>,
  2809. * keyIds: !Set.<string>,
  2810. * encrypted: boolean,
  2811. * aesEncrypted: boolean
  2812. * }>}
  2813. * @private
  2814. */
  2815. async parseDrmInfo_(playlist, mimeType, getUris, variables) {
  2816. /** @type {!Map<!shaka.hls.Tag, ?shaka.media.InitSegmentReference>} */
  2817. const drmTagsMap = new Map();
  2818. if (playlist.segments) {
  2819. for (const segment of playlist.segments) {
  2820. const segmentKeyTags = shaka.hls.Utils.filterTagsByName(segment.tags,
  2821. 'EXT-X-KEY');
  2822. let initSegmentRef = null;
  2823. if (segmentKeyTags.length) {
  2824. initSegmentRef = this.getInitSegmentReference_(playlist,
  2825. segment.tags, getUris, variables);
  2826. for (const segmentKeyTag of segmentKeyTags) {
  2827. drmTagsMap.set(segmentKeyTag, initSegmentRef);
  2828. }
  2829. }
  2830. }
  2831. }
  2832. let encrypted = false;
  2833. let aesEncrypted = false;
  2834. /** @type {!Array.<shaka.extern.DrmInfo>}*/
  2835. const drmInfos = [];
  2836. const keyIds = new Set();
  2837. for (const [key, value] of drmTagsMap) {
  2838. const drmTag = /** @type {!shaka.hls.Tag} */ (key);
  2839. const initSegmentRef =
  2840. /** @type {?shaka.media.InitSegmentReference} */ (value);
  2841. const method = drmTag.getRequiredAttrValue('METHOD');
  2842. if (method != 'NONE') {
  2843. encrypted = true;
  2844. // According to the HLS spec, KEYFORMAT is optional and implicitly
  2845. // defaults to "identity".
  2846. // https://datatracker.ietf.org/doc/html/draft-pantos-hls-rfc8216bis-11#section-4.4.4.4
  2847. const keyFormat =
  2848. drmTag.getAttributeValue('KEYFORMAT') || 'identity';
  2849. let drmInfo = null;
  2850. if (this.isAesMethod_(method)) {
  2851. // These keys are handled separately.
  2852. aesEncrypted = true;
  2853. continue;
  2854. } else if (keyFormat == 'identity') {
  2855. // eslint-disable-next-line no-await-in-loop
  2856. drmInfo = await this.identityDrmParser_(
  2857. drmTag, mimeType, getUris, initSegmentRef, variables);
  2858. } else {
  2859. const drmParser =
  2860. shaka.hls.HlsParser.KEYFORMATS_TO_DRM_PARSERS_[keyFormat];
  2861. drmInfo = drmParser ? drmParser(drmTag, mimeType) : null;
  2862. }
  2863. if (drmInfo) {
  2864. if (drmInfo.keyIds) {
  2865. for (const keyId of drmInfo.keyIds) {
  2866. keyIds.add(keyId);
  2867. }
  2868. }
  2869. drmInfos.push(drmInfo);
  2870. } else {
  2871. shaka.log.warning('Unsupported HLS KEYFORMAT', keyFormat);
  2872. }
  2873. }
  2874. }
  2875. return {drmInfos, keyIds, encrypted, aesEncrypted};
  2876. }
  2877. /**
  2878. * @param {!shaka.hls.Tag} drmTag
  2879. * @param {!shaka.hls.Playlist} playlist
  2880. * @param {function():!Array.<string>} getUris
  2881. * @param {?Map.<string, string>=} variables
  2882. * @return {!shaka.extern.aesKey}
  2883. * @private
  2884. */
  2885. parseAESDrmTag_(drmTag, playlist, getUris, variables) {
  2886. // Check if the Web Crypto API is available.
  2887. if (!window.crypto || !window.crypto.subtle) {
  2888. shaka.log.alwaysWarn('Web Crypto API is not available to decrypt ' +
  2889. 'AES. (Web Crypto only exists in secure origins like https)');
  2890. throw new shaka.util.Error(
  2891. shaka.util.Error.Severity.CRITICAL,
  2892. shaka.util.Error.Category.MANIFEST,
  2893. shaka.util.Error.Code.NO_WEB_CRYPTO_API);
  2894. }
  2895. // HLS RFC 8216 Section 5.2:
  2896. // An EXT-X-KEY tag with a KEYFORMAT of "identity" that does not have an IV
  2897. // attribute indicates that the Media Sequence Number is to be used as the
  2898. // IV when decrypting a Media Segment, by putting its big-endian binary
  2899. // representation into a 16-octet (128-bit) buffer and padding (on the left)
  2900. // with zeros.
  2901. let firstMediaSequenceNumber = 0;
  2902. let iv;
  2903. const ivHex = drmTag.getAttributeValue('IV', '');
  2904. if (!ivHex) {
  2905. // Media Sequence Number will be used as IV.
  2906. firstMediaSequenceNumber = shaka.hls.Utils.getFirstTagWithNameAsNumber(
  2907. playlist.tags, 'EXT-X-MEDIA-SEQUENCE', 0);
  2908. } else {
  2909. // Exclude 0x at the start of string.
  2910. iv = shaka.util.Uint8ArrayUtils.fromHex(ivHex.substr(2));
  2911. if (iv.byteLength != 16) {
  2912. throw new shaka.util.Error(
  2913. shaka.util.Error.Severity.CRITICAL,
  2914. shaka.util.Error.Category.MANIFEST,
  2915. shaka.util.Error.Code.AES_128_INVALID_IV_LENGTH);
  2916. }
  2917. }
  2918. const aesKeyInfoKey = `${drmTag.toString()}-${firstMediaSequenceNumber}`;
  2919. if (!this.aesKeyInfoMap_.has(aesKeyInfoKey)) {
  2920. // Default AES-128
  2921. const keyInfo = {
  2922. bitsKey: 128,
  2923. blockCipherMode: 'CBC',
  2924. iv,
  2925. firstMediaSequenceNumber,
  2926. };
  2927. const method = drmTag.getRequiredAttrValue('METHOD');
  2928. switch (method) {
  2929. case 'AES-256':
  2930. keyInfo.bitsKey = 256;
  2931. break;
  2932. case 'AES-256-CTR':
  2933. keyInfo.bitsKey = 256;
  2934. keyInfo.blockCipherMode = 'CTR';
  2935. break;
  2936. }
  2937. // Don't download the key object until the segment is parsed, to avoid a
  2938. // startup delay for long manifests with lots of keys.
  2939. keyInfo.fetchKey = async () => {
  2940. const keyUris = shaka.hls.Utils.constructSegmentUris(
  2941. getUris(), drmTag.getRequiredAttrValue('URI'), variables);
  2942. const keyMapKey = keyUris.sort().join('');
  2943. if (!this.aesKeyMap_.has(keyMapKey)) {
  2944. const requestType = shaka.net.NetworkingEngine.RequestType.KEY;
  2945. const request = shaka.net.NetworkingEngine.makeRequest(
  2946. keyUris, this.config_.retryParameters);
  2947. const keyResponse = this.makeNetworkRequest_(request, requestType)
  2948. .promise;
  2949. this.aesKeyMap_.set(keyMapKey, keyResponse);
  2950. }
  2951. const keyResponse = await this.aesKeyMap_.get(keyMapKey);
  2952. // keyResponse.status is undefined when URI is "data:text/plain;base64,"
  2953. if (!keyResponse.data ||
  2954. keyResponse.data.byteLength != (keyInfo.bitsKey / 8)) {
  2955. throw new shaka.util.Error(
  2956. shaka.util.Error.Severity.CRITICAL,
  2957. shaka.util.Error.Category.MANIFEST,
  2958. shaka.util.Error.Code.AES_128_INVALID_KEY_LENGTH);
  2959. }
  2960. const algorithm = {
  2961. name: keyInfo.blockCipherMode == 'CTR' ? 'AES-CTR' : 'AES-CBC',
  2962. length: keyInfo.bitsKey,
  2963. };
  2964. keyInfo.cryptoKey = await window.crypto.subtle.importKey(
  2965. 'raw', keyResponse.data, algorithm, true, ['decrypt']);
  2966. keyInfo.fetchKey = undefined; // No longer needed.
  2967. };
  2968. this.aesKeyInfoMap_.set(aesKeyInfoKey, keyInfo);
  2969. }
  2970. return this.aesKeyInfoMap_.get(aesKeyInfoKey);
  2971. }
  2972. /**
  2973. * @param {!shaka.hls.Playlist} playlist
  2974. * @private
  2975. */
  2976. determineStartTime_(playlist) {
  2977. // If we already have a starttime we avoid processing this again.
  2978. if (this.startTime_ != null) {
  2979. return;
  2980. }
  2981. const startTimeTag =
  2982. shaka.hls.Utils.getFirstTagWithName(playlist.tags, 'EXT-X-START');
  2983. if (startTimeTag) {
  2984. this.startTime_ =
  2985. Number(startTimeTag.getRequiredAttrValue('TIME-OFFSET'));
  2986. }
  2987. }
  2988. /**
  2989. * @param {!shaka.hls.Playlist} playlist
  2990. * @private
  2991. */
  2992. determinePresentationType_(playlist) {
  2993. const PresentationType = shaka.hls.HlsParser.PresentationType_;
  2994. const presentationTypeTag =
  2995. shaka.hls.Utils.getFirstTagWithName(playlist.tags,
  2996. 'EXT-X-PLAYLIST-TYPE');
  2997. const endListTag =
  2998. shaka.hls.Utils.getFirstTagWithName(playlist.tags, 'EXT-X-ENDLIST');
  2999. const isVod = (presentationTypeTag && presentationTypeTag.value == 'VOD') ||
  3000. endListTag;
  3001. const isEvent = presentationTypeTag &&
  3002. presentationTypeTag.value == 'EVENT' && !isVod;
  3003. const isLive = !isVod && !isEvent;
  3004. if (isVod) {
  3005. this.setPresentationType_(PresentationType.VOD);
  3006. } else {
  3007. // If it's not VOD, it must be presentation type LIVE or an ongoing EVENT.
  3008. if (isLive) {
  3009. this.setPresentationType_(PresentationType.LIVE);
  3010. } else {
  3011. this.setPresentationType_(PresentationType.EVENT);
  3012. }
  3013. }
  3014. }
  3015. /**
  3016. * @param {!shaka.hls.Playlist} playlist
  3017. * @private
  3018. */
  3019. determineLastTargetDuration_(playlist) {
  3020. let lastTargetDuration = Infinity;
  3021. const segments = playlist.segments;
  3022. if (segments.length) {
  3023. let segmentIndex = segments.length - 1;
  3024. while (segmentIndex >= 0) {
  3025. const segment = segments[segmentIndex];
  3026. const extinfTag =
  3027. shaka.hls.Utils.getFirstTagWithName(segment.tags, 'EXTINF');
  3028. if (extinfTag) {
  3029. // The EXTINF tag format is '#EXTINF:<duration>,[<title>]'.
  3030. // We're interested in the duration part.
  3031. const extinfValues = extinfTag.value.split(',');
  3032. lastTargetDuration = Number(extinfValues[0]);
  3033. break;
  3034. }
  3035. segmentIndex--;
  3036. }
  3037. }
  3038. const targetDurationTag = this.getRequiredTag_(playlist.tags,
  3039. 'EXT-X-TARGETDURATION');
  3040. const targetDuration = Number(targetDurationTag.value);
  3041. const partialTargetDurationTag =
  3042. shaka.hls.Utils.getFirstTagWithName(playlist.tags, 'EXT-X-PART-INF');
  3043. if (partialTargetDurationTag) {
  3044. this.partialTargetDuration_ = Number(
  3045. partialTargetDurationTag.getRequiredAttrValue('PART-TARGET'));
  3046. }
  3047. // Get the server-recommended min distance from the live edge.
  3048. const serverControlTag = shaka.hls.Utils.getFirstTagWithName(
  3049. playlist.tags, 'EXT-X-SERVER-CONTROL');
  3050. // According to the HLS spec, updates should not happen more often than
  3051. // once in targetDuration. It also requires us to only update the active
  3052. // variant. We might implement that later, but for now every variant
  3053. // will be updated. To get the update period, choose the smallest
  3054. // targetDuration value across all playlists.
  3055. // 1. Update the shortest one to use as update period and segment
  3056. // availability time (for LIVE).
  3057. if (this.lowLatencyMode_ && this.partialTargetDuration_) {
  3058. // For low latency streaming, use the partial segment target duration.
  3059. if (this.lowLatencyByterangeOptimization_) {
  3060. // We always have at least 1 partial segment part, and most servers
  3061. // allow you to make a request with _HLS_msn=X&_HLS_part=0 with a
  3062. // distance of 4 partial segments. With this we ensure that we
  3063. // obtain the minimum latency in this type of case.
  3064. if (this.partialTargetDuration_ * 5 <= lastTargetDuration) {
  3065. this.lastTargetDuration_ = Math.min(
  3066. this.partialTargetDuration_, this.lastTargetDuration_);
  3067. } else {
  3068. this.lastTargetDuration_ = Math.min(
  3069. lastTargetDuration, this.lastTargetDuration_);
  3070. }
  3071. } else {
  3072. this.lastTargetDuration_ = Math.min(
  3073. this.partialTargetDuration_, this.lastTargetDuration_);
  3074. }
  3075. // Use 'PART-HOLD-BACK' as the presentation delay for low latency mode.
  3076. this.lowLatencyPresentationDelay_ = serverControlTag ? Number(
  3077. serverControlTag.getRequiredAttrValue('PART-HOLD-BACK')) : 0;
  3078. } else {
  3079. this.lastTargetDuration_ = Math.min(
  3080. lastTargetDuration, this.lastTargetDuration_);
  3081. // Use 'HOLD-BACK' as the presentation delay for default if defined.
  3082. const holdBack = serverControlTag ?
  3083. serverControlTag.getAttribute('HOLD-BACK') : null;
  3084. this.presentationDelay_ = holdBack ? Number(holdBack.value) : 0;
  3085. }
  3086. // 2. Update the longest target duration if need be to use as a
  3087. // presentation delay later.
  3088. this.maxTargetDuration_ = Math.max(
  3089. targetDuration, this.maxTargetDuration_);
  3090. }
  3091. /**
  3092. * @param {!shaka.hls.Playlist} playlist
  3093. * @private
  3094. */
  3095. changePresentationTimelineToLive_(playlist) {
  3096. // The live edge will be calculated from segments, so we don't need to
  3097. // set a presentation start time. We will assert later that this is
  3098. // working as expected.
  3099. // The HLS spec (RFC 8216) states in 6.3.3:
  3100. //
  3101. // "The client SHALL choose which Media Segment to play first ... the
  3102. // client SHOULD NOT choose a segment that starts less than three target
  3103. // durations from the end of the Playlist file. Doing so can trigger
  3104. // playback stalls."
  3105. //
  3106. // We accomplish this in our DASH-y model by setting a presentation
  3107. // delay of configured value, or 3 segments duration if not configured.
  3108. // This will be the "live edge" of the presentation.
  3109. let presentationDelay = 0;
  3110. if (this.config_.defaultPresentationDelay) {
  3111. presentationDelay = this.config_.defaultPresentationDelay;
  3112. } else if (this.lowLatencyPresentationDelay_) {
  3113. presentationDelay = this.lowLatencyPresentationDelay_;
  3114. } else if (this.presentationDelay_) {
  3115. presentationDelay = this.presentationDelay_;
  3116. } else {
  3117. const totalSegments = playlist.segments.length;
  3118. let delaySegments = this.config_.hls.liveSegmentsDelay;
  3119. if (delaySegments > (totalSegments - 2)) {
  3120. delaySegments = Math.max(1, totalSegments - 2);
  3121. }
  3122. for (let i = totalSegments - delaySegments; i < totalSegments; i++) {
  3123. const extinfTag = shaka.hls.Utils.getFirstTagWithName(
  3124. playlist.segments[i].tags, 'EXTINF');
  3125. if (extinfTag) {
  3126. const extinfValues = extinfTag.value.split(',');
  3127. const duration = Number(extinfValues[0]);
  3128. presentationDelay += Math.ceil(duration);
  3129. } else {
  3130. presentationDelay += this.maxTargetDuration_;
  3131. }
  3132. }
  3133. }
  3134. if (this.startTime_ && this.startTime_ < 0) {
  3135. presentationDelay = Math.min(-this.startTime_, presentationDelay);
  3136. this.startTime_ += presentationDelay;
  3137. }
  3138. this.presentationTimeline_.setPresentationStartTime(0);
  3139. this.presentationTimeline_.setDelay(presentationDelay);
  3140. this.presentationTimeline_.setStatic(false);
  3141. }
  3142. /**
  3143. * Get the InitSegmentReference for a segment if it has a EXT-X-MAP tag.
  3144. * @param {!shaka.hls.Playlist} playlist
  3145. * @param {!Array.<!shaka.hls.Tag>} tags Segment tags
  3146. * @param {function():!Array.<string>} getUris
  3147. * @param {?Map.<string, string>=} variables
  3148. * @return {shaka.media.InitSegmentReference}
  3149. * @private
  3150. */
  3151. getInitSegmentReference_(playlist, tags, getUris, variables) {
  3152. /** @type {?shaka.hls.Tag} */
  3153. const mapTag = shaka.hls.Utils.getFirstTagWithName(tags, 'EXT-X-MAP');
  3154. if (!mapTag) {
  3155. return null;
  3156. }
  3157. // Map tag example: #EXT-X-MAP:URI="main.mp4",BYTERANGE="720@0"
  3158. const verbatimInitSegmentUri = mapTag.getRequiredAttrValue('URI');
  3159. const absoluteInitSegmentUris = shaka.hls.Utils.constructSegmentUris(
  3160. getUris(), verbatimInitSegmentUri, variables);
  3161. const mapTagKey = [
  3162. absoluteInitSegmentUris.toString(),
  3163. mapTag.getAttributeValue('BYTERANGE', ''),
  3164. ].join('-');
  3165. if (!this.mapTagToInitSegmentRefMap_.has(mapTagKey)) {
  3166. /** @type {shaka.extern.aesKey|undefined} */
  3167. let aesKey = undefined;
  3168. let byteRangeTag = null;
  3169. for (const tag of tags) {
  3170. if (tag.name == 'EXT-X-KEY') {
  3171. if (this.isAesMethod_(tag.getRequiredAttrValue('METHOD')) &&
  3172. tag.id < mapTag.id) {
  3173. aesKey =
  3174. this.parseAESDrmTag_(tag, playlist, getUris, variables);
  3175. }
  3176. } else if (tag.name == 'EXT-X-BYTERANGE' && tag.id < mapTag.id) {
  3177. byteRangeTag = tag;
  3178. }
  3179. }
  3180. const initSegmentRef = this.createInitSegmentReference_(
  3181. absoluteInitSegmentUris, mapTag, byteRangeTag, aesKey);
  3182. this.mapTagToInitSegmentRefMap_.set(mapTagKey, initSegmentRef);
  3183. }
  3184. return this.mapTagToInitSegmentRefMap_.get(mapTagKey);
  3185. }
  3186. /**
  3187. * Create an InitSegmentReference object for the EXT-X-MAP tag in the media
  3188. * playlist.
  3189. * @param {!Array.<string>} absoluteInitSegmentUris
  3190. * @param {!shaka.hls.Tag} mapTag EXT-X-MAP
  3191. * @param {shaka.hls.Tag=} byteRangeTag EXT-X-BYTERANGE
  3192. * @param {shaka.extern.aesKey=} aesKey
  3193. * @return {!shaka.media.InitSegmentReference}
  3194. * @private
  3195. */
  3196. createInitSegmentReference_(absoluteInitSegmentUris, mapTag, byteRangeTag,
  3197. aesKey) {
  3198. let startByte = 0;
  3199. let endByte = null;
  3200. let byterange = mapTag.getAttributeValue('BYTERANGE');
  3201. if (!byterange && byteRangeTag) {
  3202. byterange = byteRangeTag.value;
  3203. }
  3204. // If a BYTERANGE attribute is not specified, the segment consists
  3205. // of the entire resource.
  3206. if (byterange) {
  3207. const blocks = byterange.split('@');
  3208. const byteLength = Number(blocks[0]);
  3209. startByte = Number(blocks[1]);
  3210. endByte = startByte + byteLength - 1;
  3211. if (aesKey) {
  3212. // MAP segment encrypted with method AES, when served with
  3213. // HTTP Range, has the unencrypted size specified in the range.
  3214. // See: https://tools.ietf.org/html/draft-pantos-hls-rfc8216bis-08#section-6.3.6
  3215. const length = (endByte + 1) - startByte;
  3216. if (length % 16) {
  3217. endByte += (16 - (length % 16));
  3218. }
  3219. }
  3220. }
  3221. const initSegmentRef = new shaka.media.InitSegmentReference(
  3222. () => absoluteInitSegmentUris,
  3223. startByte,
  3224. endByte,
  3225. /* mediaQuality= */ null,
  3226. /* timescale= */ null,
  3227. /* segmentData= */ null,
  3228. aesKey);
  3229. return initSegmentRef;
  3230. }
  3231. /**
  3232. * Parses one shaka.hls.Segment object into a shaka.media.SegmentReference.
  3233. *
  3234. * @param {shaka.media.InitSegmentReference} initSegmentReference
  3235. * @param {shaka.media.SegmentReference} previousReference
  3236. * @param {!shaka.hls.Segment} hlsSegment
  3237. * @param {number} startTime
  3238. * @param {!Map.<string, string>} variables
  3239. * @param {!shaka.hls.Playlist} playlist
  3240. * @param {string} type
  3241. * @param {function():!Array.<string>} getUris
  3242. * @param {shaka.extern.aesKey=} aesKey
  3243. * @return {shaka.media.SegmentReference}
  3244. * @private
  3245. */
  3246. createSegmentReference_(
  3247. initSegmentReference, previousReference, hlsSegment, startTime,
  3248. variables, playlist, type, getUris, aesKey) {
  3249. const HlsParser = shaka.hls.HlsParser;
  3250. const getMimeType = (uri) => {
  3251. const parsedUri = new goog.Uri(uri);
  3252. const extension = parsedUri.getPath().split('.').pop();
  3253. const map = HlsParser.EXTENSION_MAP_BY_CONTENT_TYPE_[type];
  3254. let mimeType = map[extension];
  3255. if (!mimeType) {
  3256. mimeType = HlsParser.RAW_FORMATS_TO_MIME_TYPES_[extension];
  3257. }
  3258. return mimeType;
  3259. };
  3260. const tags = hlsSegment.tags;
  3261. const extinfTag =
  3262. shaka.hls.Utils.getFirstTagWithName(tags, 'EXTINF');
  3263. let endTime = 0;
  3264. let startByte = 0;
  3265. let endByte = null;
  3266. if (hlsSegment.partialSegments.length) {
  3267. this.manifest_.isLowLatency = true;
  3268. }
  3269. let syncTime = null;
  3270. if (!this.config_.hls.ignoreManifestProgramDateTime) {
  3271. const dateTimeTag =
  3272. shaka.hls.Utils.getFirstTagWithName(tags, 'EXT-X-PROGRAM-DATE-TIME');
  3273. if (dateTimeTag && dateTimeTag.value) {
  3274. syncTime = shaka.util.TXml.parseDate(dateTimeTag.value);
  3275. goog.asserts.assert(syncTime != null,
  3276. 'EXT-X-PROGRAM-DATE-TIME format not valid');
  3277. this.usesProgramDateTime_ = true;
  3278. }
  3279. }
  3280. let status = shaka.media.SegmentReference.Status.AVAILABLE;
  3281. if (shaka.hls.Utils.getFirstTagWithName(tags, 'EXT-X-GAP')) {
  3282. this.manifest_.gapCount++;
  3283. status = shaka.media.SegmentReference.Status.MISSING;
  3284. }
  3285. if (!extinfTag) {
  3286. if (hlsSegment.partialSegments.length == 0) {
  3287. // EXTINF tag must be available if the segment has no partial segments.
  3288. throw new shaka.util.Error(
  3289. shaka.util.Error.Severity.CRITICAL,
  3290. shaka.util.Error.Category.MANIFEST,
  3291. shaka.util.Error.Code.HLS_REQUIRED_TAG_MISSING, 'EXTINF');
  3292. } else if (!this.lowLatencyMode_) {
  3293. // Without EXTINF and without low-latency mode, partial segments get
  3294. // ignored.
  3295. return null;
  3296. }
  3297. }
  3298. // Create SegmentReferences for the partial segments.
  3299. let partialSegmentRefs = [];
  3300. // Optimization for LL-HLS with byterange
  3301. // More info in https://tinyurl.com/hls-open-byte-range
  3302. let segmentWithByteRangeOptimization = false;
  3303. let getUrisOptimization = null;
  3304. let somePartialSegmentWithGap = false;
  3305. let isPreloadSegment = false;
  3306. if (this.lowLatencyMode_ && hlsSegment.partialSegments.length) {
  3307. const byterangeOptimizationSupport =
  3308. initSegmentReference && window.ReadableStream &&
  3309. this.config_.hls.allowLowLatencyByteRangeOptimization;
  3310. let partialSyncTime = syncTime;
  3311. for (let i = 0; i < hlsSegment.partialSegments.length; i++) {
  3312. const item = hlsSegment.partialSegments[i];
  3313. const pPreviousReference = i == 0 ?
  3314. previousReference : partialSegmentRefs[partialSegmentRefs.length - 1];
  3315. const pStartTime = (i == 0) ? startTime : pPreviousReference.endTime;
  3316. // If DURATION is missing from this partial segment, use the target
  3317. // partial duration from the top of the playlist, which is a required
  3318. // attribute for content with partial segments.
  3319. const pDuration = Number(item.getAttributeValue('DURATION')) ||
  3320. this.partialTargetDuration_;
  3321. // If for some reason we have neither an explicit duration, nor a target
  3322. // partial duration, we should SKIP this partial segment to avoid
  3323. // duplicating content in the presentation timeline.
  3324. if (!pDuration) {
  3325. continue;
  3326. }
  3327. const pEndTime = pStartTime + pDuration;
  3328. let pStartByte = 0;
  3329. let pEndByte = null;
  3330. if (item.name == 'EXT-X-PRELOAD-HINT') {
  3331. // A preload hinted partial segment may have byterange start info.
  3332. const pByterangeStart = item.getAttributeValue('BYTERANGE-START');
  3333. pStartByte = pByterangeStart ? Number(pByterangeStart) : 0;
  3334. // A preload hinted partial segment may have byterange length info.
  3335. const pByterangeLength = item.getAttributeValue('BYTERANGE-LENGTH');
  3336. if (pByterangeLength) {
  3337. pEndByte = pStartByte + Number(pByterangeLength) - 1;
  3338. } else if (pStartByte) {
  3339. // If we have a non-zero start byte, but no end byte, follow the
  3340. // recommendation of https://tinyurl.com/hls-open-byte-range and
  3341. // set the end byte explicitly to a large integer.
  3342. pEndByte = Number.MAX_SAFE_INTEGER;
  3343. }
  3344. } else {
  3345. const pByterange = item.getAttributeValue('BYTERANGE');
  3346. [pStartByte, pEndByte] =
  3347. this.parseByteRange_(pPreviousReference, pByterange);
  3348. }
  3349. const pUri = item.getAttributeValue('URI');
  3350. if (!pUri) {
  3351. continue;
  3352. }
  3353. let partialStatus = shaka.media.SegmentReference.Status.AVAILABLE;
  3354. if (item.getAttributeValue('GAP') == 'YES') {
  3355. this.manifest_.gapCount++;
  3356. partialStatus = shaka.media.SegmentReference.Status.MISSING;
  3357. somePartialSegmentWithGap = true;
  3358. }
  3359. let uris = null;
  3360. const getPartialUris = () => {
  3361. if (uris == null) {
  3362. goog.asserts.assert(pUri, 'Partial uri should be defined!');
  3363. uris = shaka.hls.Utils.constructSegmentUris(
  3364. getUris(), pUri, variables);
  3365. }
  3366. return uris;
  3367. };
  3368. if (byterangeOptimizationSupport &&
  3369. pStartByte >= 0 && pEndByte != null) {
  3370. getUrisOptimization = getPartialUris;
  3371. segmentWithByteRangeOptimization = true;
  3372. }
  3373. const partial = new shaka.media.SegmentReference(
  3374. pStartTime,
  3375. pEndTime,
  3376. getPartialUris,
  3377. pStartByte,
  3378. pEndByte,
  3379. initSegmentReference,
  3380. /* timestampOffset= */ 0,
  3381. /* appendWindowStart= */ 0,
  3382. /* appendWindowEnd= */ Infinity,
  3383. /* partialReferences= */ [],
  3384. /* tilesLayout= */ '',
  3385. /* tileDuration= */ null,
  3386. partialSyncTime,
  3387. partialStatus,
  3388. aesKey);
  3389. if (item.name == 'EXT-X-PRELOAD-HINT') {
  3390. partial.markAsPreload();
  3391. isPreloadSegment = true;
  3392. }
  3393. // The spec doesn't say that we can assume INDEPENDENT=YES for the
  3394. // first partial segment. It does call the flag "optional", though, and
  3395. // that cases where there are no such flags on any partial segments, it
  3396. // is sensible to assume the first one is independent.
  3397. if (item.getAttributeValue('INDEPENDENT') != 'YES' && i > 0) {
  3398. partial.markAsNonIndependent();
  3399. }
  3400. const pMimeType = getMimeType(pUri);
  3401. if (pMimeType) {
  3402. partial.mimeType = pMimeType;
  3403. if (HlsParser.MIME_TYPES_WITHOUT_INIT_SEGMENT_.has(pMimeType)) {
  3404. partial.initSegmentReference = null;
  3405. }
  3406. }
  3407. partialSegmentRefs.push(partial);
  3408. if (partialSyncTime) {
  3409. partialSyncTime += pDuration;
  3410. }
  3411. } // for-loop of hlsSegment.partialSegments
  3412. }
  3413. // If the segment has EXTINF tag, set the segment's end time, start byte
  3414. // and end byte based on the duration and byterange information.
  3415. // Otherwise, calculate the end time, start / end byte based on its partial
  3416. // segments.
  3417. // Note that the sum of partial segments durations may be slightly different
  3418. // from the parent segment's duration. In this case, use the duration from
  3419. // the parent segment tag.
  3420. if (extinfTag) {
  3421. // The EXTINF tag format is '#EXTINF:<duration>,[<title>]'.
  3422. // We're interested in the duration part.
  3423. const extinfValues = extinfTag.value.split(',');
  3424. const duration = Number(extinfValues[0]);
  3425. // Skip segments without duration
  3426. if (duration == 0) {
  3427. return null;
  3428. }
  3429. endTime = startTime + duration;
  3430. } else if (partialSegmentRefs.length) {
  3431. endTime = partialSegmentRefs[partialSegmentRefs.length - 1].endTime;
  3432. } else {
  3433. // Skip segments without duration and without partialsegments
  3434. return null;
  3435. }
  3436. if (segmentWithByteRangeOptimization) {
  3437. // We cannot optimize segments with gaps, or with a start byte that is
  3438. // not 0.
  3439. if (somePartialSegmentWithGap || partialSegmentRefs[0].startByte != 0) {
  3440. segmentWithByteRangeOptimization = false;
  3441. getUrisOptimization = null;
  3442. } else {
  3443. partialSegmentRefs = [];
  3444. }
  3445. }
  3446. // If the segment has EXT-X-BYTERANGE tag, set the start byte and end byte
  3447. // base on the byterange information. If segment has no EXT-X-BYTERANGE tag
  3448. // and has partial segments, set the start byte and end byte base on the
  3449. // partial segments.
  3450. const byterangeTag =
  3451. shaka.hls.Utils.getFirstTagWithName(tags, 'EXT-X-BYTERANGE');
  3452. if (byterangeTag) {
  3453. [startByte, endByte] =
  3454. this.parseByteRange_(previousReference, byterangeTag.value);
  3455. } else if (partialSegmentRefs.length) {
  3456. startByte = partialSegmentRefs[0].startByte;
  3457. endByte = partialSegmentRefs[partialSegmentRefs.length - 1].endByte;
  3458. }
  3459. let tilesLayout = '';
  3460. let tileDuration = null;
  3461. if (type == shaka.util.ManifestParserUtils.ContentType.IMAGE) {
  3462. // By default in HLS the tilesLayout is 1x1
  3463. tilesLayout = '1x1';
  3464. const tilesTag =
  3465. shaka.hls.Utils.getFirstTagWithName(tags, 'EXT-X-TILES');
  3466. if (tilesTag) {
  3467. tilesLayout = tilesTag.getRequiredAttrValue('LAYOUT');
  3468. const duration = tilesTag.getAttributeValue('DURATION');
  3469. if (duration) {
  3470. tileDuration = Number(duration);
  3471. }
  3472. }
  3473. }
  3474. let uris = null;
  3475. const getSegmentUris = () => {
  3476. if (getUrisOptimization) {
  3477. return getUrisOptimization();
  3478. }
  3479. if (uris == null) {
  3480. uris = shaka.hls.Utils.constructSegmentUris(getUris(),
  3481. hlsSegment.verbatimSegmentUri, variables);
  3482. }
  3483. return uris || [];
  3484. };
  3485. const allPartialSegments = partialSegmentRefs.length > 0 &&
  3486. !!hlsSegment.verbatimSegmentUri;
  3487. const reference = new shaka.media.SegmentReference(
  3488. startTime,
  3489. endTime,
  3490. getSegmentUris,
  3491. startByte,
  3492. endByte,
  3493. initSegmentReference,
  3494. /* timestampOffset= */ 0,
  3495. /* appendWindowStart= */ 0,
  3496. /* appendWindowEnd= */ Infinity,
  3497. partialSegmentRefs,
  3498. tilesLayout,
  3499. tileDuration,
  3500. syncTime,
  3501. status,
  3502. aesKey,
  3503. allPartialSegments,
  3504. );
  3505. const mimeType = getMimeType(hlsSegment.verbatimSegmentUri);
  3506. if (mimeType) {
  3507. reference.mimeType = mimeType;
  3508. if (HlsParser.MIME_TYPES_WITHOUT_INIT_SEGMENT_.has(mimeType)) {
  3509. reference.initSegmentReference = null;
  3510. }
  3511. }
  3512. if (segmentWithByteRangeOptimization) {
  3513. this.lowLatencyByterangeOptimization_ = true;
  3514. reference.markAsByterangeOptimization();
  3515. if (isPreloadSegment) {
  3516. reference.markAsPreload();
  3517. }
  3518. }
  3519. return reference;
  3520. }
  3521. /**
  3522. * Parse the startByte and endByte.
  3523. * @param {shaka.media.SegmentReference} previousReference
  3524. * @param {?string} byterange
  3525. * @return {!Array.<number>} An array with the start byte and end byte.
  3526. * @private
  3527. */
  3528. parseByteRange_(previousReference, byterange) {
  3529. let startByte = 0;
  3530. let endByte = null;
  3531. // If BYTERANGE is not specified, the segment consists of the entire
  3532. // resource.
  3533. if (byterange) {
  3534. const blocks = byterange.split('@');
  3535. const byteLength = Number(blocks[0]);
  3536. if (blocks[1]) {
  3537. startByte = Number(blocks[1]);
  3538. } else {
  3539. goog.asserts.assert(previousReference,
  3540. 'Cannot refer back to previous HLS segment!');
  3541. startByte = previousReference.endByte + 1;
  3542. }
  3543. endByte = startByte + byteLength - 1;
  3544. }
  3545. return [startByte, endByte];
  3546. }
  3547. /**
  3548. * @param {!Array.<!shaka.hls.Tag>} tags
  3549. * @param {string} contentType
  3550. * @param {!Map.<string, string>} variables
  3551. * @param {function():!Array.<string>} getUris
  3552. * @private
  3553. */
  3554. processDateRangeTags_(tags, contentType, variables, getUris) {
  3555. const ContentType = shaka.util.ManifestParserUtils.ContentType;
  3556. if (contentType != ContentType.VIDEO && contentType != ContentType.AUDIO) {
  3557. // DATE-RANGE should only appear in AUDIO or VIDEO playlists.
  3558. // We ignore those that appear in other playlists.
  3559. return;
  3560. }
  3561. const Utils = shaka.hls.Utils;
  3562. const initialProgramDateTime =
  3563. this.presentationTimeline_.getInitialProgramDateTime();
  3564. if (!initialProgramDateTime ||
  3565. this.ignoreManifestProgramDateTimeFor_(contentType)) {
  3566. return;
  3567. }
  3568. let dateRangeTags =
  3569. shaka.hls.Utils.filterTagsByName(tags, 'EXT-X-DATERANGE');
  3570. dateRangeTags = dateRangeTags.sort((a, b) => {
  3571. const aStartDateValue = a.getRequiredAttrValue('START-DATE');
  3572. const bStartDateValue = b.getRequiredAttrValue('START-DATE');
  3573. if (aStartDateValue < bStartDateValue) {
  3574. return -1;
  3575. }
  3576. if (aStartDateValue > bStartDateValue) {
  3577. return 1;
  3578. }
  3579. return 0;
  3580. });
  3581. for (let i = 0; i < dateRangeTags.length; i++) {
  3582. const tag = dateRangeTags[i];
  3583. try {
  3584. const id = tag.getRequiredAttrValue('ID');
  3585. if (this.dateRangeIdsEmitted_.has(id)) {
  3586. continue;
  3587. }
  3588. const startDateValue = tag.getRequiredAttrValue('START-DATE');
  3589. const startDate = shaka.util.TXml.parseDate(startDateValue);
  3590. if (isNaN(startDate)) {
  3591. // Invalid START-DATE
  3592. continue;
  3593. }
  3594. goog.asserts.assert(startDate != null,
  3595. 'Start date should not be null!');
  3596. const startTime = Math.max(0, startDate - initialProgramDateTime);
  3597. let endTime = null;
  3598. const endDateValue = tag.getAttributeValue('END-DATE');
  3599. if (endDateValue) {
  3600. const endDate = shaka.util.TXml.parseDate(endDateValue);
  3601. if (!isNaN(endDate)) {
  3602. goog.asserts.assert(endDate != null,
  3603. 'End date should not be null!');
  3604. endTime = endDate - initialProgramDateTime;
  3605. if (endTime < 0) {
  3606. // Date range in the past
  3607. continue;
  3608. }
  3609. }
  3610. }
  3611. if (endTime == null) {
  3612. const durationValue = tag.getAttributeValue('DURATION') ||
  3613. tag.getAttributeValue('PLANNED-DURATION');
  3614. if (durationValue) {
  3615. const duration = parseFloat(durationValue);
  3616. if (!isNaN(duration)) {
  3617. endTime = startTime + duration;
  3618. }
  3619. const realEndTime = startDate - initialProgramDateTime + duration;
  3620. if (realEndTime < 0) {
  3621. // Date range in the past
  3622. continue;
  3623. }
  3624. }
  3625. }
  3626. const type =
  3627. tag.getAttributeValue('CLASS') || 'com.apple.quicktime.HLS';
  3628. const endOnNext = tag.getAttributeValue('END-ON-NEXT') == 'YES';
  3629. if (endTime == null && endOnNext) {
  3630. for (let j = i + 1; j < dateRangeTags.length; j++) {
  3631. const otherDateRangeType =
  3632. dateRangeTags[j].getAttributeValue('CLASS') ||
  3633. 'com.apple.quicktime.HLS';
  3634. if (type != otherDateRangeType) {
  3635. continue;
  3636. }
  3637. const otherDateRangeStartDateValue =
  3638. dateRangeTags[j].getRequiredAttrValue('START-DATE');
  3639. const otherDateRangeStartDate =
  3640. shaka.util.TXml.parseDate(otherDateRangeStartDateValue);
  3641. if (isNaN(otherDateRangeStartDate)) {
  3642. // Invalid START-DATE
  3643. continue;
  3644. }
  3645. if (otherDateRangeStartDate &&
  3646. otherDateRangeStartDate > startDate) {
  3647. endTime = Math.max(0,
  3648. otherDateRangeStartDate - initialProgramDateTime);
  3649. break;
  3650. }
  3651. }
  3652. if (endTime == null) {
  3653. // Since we cannot know when it ends, we omit it for now and in the
  3654. // future with an update we will be able to have more information.
  3655. continue;
  3656. }
  3657. }
  3658. // Exclude these attributes from the metadata since they already go into
  3659. // other fields (eg: startTime or endTime) or are not necessary..
  3660. const excludedAttributes = [
  3661. 'CLASS',
  3662. 'START-DATE',
  3663. 'END-DATE',
  3664. 'DURATION',
  3665. 'END-ON-NEXT',
  3666. ];
  3667. /* @type {!Array.<shaka.extern.MetadataFrame>} */
  3668. const values = [];
  3669. for (const attribute of tag.attributes) {
  3670. if (excludedAttributes.includes(attribute.name)) {
  3671. continue;
  3672. }
  3673. let data = Utils.variableSubstitution(attribute.value, variables);
  3674. if (attribute.name == 'X-ASSET-URI' ||
  3675. attribute.name == 'X-ASSET-LIST') {
  3676. data = Utils.constructSegmentUris(
  3677. getUris(), attribute.value, variables)[0];
  3678. }
  3679. const metadataFrame = {
  3680. key: attribute.name,
  3681. description: '',
  3682. data,
  3683. mimeType: null,
  3684. pictureType: null,
  3685. };
  3686. values.push(metadataFrame);
  3687. }
  3688. // ID is always required. So we need more than 1 value.
  3689. if (values.length > 1) {
  3690. this.playerInterface_.onMetadata(type, startTime, endTime, values);
  3691. }
  3692. this.dateRangeIdsEmitted_.add(id);
  3693. } catch (e) {
  3694. shaka.log.warning('Ignorando DATERANGE con errores', tag.toString());
  3695. }
  3696. }
  3697. }
  3698. /**
  3699. * Parses shaka.hls.Segment objects into shaka.media.SegmentReferences and
  3700. * get the bandwidth necessary for this segments If it's defined in the
  3701. * playlist.
  3702. *
  3703. * @param {!shaka.hls.Playlist} playlist
  3704. * @param {!Map.<number, number>} mediaSequenceToStartTime
  3705. * @param {!Map.<string, string>} variables
  3706. * @param {function():!Array.<string>} getUris
  3707. * @param {string} type
  3708. * @return {{segments: !Array.<!shaka.media.SegmentReference>,
  3709. * bandwidth: (number|undefined)}}
  3710. * @private
  3711. */
  3712. createSegments_(playlist, mediaSequenceToStartTime, variables,
  3713. getUris, type) {
  3714. /** @type {Array.<!shaka.hls.Segment>} */
  3715. const hlsSegments = playlist.segments;
  3716. goog.asserts.assert(hlsSegments.length, 'Playlist should have segments!');
  3717. /** @type {shaka.media.InitSegmentReference} */
  3718. let initSegmentRef;
  3719. /** @type {shaka.extern.aesKey|undefined} */
  3720. let aesKey = undefined;
  3721. let discontinuitySequence = shaka.hls.Utils.getFirstTagWithNameAsNumber(
  3722. playlist.tags, 'EXT-X-DISCONTINUITY-SEQUENCE', -1);
  3723. const mediaSequenceNumber = shaka.hls.Utils.getFirstTagWithNameAsNumber(
  3724. playlist.tags, 'EXT-X-MEDIA-SEQUENCE', 0);
  3725. const skipTag = shaka.hls.Utils.getFirstTagWithName(
  3726. playlist.tags, 'EXT-X-SKIP');
  3727. const skippedSegments =
  3728. skipTag ? Number(skipTag.getAttributeValue('SKIPPED-SEGMENTS')) : 0;
  3729. let position = mediaSequenceNumber + skippedSegments;
  3730. let firstStartTime = 0;
  3731. // For live stream, use the cached value in the mediaSequenceToStartTime
  3732. // map if available.
  3733. if (this.isLive_() && mediaSequenceToStartTime.has(position)) {
  3734. firstStartTime = mediaSequenceToStartTime.get(position);
  3735. }
  3736. // This is for recovering from disconnects.
  3737. if (firstStartTime === 0 &&
  3738. this.presentationType_ == shaka.hls.HlsParser.PresentationType_.LIVE &&
  3739. mediaSequenceToStartTime.size > 0 &&
  3740. !mediaSequenceToStartTime.has(position) &&
  3741. this.presentationTimeline_.getPresentationStartTime() != null) {
  3742. firstStartTime = this.presentationTimeline_.getSegmentAvailabilityStart();
  3743. }
  3744. /** @type {!Array.<!shaka.media.SegmentReference>} */
  3745. const references = [];
  3746. let previousReference = null;
  3747. /** @type {!Array.<{bitrate: number, duration: number}>} */
  3748. const bitrates = [];
  3749. for (let i = 0; i < hlsSegments.length; i++) {
  3750. const item = hlsSegments[i];
  3751. const startTime =
  3752. (i == 0) ? firstStartTime : previousReference.endTime;
  3753. position = mediaSequenceNumber + skippedSegments + i;
  3754. const discontinuityTag = shaka.hls.Utils.getFirstTagWithName(
  3755. item.tags, 'EXT-X-DISCONTINUITY');
  3756. if (discontinuityTag) {
  3757. discontinuitySequence++;
  3758. }
  3759. // Apply new AES tags as you see them, keeping a running total.
  3760. for (const drmTag of item.tags) {
  3761. if (drmTag.name == 'EXT-X-KEY') {
  3762. if (this.isAesMethod_(drmTag.getRequiredAttrValue('METHOD'))) {
  3763. aesKey =
  3764. this.parseAESDrmTag_(drmTag, playlist, getUris, variables);
  3765. } else {
  3766. aesKey = undefined;
  3767. }
  3768. }
  3769. }
  3770. mediaSequenceToStartTime.set(position, startTime);
  3771. initSegmentRef = this.getInitSegmentReference_(playlist,
  3772. item.tags, getUris, variables);
  3773. // If the stream is low latency and the user has not configured the
  3774. // lowLatencyMode, but if it has been configured to activate the
  3775. // lowLatencyMode if a stream of this type is detected, we automatically
  3776. // activate the lowLatencyMode.
  3777. if (!this.lowLatencyMode_) {
  3778. const autoLowLatencyMode = this.playerInterface_.isAutoLowLatencyMode();
  3779. if (autoLowLatencyMode) {
  3780. this.playerInterface_.enableLowLatencyMode();
  3781. this.lowLatencyMode_ = this.playerInterface_.isLowLatencyMode();
  3782. }
  3783. }
  3784. const reference = this.createSegmentReference_(
  3785. initSegmentRef,
  3786. previousReference,
  3787. item,
  3788. startTime,
  3789. variables,
  3790. playlist,
  3791. type,
  3792. getUris,
  3793. aesKey);
  3794. if (reference) {
  3795. const bitrate = shaka.hls.Utils.getFirstTagWithNameAsNumber(
  3796. item.tags, 'EXT-X-BITRATE');
  3797. if (bitrate) {
  3798. bitrates.push({
  3799. bitrate,
  3800. duration: reference.endTime - reference.startTime,
  3801. });
  3802. } else if (bitrates.length) {
  3803. // It applies to every segment between it and the next EXT-X-BITRATE,
  3804. // so we use the latest bitrate value
  3805. const prevBitrate = bitrates.pop();
  3806. prevBitrate.duration += reference.endTime - reference.startTime;
  3807. bitrates.push(prevBitrate);
  3808. }
  3809. previousReference = reference;
  3810. reference.discontinuitySequence = discontinuitySequence;
  3811. if (this.ignoreManifestProgramDateTimeFor_(type) &&
  3812. this.minSequenceNumber_ != null &&
  3813. position < this.minSequenceNumber_) {
  3814. // This segment is ignored as part of our fallback synchronization
  3815. // method.
  3816. } else {
  3817. references.push(reference);
  3818. }
  3819. }
  3820. }
  3821. let bandwidth = undefined;
  3822. if (bitrates.length) {
  3823. const duration = bitrates.reduce((sum, value) => {
  3824. return sum + value.duration;
  3825. }, 0);
  3826. bandwidth = Math.round(bitrates.reduce((sum, value) => {
  3827. return sum + value.bitrate * value.duration;
  3828. }, 0) / duration * 1000);
  3829. }
  3830. // If some segments have sync times, but not all, extrapolate the sync
  3831. // times of the ones with none.
  3832. const someSyncTime = references.some((ref) => ref.syncTime != null);
  3833. if (someSyncTime) {
  3834. for (let i = 0; i < references.length; i++) {
  3835. const reference = references[i];
  3836. if (reference.syncTime != null) {
  3837. // No need to extrapolate.
  3838. continue;
  3839. }
  3840. // Find the nearest segment with syncTime, in either direction.
  3841. // This looks forward and backward simultaneously, keeping track of what
  3842. // to offset the syncTime it finds by as it goes.
  3843. let forwardAdd = 0;
  3844. let forwardI = i;
  3845. /**
  3846. * Look forwards one reference at a time, summing all durations as we
  3847. * go, until we find a reference with a syncTime to use as a basis.
  3848. * This DOES count the original reference, but DOESN'T count the first
  3849. * reference with a syncTime (as we approach it from behind).
  3850. * @return {?number}
  3851. */
  3852. const lookForward = () => {
  3853. const other = references[forwardI];
  3854. if (other) {
  3855. if (other.syncTime != null) {
  3856. return other.syncTime + forwardAdd;
  3857. }
  3858. forwardAdd -= other.endTime - other.startTime;
  3859. forwardI += 1;
  3860. }
  3861. return null;
  3862. };
  3863. let backwardAdd = 0;
  3864. let backwardI = i;
  3865. /**
  3866. * Look backwards one reference at a time, summing all durations as we
  3867. * go, until we find a reference with a syncTime to use as a basis.
  3868. * This DOESN'T count the original reference, but DOES count the first
  3869. * reference with a syncTime (as we approach it from ahead).
  3870. * @return {?number}
  3871. */
  3872. const lookBackward = () => {
  3873. const other = references[backwardI];
  3874. if (other) {
  3875. if (other != reference) {
  3876. backwardAdd += other.endTime - other.startTime;
  3877. }
  3878. if (other.syncTime != null) {
  3879. return other.syncTime + backwardAdd;
  3880. }
  3881. backwardI -= 1;
  3882. }
  3883. return null;
  3884. };
  3885. while (reference.syncTime == null) {
  3886. reference.syncTime = lookBackward();
  3887. if (reference.syncTime == null) {
  3888. reference.syncTime = lookForward();
  3889. }
  3890. }
  3891. }
  3892. }
  3893. // Split the sync times properly among partial segments.
  3894. if (someSyncTime) {
  3895. for (const reference of references) {
  3896. let syncTime = reference.syncTime;
  3897. for (const partial of reference.partialReferences) {
  3898. partial.syncTime = syncTime;
  3899. syncTime += partial.endTime - partial.startTime;
  3900. }
  3901. }
  3902. }
  3903. // lowestSyncTime is a value from a previous playlist update. Use it to
  3904. // set reference start times. If this is the first playlist parse, we will
  3905. // skip this step, and wait until we have sync time across stream types.
  3906. const lowestSyncTime = this.lowestSyncTime_;
  3907. if (someSyncTime && lowestSyncTime != Infinity) {
  3908. if (!this.ignoreManifestProgramDateTimeFor_(type)) {
  3909. for (const reference of references) {
  3910. reference.syncAgainst(lowestSyncTime);
  3911. }
  3912. }
  3913. }
  3914. return {
  3915. segments: references,
  3916. bandwidth,
  3917. };
  3918. }
  3919. /**
  3920. * Attempts to guess stream's mime type based on content type and URI.
  3921. *
  3922. * @param {string} contentType
  3923. * @param {string} codecs
  3924. * @return {?string}
  3925. * @private
  3926. */
  3927. guessMimeTypeBeforeLoading_(contentType, codecs) {
  3928. if (contentType == shaka.util.ManifestParserUtils.ContentType.TEXT) {
  3929. if (codecs == 'vtt' || codecs == 'wvtt') {
  3930. // If codecs is 'vtt', it's WebVTT.
  3931. return 'text/vtt';
  3932. } else if (codecs && codecs !== '') {
  3933. // Otherwise, assume MP4-embedded text, since text-based formats tend
  3934. // not to have a codecs string at all.
  3935. return 'application/mp4';
  3936. }
  3937. }
  3938. if (contentType == shaka.util.ManifestParserUtils.ContentType.IMAGE) {
  3939. if (!codecs || codecs == 'jpeg') {
  3940. return 'image/jpeg';
  3941. }
  3942. }
  3943. if (contentType == shaka.util.ManifestParserUtils.ContentType.AUDIO) {
  3944. // See: https://bugs.chromium.org/p/chromium/issues/detail?id=489520
  3945. if (codecs == 'mp4a.40.34') {
  3946. return 'audio/mpeg';
  3947. }
  3948. }
  3949. if (codecs == 'mjpg') {
  3950. return 'application/mp4';
  3951. }
  3952. // Not enough information to guess from the content type and codecs.
  3953. return null;
  3954. }
  3955. /**
  3956. * Get a fallback mime type for the content. Used if all the better methods
  3957. * for determining the mime type have failed.
  3958. *
  3959. * @param {string} contentType
  3960. * @return {string}
  3961. * @private
  3962. */
  3963. guessMimeTypeFallback_(contentType) {
  3964. if (contentType == shaka.util.ManifestParserUtils.ContentType.TEXT) {
  3965. // If there was no codecs string and no content-type, assume HLS text
  3966. // streams are WebVTT.
  3967. return 'text/vtt';
  3968. }
  3969. // If the HLS content is lacking in both MIME type metadata and
  3970. // segment file extensions, we fall back to assuming it's MP4.
  3971. const map = shaka.hls.HlsParser.EXTENSION_MAP_BY_CONTENT_TYPE_[contentType];
  3972. return map['mp4'];
  3973. }
  3974. /**
  3975. * @param {!Array.<!shaka.media.SegmentReference>} segments
  3976. * @return {{segment: !shaka.media.SegmentReference, segmentIndex: number}}
  3977. * @private
  3978. */
  3979. getAvailableSegment_(segments) {
  3980. goog.asserts.assert(segments.length, 'Should have segments!');
  3981. // If you wait long enough, requesting the first segment can fail
  3982. // because it has fallen off the left edge of DVR, so to be safer,
  3983. // let's request the middle segment.
  3984. let segmentIndex = this.isLive_() ?
  3985. Math.trunc((segments.length - 1) / 2) : 0;
  3986. let segment = segments[segmentIndex];
  3987. while (segment.getStatus() == shaka.media.SegmentReference.Status.MISSING &&
  3988. (segmentIndex + 1) < segments.length) {
  3989. segmentIndex ++;
  3990. segment = segments[segmentIndex];
  3991. }
  3992. return {segment, segmentIndex};
  3993. }
  3994. /**
  3995. * Attempts to guess stream's mime type.
  3996. *
  3997. * @param {string} contentType
  3998. * @param {string} codecs
  3999. * @param {!Array.<!shaka.media.SegmentReference>} segments
  4000. * @return {!Promise.<string>}
  4001. * @private
  4002. */
  4003. async guessMimeType_(contentType, codecs, segments) {
  4004. const HlsParser = shaka.hls.HlsParser;
  4005. const requestType = shaka.net.NetworkingEngine.RequestType.SEGMENT;
  4006. const {segment} = this.getAvailableSegment_(segments);
  4007. if (segment.status == shaka.media.SegmentReference.Status.MISSING) {
  4008. return this.guessMimeTypeFallback_(contentType);
  4009. }
  4010. const segmentUris = segment.getUris();
  4011. const parsedUri = new goog.Uri(segmentUris[0]);
  4012. const extension = parsedUri.getPath().split('.').pop();
  4013. const map = HlsParser.EXTENSION_MAP_BY_CONTENT_TYPE_[contentType];
  4014. let mimeType = map[extension];
  4015. if (mimeType) {
  4016. return mimeType;
  4017. }
  4018. mimeType = HlsParser.RAW_FORMATS_TO_MIME_TYPES_[extension];
  4019. if (mimeType) {
  4020. return mimeType;
  4021. }
  4022. // The extension map didn't work, so guess based on codecs.
  4023. mimeType = this.guessMimeTypeBeforeLoading_(contentType, codecs);
  4024. if (mimeType) {
  4025. return mimeType;
  4026. }
  4027. // If unable to guess mime type, request a segment and try getting it
  4028. // from the response.
  4029. let contentMimeType;
  4030. const type = shaka.net.NetworkingEngine.AdvancedRequestType.MEDIA_SEGMENT;
  4031. const headRequest = shaka.net.NetworkingEngine.makeRequest(
  4032. segmentUris, this.config_.retryParameters);
  4033. try {
  4034. headRequest.method = 'HEAD';
  4035. const response = await this.makeNetworkRequest_(
  4036. headRequest, requestType, {type}).promise;
  4037. contentMimeType = response.headers['content-type'];
  4038. } catch (error) {
  4039. if (error &&
  4040. (error.code == shaka.util.Error.Code.HTTP_ERROR ||
  4041. error.code == shaka.util.Error.Code.BAD_HTTP_STATUS)) {
  4042. headRequest.method = 'GET';
  4043. const response = await this.makeNetworkRequest_(
  4044. headRequest, requestType, {type}).promise;
  4045. contentMimeType = response.headers['content-type'];
  4046. }
  4047. }
  4048. if (contentMimeType) {
  4049. // Split the MIME type in case the server sent additional parameters.
  4050. return contentMimeType.toLowerCase().split(';')[0];
  4051. }
  4052. return this.guessMimeTypeFallback_(contentType);
  4053. }
  4054. /**
  4055. * Returns a tag with a given name.
  4056. * Throws an error if tag was not found.
  4057. *
  4058. * @param {!Array.<shaka.hls.Tag>} tags
  4059. * @param {string} tagName
  4060. * @return {!shaka.hls.Tag}
  4061. * @private
  4062. */
  4063. getRequiredTag_(tags, tagName) {
  4064. const tag = shaka.hls.Utils.getFirstTagWithName(tags, tagName);
  4065. if (!tag) {
  4066. throw new shaka.util.Error(
  4067. shaka.util.Error.Severity.CRITICAL,
  4068. shaka.util.Error.Category.MANIFEST,
  4069. shaka.util.Error.Code.HLS_REQUIRED_TAG_MISSING, tagName);
  4070. }
  4071. return tag;
  4072. }
  4073. /**
  4074. * @param {shaka.extern.Stream} stream
  4075. * @param {?string} width
  4076. * @param {?string} height
  4077. * @param {?string} frameRate
  4078. * @param {?string} videoRange
  4079. * @param {?string} videoLayout
  4080. * @param {?string} colorGamut
  4081. * @private
  4082. */
  4083. addVideoAttributes_(stream, width, height, frameRate, videoRange,
  4084. videoLayout, colorGamut) {
  4085. if (stream) {
  4086. stream.width = Number(width) || undefined;
  4087. stream.height = Number(height) || undefined;
  4088. stream.frameRate = Number(frameRate) || undefined;
  4089. stream.hdr = videoRange || undefined;
  4090. stream.videoLayout = videoLayout || undefined;
  4091. stream.colorGamut = colorGamut || undefined;
  4092. }
  4093. }
  4094. /**
  4095. * Makes a network request for the manifest and returns a Promise
  4096. * with the resulting data.
  4097. *
  4098. * @param {!Array.<string>} uris
  4099. * @param {boolean=} isPlaylist
  4100. * @return {!shaka.net.NetworkingEngine.PendingRequest}
  4101. * @private
  4102. */
  4103. requestManifest_(uris, isPlaylist) {
  4104. const requestType = shaka.net.NetworkingEngine.RequestType.MANIFEST;
  4105. const request = shaka.net.NetworkingEngine.makeRequest(
  4106. uris, this.config_.retryParameters);
  4107. const type = isPlaylist ?
  4108. shaka.net.NetworkingEngine.AdvancedRequestType.MEDIA_PLAYLIST :
  4109. shaka.net.NetworkingEngine.AdvancedRequestType.MASTER_PLAYLIST;
  4110. return this.makeNetworkRequest_(request, requestType, {type});
  4111. }
  4112. /**
  4113. * Called when the update timer ticks. Because parsing a manifest is async,
  4114. * this method is async. To work with this, this method will schedule the next
  4115. * update when it finished instead of using a repeating-start.
  4116. *
  4117. * @return {!Promise}
  4118. * @private
  4119. */
  4120. async onUpdate_() {
  4121. shaka.log.info('Updating manifest...');
  4122. goog.asserts.assert(
  4123. this.getUpdatePlaylistDelay_() > 0,
  4124. 'We should only call |onUpdate_| when we are suppose to be updating.');
  4125. // Detect a call to stop()
  4126. if (!this.playerInterface_) {
  4127. return;
  4128. }
  4129. try {
  4130. const startTime = Date.now();
  4131. await this.update();
  4132. // Keep track of how long the longest manifest update took.
  4133. const endTime = Date.now();
  4134. // This may have converted to VOD, in which case we stop updating.
  4135. if (this.isLive_()) {
  4136. const updateDuration = (endTime - startTime) / 1000.0;
  4137. this.averageUpdateDuration_.sample(1, updateDuration);
  4138. const delay = this.getUpdatePlaylistDelay_();
  4139. const finalDelay = Math.max(0,
  4140. delay - this.averageUpdateDuration_.getEstimate());
  4141. this.updatePlaylistTimer_.tickAfter(/* seconds= */ finalDelay);
  4142. }
  4143. } catch (error) {
  4144. // Detect a call to stop() during this.update()
  4145. if (!this.playerInterface_) {
  4146. return;
  4147. }
  4148. goog.asserts.assert(error instanceof shaka.util.Error,
  4149. 'Should only receive a Shaka error');
  4150. if (this.config_.raiseFatalErrorOnManifestUpdateRequestFailure) {
  4151. this.playerInterface_.onError(error);
  4152. return;
  4153. }
  4154. // We will retry updating, so override the severity of the error.
  4155. error.severity = shaka.util.Error.Severity.RECOVERABLE;
  4156. this.playerInterface_.onError(error);
  4157. // Try again very soon.
  4158. this.updatePlaylistTimer_.tickAfter(/* seconds= */ 0.1);
  4159. }
  4160. // Detect a call to stop()
  4161. if (!this.playerInterface_) {
  4162. return;
  4163. }
  4164. this.playerInterface_.onManifestUpdated();
  4165. }
  4166. /**
  4167. * @return {boolean}
  4168. * @private
  4169. */
  4170. isLive_() {
  4171. const PresentationType = shaka.hls.HlsParser.PresentationType_;
  4172. return this.presentationType_ != PresentationType.VOD;
  4173. }
  4174. /**
  4175. * @return {number}
  4176. * @private
  4177. */
  4178. getUpdatePlaylistDelay_() {
  4179. // The HLS spec (RFC 8216) states in 6.3.4:
  4180. // "the client MUST wait for at least the target duration before
  4181. // attempting to reload the Playlist file again".
  4182. // For LL-HLS, the server must add a new partial segment to the Playlist
  4183. // every part target duration.
  4184. return this.lastTargetDuration_;
  4185. }
  4186. /**
  4187. * @param {shaka.hls.HlsParser.PresentationType_} type
  4188. * @private
  4189. */
  4190. setPresentationType_(type) {
  4191. this.presentationType_ = type;
  4192. if (this.presentationTimeline_) {
  4193. this.presentationTimeline_.setStatic(!this.isLive_());
  4194. }
  4195. // If this manifest is not for live content, then we have no reason to
  4196. // update it.
  4197. if (!this.isLive_()) {
  4198. this.updatePlaylistTimer_.stop();
  4199. }
  4200. }
  4201. /**
  4202. * Create a networking request. This will manage the request using the
  4203. * parser's operation manager. If the parser has already been stopped, the
  4204. * request will not be made.
  4205. *
  4206. * @param {shaka.extern.Request} request
  4207. * @param {shaka.net.NetworkingEngine.RequestType} type
  4208. * @param {shaka.extern.RequestContext=} context
  4209. * @return {!shaka.net.NetworkingEngine.PendingRequest}
  4210. * @private
  4211. */
  4212. makeNetworkRequest_(request, type, context) {
  4213. if (!this.operationManager_) {
  4214. throw new shaka.util.Error(
  4215. shaka.util.Error.Severity.CRITICAL,
  4216. shaka.util.Error.Category.PLAYER,
  4217. shaka.util.Error.Code.OPERATION_ABORTED);
  4218. }
  4219. if (!context) {
  4220. context = {};
  4221. }
  4222. context.isPreload = this.isPreloadFn_();
  4223. const op = this.playerInterface_.networkingEngine.request(
  4224. type, request, context);
  4225. this.operationManager_.manage(op);
  4226. return op;
  4227. }
  4228. /**
  4229. * @param {string} method
  4230. * @return {boolean}
  4231. * @private
  4232. */
  4233. isAesMethod_(method) {
  4234. return method == 'AES-128' ||
  4235. method == 'AES-256' ||
  4236. method == 'AES-256-CTR';
  4237. }
  4238. /**
  4239. * @param {!shaka.hls.Tag} drmTag
  4240. * @param {string} mimeType
  4241. * @return {?shaka.extern.DrmInfo}
  4242. * @private
  4243. */
  4244. static fairplayDrmParser_(drmTag, mimeType) {
  4245. if (mimeType == 'video/mp2t') {
  4246. throw new shaka.util.Error(
  4247. shaka.util.Error.Severity.CRITICAL,
  4248. shaka.util.Error.Category.MANIFEST,
  4249. shaka.util.Error.Code.HLS_MSE_ENCRYPTED_MP2T_NOT_SUPPORTED);
  4250. }
  4251. if (shaka.util.Platform.isMediaKeysPolyfilled()) {
  4252. throw new shaka.util.Error(
  4253. shaka.util.Error.Severity.CRITICAL,
  4254. shaka.util.Error.Category.MANIFEST,
  4255. shaka.util.Error.Code
  4256. .HLS_MSE_ENCRYPTED_LEGACY_APPLE_MEDIA_KEYS_NOT_SUPPORTED);
  4257. }
  4258. const method = drmTag.getRequiredAttrValue('METHOD');
  4259. const VALID_METHODS = ['SAMPLE-AES', 'SAMPLE-AES-CTR'];
  4260. if (!VALID_METHODS.includes(method)) {
  4261. shaka.log.error('FairPlay in HLS is only supported with [',
  4262. VALID_METHODS.join(', '), '], not', method);
  4263. return null;
  4264. }
  4265. let encryptionScheme = 'cenc';
  4266. if (method == 'SAMPLE-AES') {
  4267. // It should be 'cbcs-1-9' but Safari doesn't support it.
  4268. // See: https://github.com/WebKit/WebKit/blob/main/Source/WebCore/Modules/encryptedmedia/MediaKeyEncryptionScheme.idl
  4269. encryptionScheme = 'cbcs';
  4270. }
  4271. /*
  4272. * Even if we're not able to construct initData through the HLS tag, adding
  4273. * a DRMInfo will allow DRM Engine to request a media key system access
  4274. * with the correct keySystem and initDataType
  4275. */
  4276. const drmInfo = shaka.util.ManifestParserUtils.createDrmInfo(
  4277. 'com.apple.fps', encryptionScheme, [
  4278. {initDataType: 'sinf', initData: new Uint8Array(0), keyId: null},
  4279. ], drmTag.getRequiredAttrValue('URI'));
  4280. return drmInfo;
  4281. }
  4282. /**
  4283. * @param {!shaka.hls.Tag} drmTag
  4284. * @return {?shaka.extern.DrmInfo}
  4285. * @private
  4286. */
  4287. static widevineDrmParser_(drmTag) {
  4288. const method = drmTag.getRequiredAttrValue('METHOD');
  4289. const VALID_METHODS = ['SAMPLE-AES', 'SAMPLE-AES-CTR'];
  4290. if (!VALID_METHODS.includes(method)) {
  4291. shaka.log.error('Widevine in HLS is only supported with [',
  4292. VALID_METHODS.join(', '), '], not', method);
  4293. return null;
  4294. }
  4295. let encryptionScheme = 'cenc';
  4296. if (method == 'SAMPLE-AES') {
  4297. encryptionScheme = 'cbcs';
  4298. }
  4299. const uri = drmTag.getRequiredAttrValue('URI');
  4300. const parsedData = shaka.net.DataUriPlugin.parseRaw(uri.split('?')[0]);
  4301. // The data encoded in the URI is a PSSH box to be used as init data.
  4302. const pssh = shaka.util.BufferUtils.toUint8(parsedData.data);
  4303. const drmInfo = shaka.util.ManifestParserUtils.createDrmInfo(
  4304. 'com.widevine.alpha', encryptionScheme, [
  4305. {initDataType: 'cenc', initData: pssh},
  4306. ]);
  4307. const keyId = drmTag.getAttributeValue('KEYID');
  4308. if (keyId) {
  4309. const keyIdLowerCase = keyId.toLowerCase();
  4310. // This value should begin with '0x':
  4311. goog.asserts.assert(
  4312. keyIdLowerCase.startsWith('0x'), 'Incorrect KEYID format!');
  4313. // But the output should not contain the '0x':
  4314. drmInfo.keyIds = new Set([keyIdLowerCase.substr(2)]);
  4315. }
  4316. return drmInfo;
  4317. }
  4318. /**
  4319. * See: https://docs.microsoft.com/en-us/playready/packaging/mp4-based-formats-supported-by-playready-clients?tabs=case4
  4320. *
  4321. * @param {!shaka.hls.Tag} drmTag
  4322. * @return {?shaka.extern.DrmInfo}
  4323. * @private
  4324. */
  4325. static playreadyDrmParser_(drmTag) {
  4326. const method = drmTag.getRequiredAttrValue('METHOD');
  4327. const VALID_METHODS = ['SAMPLE-AES', 'SAMPLE-AES-CTR'];
  4328. if (!VALID_METHODS.includes(method)) {
  4329. shaka.log.error('PlayReady in HLS is only supported with [',
  4330. VALID_METHODS.join(', '), '], not', method);
  4331. return null;
  4332. }
  4333. let encryptionScheme = 'cenc';
  4334. if (method == 'SAMPLE-AES') {
  4335. encryptionScheme = 'cbcs';
  4336. }
  4337. const uri = drmTag.getRequiredAttrValue('URI');
  4338. const parsedData = shaka.net.DataUriPlugin.parseRaw(uri.split('?')[0]);
  4339. // The data encoded in the URI is a PlayReady Pro Object, so we need
  4340. // convert it to pssh.
  4341. const data = shaka.util.BufferUtils.toUint8(parsedData.data);
  4342. const systemId = new Uint8Array([
  4343. 0x9a, 0x04, 0xf0, 0x79, 0x98, 0x40, 0x42, 0x86,
  4344. 0xab, 0x92, 0xe6, 0x5b, 0xe0, 0x88, 0x5f, 0x95,
  4345. ]);
  4346. const keyIds = new Set();
  4347. const psshVersion = 0;
  4348. const pssh =
  4349. shaka.util.Pssh.createPssh(data, systemId, keyIds, psshVersion);
  4350. const drmInfo = shaka.util.ManifestParserUtils.createDrmInfo(
  4351. 'com.microsoft.playready', encryptionScheme, [
  4352. {initDataType: 'cenc', initData: pssh},
  4353. ]);
  4354. return drmInfo;
  4355. }
  4356. /**
  4357. * See: https://datatracker.ietf.org/doc/html/draft-pantos-hls-rfc8216bis-11#section-5.1
  4358. *
  4359. * @param {!shaka.hls.Tag} drmTag
  4360. * @param {string} mimeType
  4361. * @param {function():!Array.<string>} getUris
  4362. * @param {?shaka.media.InitSegmentReference} initSegmentRef
  4363. * @param {?Map.<string, string>=} variables
  4364. * @return {!Promise.<?shaka.extern.DrmInfo>}
  4365. * @private
  4366. */
  4367. async identityDrmParser_(drmTag, mimeType, getUris, initSegmentRef,
  4368. variables) {
  4369. if (mimeType == 'video/mp2t') {
  4370. throw new shaka.util.Error(
  4371. shaka.util.Error.Severity.CRITICAL,
  4372. shaka.util.Error.Category.MANIFEST,
  4373. shaka.util.Error.Code.HLS_MSE_ENCRYPTED_MP2T_NOT_SUPPORTED);
  4374. }
  4375. if (shaka.util.Platform.isMediaKeysPolyfilled()) {
  4376. throw new shaka.util.Error(
  4377. shaka.util.Error.Severity.CRITICAL,
  4378. shaka.util.Error.Category.MANIFEST,
  4379. shaka.util.Error.Code
  4380. .HLS_MSE_ENCRYPTED_LEGACY_APPLE_MEDIA_KEYS_NOT_SUPPORTED);
  4381. }
  4382. const method = drmTag.getRequiredAttrValue('METHOD');
  4383. const VALID_METHODS = ['SAMPLE-AES', 'SAMPLE-AES-CTR'];
  4384. if (!VALID_METHODS.includes(method)) {
  4385. shaka.log.error('Identity (ClearKey) in HLS is only supported with [',
  4386. VALID_METHODS.join(', '), '], not', method);
  4387. return null;
  4388. }
  4389. const keyUris = shaka.hls.Utils.constructSegmentUris(
  4390. getUris(), drmTag.getRequiredAttrValue('URI'), variables);
  4391. let key;
  4392. if (keyUris[0].startsWith('data:text/plain;base64,')) {
  4393. key = shaka.util.Uint8ArrayUtils.toHex(
  4394. shaka.util.Uint8ArrayUtils.fromBase64(
  4395. keyUris[0].split('data:text/plain;base64,').pop()));
  4396. } else {
  4397. const keyMapKey = keyUris.sort().join('');
  4398. if (!this.identityKeyMap_.has(keyMapKey)) {
  4399. const requestType = shaka.net.NetworkingEngine.RequestType.KEY;
  4400. const request = shaka.net.NetworkingEngine.makeRequest(
  4401. keyUris, this.config_.retryParameters);
  4402. const keyResponse = this.makeNetworkRequest_(request, requestType)
  4403. .promise;
  4404. this.identityKeyMap_.set(keyMapKey, keyResponse);
  4405. }
  4406. const keyResponse = await this.identityKeyMap_.get(keyMapKey);
  4407. key = shaka.util.Uint8ArrayUtils.toHex(keyResponse.data);
  4408. }
  4409. // NOTE: The ClearKey CDM requires a key-id to key mapping. HLS doesn't
  4410. // provide a key ID anywhere. So although we could use the 'URI' attribute
  4411. // to fetch the actual 16-byte key, without a key ID, we can't provide this
  4412. // automatically to the ClearKey CDM. By default we assume that keyId is 0,
  4413. // but we will try to get key ID from Init Segment.
  4414. // If the application want override this behavior will have to use
  4415. // player.configure('drm.clearKeys', { ... }) to provide the key IDs
  4416. // and keys or player.configure('drm.servers.org\.w3\.clearkey', ...) to
  4417. // provide a ClearKey license server URI.
  4418. let keyId = '00000000000000000000000000000000';
  4419. if (initSegmentRef) {
  4420. let defaultKID;
  4421. if (this.identityKidMap_.has(initSegmentRef)) {
  4422. defaultKID = this.identityKidMap_.get(initSegmentRef);
  4423. } else {
  4424. const initSegmentRequest = shaka.util.Networking.createSegmentRequest(
  4425. initSegmentRef.getUris(),
  4426. initSegmentRef.getStartByte(),
  4427. initSegmentRef.getEndByte(),
  4428. this.config_.retryParameters);
  4429. const requestType = shaka.net.NetworkingEngine.RequestType.SEGMENT;
  4430. const initType =
  4431. shaka.net.NetworkingEngine.AdvancedRequestType.INIT_SEGMENT;
  4432. const initResponse = await this.makeNetworkRequest_(
  4433. initSegmentRequest, requestType, {type: initType}).promise;
  4434. defaultKID = shaka.media.SegmentUtils.getDefaultKID(
  4435. initResponse.data);
  4436. this.identityKidMap_.set(initSegmentRef, defaultKID);
  4437. }
  4438. if (defaultKID) {
  4439. keyId = defaultKID;
  4440. }
  4441. }
  4442. const clearkeys = new Map();
  4443. clearkeys.set(keyId, key);
  4444. let encryptionScheme = 'cenc';
  4445. if (method == 'SAMPLE-AES') {
  4446. encryptionScheme = 'cbcs';
  4447. }
  4448. return shaka.util.ManifestParserUtils.createDrmInfoFromClearKeys(
  4449. clearkeys, encryptionScheme);
  4450. }
  4451. };
  4452. /**
  4453. * @typedef {{
  4454. * stream: !shaka.extern.Stream,
  4455. * type: string,
  4456. * redirectUris: !Array.<string>,
  4457. * getUris: function():!Array.<string>,
  4458. * minTimestamp: number,
  4459. * maxTimestamp: number,
  4460. * mediaSequenceToStartTime: !Map.<number, number>,
  4461. * canSkipSegments: boolean,
  4462. * canBlockReload: boolean,
  4463. * hasEndList: boolean,
  4464. * firstSequenceNumber: number,
  4465. * nextMediaSequence: number,
  4466. * nextPart: number,
  4467. * loadedOnce: boolean
  4468. * }}
  4469. *
  4470. * @description
  4471. * Contains a stream and information about it.
  4472. *
  4473. * @property {!shaka.extern.Stream} stream
  4474. * The Stream itself.
  4475. * @property {string} type
  4476. * The type value. Could be 'video', 'audio', 'text', or 'image'.
  4477. * @property {!Array.<string>} redirectUris
  4478. * The redirect URIs.
  4479. * @property {function():!Array.<string>} getUris
  4480. * The verbatim media playlist URIs, as it appeared in the master playlist.
  4481. * @property {number} minTimestamp
  4482. * The minimum timestamp found in the stream.
  4483. * @property {number} maxTimestamp
  4484. * The maximum timestamp found in the stream.
  4485. * @property {!Map.<number, number>} mediaSequenceToStartTime
  4486. * A map of media sequence numbers to media start times.
  4487. * Only used for VOD content.
  4488. * @property {boolean} canSkipSegments
  4489. * True if the server supports delta playlist updates, and we can send a
  4490. * request for a playlist that can skip older media segments.
  4491. * @property {boolean} canBlockReload
  4492. * True if the server supports blocking playlist reload, and we can send a
  4493. * request for a playlist that can block reload until some segments are
  4494. * present.
  4495. * @property {boolean} hasEndList
  4496. * True if the stream has an EXT-X-ENDLIST tag.
  4497. * @property {number} firstSequenceNumber
  4498. * The sequence number of the first reference. Only calculated if needed.
  4499. * @property {number} nextMediaSequence
  4500. * The next media sequence.
  4501. * @property {number} nextPart
  4502. * The next part.
  4503. * @property {boolean} loadedOnce
  4504. * True if the stream has been loaded at least once.
  4505. */
  4506. shaka.hls.HlsParser.StreamInfo;
  4507. /**
  4508. * @typedef {{
  4509. * audio: !Array.<shaka.hls.HlsParser.StreamInfo>,
  4510. * video: !Array.<shaka.hls.HlsParser.StreamInfo>
  4511. * }}
  4512. *
  4513. * @description Audio and video stream infos.
  4514. * @property {!Array.<shaka.hls.HlsParser.StreamInfo>} audio
  4515. * @property {!Array.<shaka.hls.HlsParser.StreamInfo>} video
  4516. */
  4517. shaka.hls.HlsParser.StreamInfos;
  4518. /**
  4519. * @const {!Object.<string, string>}
  4520. * @private
  4521. */
  4522. shaka.hls.HlsParser.RAW_FORMATS_TO_MIME_TYPES_ = {
  4523. 'aac': 'audio/aac',
  4524. 'ac3': 'audio/ac3',
  4525. 'ec3': 'audio/ec3',
  4526. 'mp3': 'audio/mpeg',
  4527. };
  4528. /**
  4529. * @const {!Object.<string, string>}
  4530. * @private
  4531. */
  4532. shaka.hls.HlsParser.AUDIO_EXTENSIONS_TO_MIME_TYPES_ = {
  4533. 'mp4': 'audio/mp4',
  4534. 'mp4a': 'audio/mp4',
  4535. 'm4s': 'audio/mp4',
  4536. 'm4i': 'audio/mp4',
  4537. 'm4a': 'audio/mp4',
  4538. 'm4f': 'audio/mp4',
  4539. 'cmfa': 'audio/mp4',
  4540. // MPEG2-TS also uses video/ for audio: https://bit.ly/TsMse
  4541. 'ts': 'video/mp2t',
  4542. 'tsa': 'video/mp2t',
  4543. };
  4544. /**
  4545. * @const {!Object.<string, string>}
  4546. * @private
  4547. */
  4548. shaka.hls.HlsParser.VIDEO_EXTENSIONS_TO_MIME_TYPES_ = {
  4549. 'mp4': 'video/mp4',
  4550. 'mp4v': 'video/mp4',
  4551. 'm4s': 'video/mp4',
  4552. 'm4i': 'video/mp4',
  4553. 'm4v': 'video/mp4',
  4554. 'm4f': 'video/mp4',
  4555. 'cmfv': 'video/mp4',
  4556. 'ts': 'video/mp2t',
  4557. 'tsv': 'video/mp2t',
  4558. };
  4559. /**
  4560. * @const {!Object.<string, string>}
  4561. * @private
  4562. */
  4563. shaka.hls.HlsParser.TEXT_EXTENSIONS_TO_MIME_TYPES_ = {
  4564. 'mp4': 'application/mp4',
  4565. 'm4s': 'application/mp4',
  4566. 'm4i': 'application/mp4',
  4567. 'm4f': 'application/mp4',
  4568. 'cmft': 'application/mp4',
  4569. 'vtt': 'text/vtt',
  4570. 'webvtt': 'text/vtt',
  4571. 'ttml': 'application/ttml+xml',
  4572. };
  4573. /**
  4574. * @const {!Object.<string, string>}
  4575. * @private
  4576. */
  4577. shaka.hls.HlsParser.IMAGE_EXTENSIONS_TO_MIME_TYPES_ = {
  4578. 'jpg': 'image/jpeg',
  4579. 'png': 'image/png',
  4580. 'svg': 'image/svg+xml',
  4581. 'webp': 'image/webp',
  4582. 'avif': 'image/avif',
  4583. };
  4584. /**
  4585. * @const {!Object.<string, !Object.<string, string>>}
  4586. * @private
  4587. */
  4588. shaka.hls.HlsParser.EXTENSION_MAP_BY_CONTENT_TYPE_ = {
  4589. 'audio': shaka.hls.HlsParser.AUDIO_EXTENSIONS_TO_MIME_TYPES_,
  4590. 'video': shaka.hls.HlsParser.VIDEO_EXTENSIONS_TO_MIME_TYPES_,
  4591. 'text': shaka.hls.HlsParser.TEXT_EXTENSIONS_TO_MIME_TYPES_,
  4592. 'image': shaka.hls.HlsParser.IMAGE_EXTENSIONS_TO_MIME_TYPES_,
  4593. };
  4594. /**
  4595. * MIME types without init segment.
  4596. *
  4597. * @const {!Set.<string>}
  4598. * @private
  4599. */
  4600. shaka.hls.HlsParser.MIME_TYPES_WITHOUT_INIT_SEGMENT_ = new Set([
  4601. 'video/mp2t',
  4602. // Containerless types
  4603. ...shaka.util.MimeUtils.RAW_FORMATS,
  4604. ]);
  4605. /**
  4606. * @typedef {function(!shaka.hls.Tag, string):?shaka.extern.DrmInfo}
  4607. * @private
  4608. */
  4609. shaka.hls.HlsParser.DrmParser_;
  4610. /**
  4611. * @const {!Object.<string, shaka.hls.HlsParser.DrmParser_>}
  4612. * @private
  4613. */
  4614. shaka.hls.HlsParser.KEYFORMATS_TO_DRM_PARSERS_ = {
  4615. 'com.apple.streamingkeydelivery':
  4616. shaka.hls.HlsParser.fairplayDrmParser_,
  4617. 'urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed':
  4618. shaka.hls.HlsParser.widevineDrmParser_,
  4619. 'com.microsoft.playready':
  4620. shaka.hls.HlsParser.playreadyDrmParser_,
  4621. };
  4622. /**
  4623. * @enum {string}
  4624. * @private
  4625. */
  4626. shaka.hls.HlsParser.PresentationType_ = {
  4627. VOD: 'VOD',
  4628. EVENT: 'EVENT',
  4629. LIVE: 'LIVE',
  4630. };
  4631. shaka.media.ManifestParser.registerParserByMime(
  4632. 'application/x-mpegurl', () => new shaka.hls.HlsParser());
  4633. shaka.media.ManifestParser.registerParserByMime(
  4634. 'application/vnd.apple.mpegurl', () => new shaka.hls.HlsParser());