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