Source: lib/dash/dash_parser.js

  1. /*! @license
  2. * Shaka Player
  3. * Copyright 2016 Google LLC
  4. * SPDX-License-Identifier: Apache-2.0
  5. */
  6. goog.provide('shaka.dash.DashParser');
  7. goog.require('goog.asserts');
  8. goog.require('shaka.Deprecate');
  9. goog.require('shaka.abr.Ewma');
  10. goog.require('shaka.dash.ContentProtection');
  11. goog.require('shaka.dash.MpdUtils');
  12. goog.require('shaka.dash.SegmentBase');
  13. goog.require('shaka.dash.SegmentList');
  14. goog.require('shaka.dash.SegmentTemplate');
  15. goog.require('shaka.log');
  16. goog.require('shaka.media.Capabilities');
  17. goog.require('shaka.media.ManifestParser');
  18. goog.require('shaka.media.PresentationTimeline');
  19. goog.require('shaka.media.SegmentIndex');
  20. goog.require('shaka.media.SegmentUtils');
  21. goog.require('shaka.net.NetworkingEngine');
  22. goog.require('shaka.text.TextEngine');
  23. goog.require('shaka.util.ContentSteeringManager');
  24. goog.require('shaka.util.Error');
  25. goog.require('shaka.util.EventManager');
  26. goog.require('shaka.util.Functional');
  27. goog.require('shaka.util.LanguageUtils');
  28. goog.require('shaka.util.ManifestParserUtils');
  29. goog.require('shaka.util.MimeUtils');
  30. goog.require('shaka.util.Networking');
  31. goog.require('shaka.util.OperationManager');
  32. goog.require('shaka.util.PeriodCombiner');
  33. goog.require('shaka.util.PlayerConfiguration');
  34. goog.require('shaka.util.StringUtils');
  35. goog.require('shaka.util.Timer');
  36. goog.require('shaka.util.TXml');
  37. goog.require('shaka.util.XmlUtils');
  38. /**
  39. * Creates a new DASH parser.
  40. *
  41. * @implements {shaka.extern.ManifestParser}
  42. * @export
  43. */
  44. shaka.dash.DashParser = class {
  45. /** Creates a new DASH parser. */
  46. constructor() {
  47. /** @private {?shaka.extern.ManifestConfiguration} */
  48. this.config_ = null;
  49. /** @private {?shaka.extern.ManifestParser.PlayerInterface} */
  50. this.playerInterface_ = null;
  51. /** @private {!Array.<string>} */
  52. this.manifestUris_ = [];
  53. /** @private {?shaka.extern.Manifest} */
  54. this.manifest_ = null;
  55. /** @private {number} */
  56. this.globalId_ = 1;
  57. /** @private {!Array<shaka.extern.xml.Node>} */
  58. this.patchLocationNodes_ = [];
  59. /**
  60. * A context of the living manifest used for processing
  61. * Patch MPD's
  62. * @private {!shaka.dash.DashParser.PatchContext}
  63. */
  64. this.manifestPatchContext_ = {
  65. mpdId: '',
  66. type: '',
  67. profiles: [],
  68. mediaPresentationDuration: null,
  69. availabilityTimeOffset: 0,
  70. getBaseUris: null,
  71. publishTime: 0,
  72. };
  73. /**
  74. * This is a cache is used the store a snapshot of the context
  75. * object which is built up throughout node traversal to maintain
  76. * a current state. This data needs to be preserved for parsing
  77. * patches.
  78. * The key is a combination period and representation id's.
  79. * @private {!Map<string, !shaka.dash.DashParser.Context>}
  80. */
  81. this.contextCache_ = new Map();
  82. /**
  83. * A map of IDs to Stream objects.
  84. * ID: Period@id,AdaptationSet@id,@Representation@id
  85. * e.g.: '1,5,23'
  86. * @private {!Object.<string, !shaka.extern.Stream>}
  87. */
  88. this.streamMap_ = {};
  89. /**
  90. * A map of period ids to their durations
  91. * @private {!Object.<string, number>}
  92. */
  93. this.periodDurations_ = {};
  94. /** @private {shaka.util.PeriodCombiner} */
  95. this.periodCombiner_ = new shaka.util.PeriodCombiner();
  96. /**
  97. * The update period in seconds, or 0 for no updates.
  98. * @private {number}
  99. */
  100. this.updatePeriod_ = 0;
  101. /**
  102. * An ewma that tracks how long updates take.
  103. * This is to mitigate issues caused by slow parsing on embedded devices.
  104. * @private {!shaka.abr.Ewma}
  105. */
  106. this.averageUpdateDuration_ = new shaka.abr.Ewma(5);
  107. /** @private {shaka.util.Timer} */
  108. this.updateTimer_ = new shaka.util.Timer(() => {
  109. if (this.mediaElement_ && !this.config_.continueLoadingWhenPaused) {
  110. this.eventManager_.unlisten(this.mediaElement_, 'timeupdate');
  111. if (this.mediaElement_.paused) {
  112. this.eventManager_.listenOnce(
  113. this.mediaElement_, 'timeupdate', () => this.onUpdate_());
  114. return;
  115. }
  116. }
  117. this.onUpdate_();
  118. });
  119. /** @private {!shaka.util.OperationManager} */
  120. this.operationManager_ = new shaka.util.OperationManager();
  121. /**
  122. * Largest period start time seen.
  123. * @private {?number}
  124. */
  125. this.largestPeriodStartTime_ = null;
  126. /**
  127. * Period IDs seen in previous manifest.
  128. * @private {!Array.<string>}
  129. */
  130. this.lastManifestUpdatePeriodIds_ = [];
  131. /**
  132. * The minimum of the availabilityTimeOffset values among the adaptation
  133. * sets.
  134. * @private {number}
  135. */
  136. this.minTotalAvailabilityTimeOffset_ = Infinity;
  137. /** @private {boolean} */
  138. this.lowLatencyMode_ = false;
  139. /** @private {?shaka.util.ContentSteeringManager} */
  140. this.contentSteeringManager_ = null;
  141. /** @private {number} */
  142. this.gapCount_ = 0;
  143. /** @private {boolean} */
  144. this.isLowLatency_ = false;
  145. /** @private {shaka.util.EventManager} */
  146. this.eventManager_ = new shaka.util.EventManager();
  147. /** @private {HTMLMediaElement} */
  148. this.mediaElement_ = null;
  149. /** @private {boolean} */
  150. this.isTransitionFromDynamicToStatic_ = false;
  151. }
  152. /**
  153. * @override
  154. * @exportInterface
  155. */
  156. configure(config) {
  157. goog.asserts.assert(config.dash != null,
  158. 'DashManifestConfiguration should not be null!');
  159. const needFireUpdate = this.playerInterface_ &&
  160. config.dash.updatePeriod != this.config_.dash.updatePeriod &&
  161. config.dash.updatePeriod >= 0;
  162. this.config_ = config;
  163. if (needFireUpdate && this.manifest_ &&
  164. this.manifest_.presentationTimeline.isLive()) {
  165. this.updateNow_();
  166. }
  167. if (this.contentSteeringManager_) {
  168. this.contentSteeringManager_.configure(this.config_);
  169. }
  170. if (this.periodCombiner_) {
  171. this.periodCombiner_.setAllowMultiTypeVariants(
  172. this.config_.dash.multiTypeVariantsAllowed &&
  173. shaka.media.Capabilities.isChangeTypeSupported());
  174. this.periodCombiner_.setUseStreamOnce(
  175. this.config_.dash.useStreamOnceInPeriodFlattening);
  176. }
  177. }
  178. /**
  179. * @override
  180. * @exportInterface
  181. */
  182. async start(uri, playerInterface) {
  183. goog.asserts.assert(this.config_, 'Must call configure() before start()!');
  184. this.lowLatencyMode_ = playerInterface.isLowLatencyMode();
  185. this.manifestUris_ = [uri];
  186. this.playerInterface_ = playerInterface;
  187. const updateDelay = await this.requestManifest_();
  188. if (this.playerInterface_) {
  189. this.setUpdateTimer_(updateDelay);
  190. }
  191. // Make sure that the parser has not been destroyed.
  192. if (!this.playerInterface_) {
  193. throw new shaka.util.Error(
  194. shaka.util.Error.Severity.CRITICAL,
  195. shaka.util.Error.Category.PLAYER,
  196. shaka.util.Error.Code.OPERATION_ABORTED);
  197. }
  198. goog.asserts.assert(this.manifest_, 'Manifest should be non-null!');
  199. return this.manifest_;
  200. }
  201. /**
  202. * @override
  203. * @exportInterface
  204. */
  205. stop() {
  206. // When the parser stops, release all segment indexes, which stops their
  207. // timers, as well.
  208. for (const stream of Object.values(this.streamMap_)) {
  209. if (stream.segmentIndex) {
  210. stream.segmentIndex.release();
  211. }
  212. }
  213. if (this.periodCombiner_) {
  214. this.periodCombiner_.release();
  215. }
  216. this.playerInterface_ = null;
  217. this.config_ = null;
  218. this.manifestUris_ = [];
  219. this.manifest_ = null;
  220. this.streamMap_ = {};
  221. this.contextCache_.clear();
  222. this.manifestPatchContext_ = {
  223. mpdId: '',
  224. type: '',
  225. profiles: [],
  226. mediaPresentationDuration: null,
  227. availabilityTimeOffset: 0,
  228. getBaseUris: null,
  229. publishTime: 0,
  230. };
  231. this.periodCombiner_ = null;
  232. if (this.updateTimer_ != null) {
  233. this.updateTimer_.stop();
  234. this.updateTimer_ = null;
  235. }
  236. if (this.contentSteeringManager_) {
  237. this.contentSteeringManager_.destroy();
  238. }
  239. if (this.eventManager_) {
  240. this.eventManager_.release();
  241. this.eventManager_ = null;
  242. }
  243. return this.operationManager_.destroy();
  244. }
  245. /**
  246. * @override
  247. * @exportInterface
  248. */
  249. async update() {
  250. try {
  251. await this.requestManifest_();
  252. } catch (error) {
  253. if (!this.playerInterface_ || !error) {
  254. return;
  255. }
  256. goog.asserts.assert(error instanceof shaka.util.Error, 'Bad error type');
  257. this.playerInterface_.onError(error);
  258. }
  259. }
  260. /**
  261. * @override
  262. * @exportInterface
  263. */
  264. onExpirationUpdated(sessionId, expiration) {
  265. // No-op
  266. }
  267. /**
  268. * @override
  269. * @exportInterface
  270. */
  271. onInitialVariantChosen(variant) {
  272. // For live it is necessary that the first time we update the manifest with
  273. // a shorter time than indicated to take into account that the last segment
  274. // added could be halfway, for example
  275. if (this.manifest_ && this.manifest_.presentationTimeline.isLive()) {
  276. const stream = variant.video || variant.audio;
  277. if (stream && stream.segmentIndex) {
  278. const availabilityEnd =
  279. this.manifest_.presentationTimeline.getSegmentAvailabilityEnd();
  280. const position = stream.segmentIndex.find(availabilityEnd);
  281. if (position == null) {
  282. return;
  283. }
  284. const reference = stream.segmentIndex.get(position);
  285. if (!reference) {
  286. return;
  287. }
  288. this.updatePeriod_ = reference.endTime - availabilityEnd;
  289. this.setUpdateTimer_(/* offset= */ 0);
  290. }
  291. }
  292. }
  293. /**
  294. * @override
  295. * @exportInterface
  296. */
  297. banLocation(uri) {
  298. if (this.contentSteeringManager_) {
  299. this.contentSteeringManager_.banLocation(uri);
  300. }
  301. }
  302. /**
  303. * @override
  304. * @exportInterface
  305. */
  306. setMediaElement(mediaElement) {
  307. this.mediaElement_ = mediaElement;
  308. }
  309. /**
  310. * Makes a network request for the manifest and parses the resulting data.
  311. *
  312. * @return {!Promise.<number>} Resolves with the time it took, in seconds, to
  313. * fulfill the request and parse the data.
  314. * @private
  315. */
  316. async requestManifest_() {
  317. const requestType = shaka.net.NetworkingEngine.RequestType.MANIFEST;
  318. let type = shaka.net.NetworkingEngine.AdvancedRequestType.MPD;
  319. let rootElement = 'MPD';
  320. const patchLocationUris = this.getPatchLocationUris_();
  321. let manifestUris = this.manifestUris_;
  322. if (patchLocationUris.length) {
  323. manifestUris = patchLocationUris;
  324. rootElement = 'Patch';
  325. type = shaka.net.NetworkingEngine.AdvancedRequestType.MPD_PATCH;
  326. } else if (this.manifestUris_.length > 1 && this.contentSteeringManager_) {
  327. const locations = this.contentSteeringManager_.getLocations(
  328. 'Location', /* ignoreBaseUrls= */ true);
  329. if (locations.length) {
  330. manifestUris = locations;
  331. }
  332. }
  333. const request = shaka.net.NetworkingEngine.makeRequest(
  334. manifestUris, this.config_.retryParameters);
  335. const startTime = Date.now();
  336. const response = await this.makeNetworkRequest_(
  337. request, requestType, {type});
  338. // Detect calls to stop().
  339. if (!this.playerInterface_) {
  340. return 0;
  341. }
  342. // For redirections add the response uri to the first entry in the
  343. // Manifest Uris array.
  344. if (response.uri && response.uri != response.originalUri &&
  345. !this.manifestUris_.includes(response.uri)) {
  346. this.manifestUris_.unshift(response.uri);
  347. }
  348. // This may throw, but it will result in a failed promise.
  349. await this.parseManifest_(response.data, response.uri, rootElement);
  350. // Keep track of how long the longest manifest update took.
  351. const endTime = Date.now();
  352. const updateDuration = (endTime - startTime) / 1000.0;
  353. this.averageUpdateDuration_.sample(1, updateDuration);
  354. // Let the caller know how long this update took.
  355. return updateDuration;
  356. }
  357. /**
  358. * Parses the manifest XML. This also handles updates and will update the
  359. * stored manifest.
  360. *
  361. * @param {BufferSource} data
  362. * @param {string} finalManifestUri The final manifest URI, which may
  363. * differ from this.manifestUri_ if there has been a redirect.
  364. * @param {string} rootElement MPD or Patch, depending on context
  365. * @return {!Promise}
  366. * @private
  367. */
  368. async parseManifest_(data, finalManifestUri, rootElement) {
  369. let manifestData = data;
  370. const manifestPreprocessor = this.config_.dash.manifestPreprocessor;
  371. const defaultManifestPreprocessor =
  372. shaka.util.PlayerConfiguration.defaultManifestPreprocessor;
  373. if (manifestPreprocessor != defaultManifestPreprocessor) {
  374. shaka.Deprecate.deprecateFeature(5,
  375. 'manifest.dash.manifestPreprocessor configuration',
  376. 'Please Use manifest.dash.manifestPreprocessorTXml instead.');
  377. const mpdElement =
  378. shaka.util.XmlUtils.parseXml(manifestData, rootElement);
  379. if (!mpdElement) {
  380. throw new shaka.util.Error(
  381. shaka.util.Error.Severity.CRITICAL,
  382. shaka.util.Error.Category.MANIFEST,
  383. shaka.util.Error.Code.DASH_INVALID_XML,
  384. finalManifestUri);
  385. }
  386. manifestPreprocessor(mpdElement);
  387. manifestData = shaka.util.XmlUtils.toArrayBuffer(mpdElement);
  388. }
  389. const mpd = shaka.util.TXml.parseXml(manifestData, rootElement);
  390. if (!mpd) {
  391. throw new shaka.util.Error(
  392. shaka.util.Error.Severity.CRITICAL,
  393. shaka.util.Error.Category.MANIFEST,
  394. shaka.util.Error.Code.DASH_INVALID_XML,
  395. finalManifestUri);
  396. }
  397. const manifestPreprocessorTXml =
  398. this.config_.dash.manifestPreprocessorTXml;
  399. const defaultManifestPreprocessorTXml =
  400. shaka.util.PlayerConfiguration.defaultManifestPreprocessorTXml;
  401. if (manifestPreprocessorTXml != defaultManifestPreprocessorTXml) {
  402. manifestPreprocessorTXml(mpd);
  403. }
  404. if (rootElement === 'Patch') {
  405. return this.processPatchManifest_(mpd);
  406. }
  407. const disableXlinkProcessing = this.config_.dash.disableXlinkProcessing;
  408. if (disableXlinkProcessing) {
  409. return this.processManifest_(mpd, finalManifestUri);
  410. }
  411. // Process the mpd to account for xlink connections.
  412. const failGracefully = this.config_.dash.xlinkFailGracefully;
  413. const xlinkOperation = shaka.dash.MpdUtils.processXlinks(
  414. mpd, this.config_.retryParameters, failGracefully, finalManifestUri,
  415. this.playerInterface_.networkingEngine);
  416. this.operationManager_.manage(xlinkOperation);
  417. const finalMpd = await xlinkOperation.promise;
  418. return this.processManifest_(finalMpd, finalManifestUri);
  419. }
  420. /**
  421. * Takes a formatted MPD and converts it into a manifest.
  422. *
  423. * @param {!shaka.extern.xml.Node} mpd
  424. * @param {string} finalManifestUri The final manifest URI, which may
  425. * differ from this.manifestUri_ if there has been a redirect.
  426. * @return {!Promise}
  427. * @private
  428. */
  429. async processManifest_(mpd, finalManifestUri) {
  430. const TXml = shaka.util.TXml;
  431. goog.asserts.assert(this.config_,
  432. 'Must call configure() before processManifest_()!');
  433. if (this.contentSteeringManager_) {
  434. this.contentSteeringManager_.clearPreviousLocations();
  435. }
  436. // Get any Location elements. This will update the manifest location and
  437. // the base URI.
  438. /** @type {!Array.<string>} */
  439. let manifestBaseUris = [finalManifestUri];
  440. /** @type {!Array.<string>} */
  441. const locations = [];
  442. /** @type {!Map.<string, string>} */
  443. const locationsMapping = new Map();
  444. const locationsObjs = TXml.findChildren(mpd, 'Location');
  445. for (const locationsObj of locationsObjs) {
  446. const serviceLocation = locationsObj.attributes['serviceLocation'];
  447. const uri = TXml.getContents(locationsObj);
  448. if (!uri) {
  449. continue;
  450. }
  451. const finalUri = shaka.util.ManifestParserUtils.resolveUris(
  452. manifestBaseUris, [uri])[0];
  453. if (serviceLocation) {
  454. if (this.contentSteeringManager_) {
  455. this.contentSteeringManager_.addLocation(
  456. 'Location', serviceLocation, finalUri);
  457. } else {
  458. locationsMapping.set(serviceLocation, finalUri);
  459. }
  460. }
  461. locations.push(finalUri);
  462. }
  463. if (this.contentSteeringManager_) {
  464. const steeringlocations = this.contentSteeringManager_.getLocations(
  465. 'Location', /* ignoreBaseUrls= */ true);
  466. if (steeringlocations.length > 0) {
  467. this.manifestUris_ = steeringlocations;
  468. manifestBaseUris = steeringlocations;
  469. }
  470. } else if (locations.length) {
  471. this.manifestUris_ = locations;
  472. manifestBaseUris = locations;
  473. }
  474. this.manifestPatchContext_.mpdId = mpd.attributes['id'] || '';
  475. this.manifestPatchContext_.publishTime =
  476. TXml.parseAttr(mpd, 'publishTime', TXml.parseDate) || 0;
  477. this.patchLocationNodes_ = TXml.findChildren(mpd, 'PatchLocation');
  478. let contentSteeringPromise = Promise.resolve();
  479. const contentSteering = TXml.findChild(mpd, 'ContentSteering');
  480. if (contentSteering && this.playerInterface_) {
  481. const defaultPathwayId =
  482. contentSteering.attributes['defaultServiceLocation'];
  483. if (!this.contentSteeringManager_) {
  484. this.contentSteeringManager_ =
  485. new shaka.util.ContentSteeringManager(this.playerInterface_);
  486. this.contentSteeringManager_.configure(this.config_);
  487. this.contentSteeringManager_.setManifestType(
  488. shaka.media.ManifestParser.DASH);
  489. this.contentSteeringManager_.setBaseUris(manifestBaseUris);
  490. this.contentSteeringManager_.setDefaultPathwayId(defaultPathwayId);
  491. const uri = TXml.getContents(contentSteering);
  492. if (uri) {
  493. const queryBeforeStart =
  494. TXml.parseAttr(contentSteering, 'queryBeforeStart',
  495. TXml.parseBoolean, /* defaultValue= */ false);
  496. if (queryBeforeStart) {
  497. contentSteeringPromise =
  498. this.contentSteeringManager_.requestInfo(uri);
  499. } else {
  500. this.contentSteeringManager_.requestInfo(uri);
  501. }
  502. }
  503. } else {
  504. this.contentSteeringManager_.setBaseUris(manifestBaseUris);
  505. this.contentSteeringManager_.setDefaultPathwayId(defaultPathwayId);
  506. }
  507. for (const serviceLocation of locationsMapping.keys()) {
  508. const uri = locationsMapping.get(serviceLocation);
  509. this.contentSteeringManager_.addLocation(
  510. 'Location', serviceLocation, uri);
  511. }
  512. }
  513. const uriObjs = TXml.findChildren(mpd, 'BaseURL');
  514. let calculatedBaseUris;
  515. let someLocationValid = false;
  516. if (this.contentSteeringManager_) {
  517. for (const uriObj of uriObjs) {
  518. const serviceLocation = uriObj.attributes['serviceLocation'];
  519. const uri = TXml.getContents(uriObj);
  520. if (serviceLocation && uri) {
  521. this.contentSteeringManager_.addLocation(
  522. 'BaseURL', serviceLocation, uri);
  523. someLocationValid = true;
  524. }
  525. }
  526. }
  527. if (!someLocationValid || !this.contentSteeringManager_) {
  528. const uris = uriObjs.map(TXml.getContents);
  529. calculatedBaseUris = shaka.util.ManifestParserUtils.resolveUris(
  530. manifestBaseUris, uris);
  531. }
  532. const getBaseUris = () => {
  533. if (this.contentSteeringManager_ && someLocationValid) {
  534. return this.contentSteeringManager_.getLocations('BaseURL');
  535. }
  536. if (calculatedBaseUris) {
  537. return calculatedBaseUris;
  538. }
  539. return [];
  540. };
  541. this.manifestPatchContext_.getBaseUris = getBaseUris;
  542. let availabilityTimeOffset = 0;
  543. if (uriObjs && uriObjs.length) {
  544. availabilityTimeOffset = TXml.parseAttr(uriObjs[0],
  545. 'availabilityTimeOffset', TXml.parseFloat) || 0;
  546. }
  547. this.manifestPatchContext_.availabilityTimeOffset = availabilityTimeOffset;
  548. const ignoreMinBufferTime = this.config_.dash.ignoreMinBufferTime;
  549. let minBufferTime = 0;
  550. if (!ignoreMinBufferTime) {
  551. minBufferTime =
  552. TXml.parseAttr(mpd, 'minBufferTime', TXml.parseDuration) || 0;
  553. }
  554. this.updatePeriod_ = /** @type {number} */ (TXml.parseAttr(
  555. mpd, 'minimumUpdatePeriod', TXml.parseDuration, -1));
  556. const presentationStartTime = TXml.parseAttr(
  557. mpd, 'availabilityStartTime', TXml.parseDate);
  558. let segmentAvailabilityDuration = TXml.parseAttr(
  559. mpd, 'timeShiftBufferDepth', TXml.parseDuration);
  560. const ignoreSuggestedPresentationDelay =
  561. this.config_.dash.ignoreSuggestedPresentationDelay;
  562. let suggestedPresentationDelay = null;
  563. if (!ignoreSuggestedPresentationDelay) {
  564. suggestedPresentationDelay = TXml.parseAttr(
  565. mpd, 'suggestedPresentationDelay', TXml.parseDuration);
  566. }
  567. const ignoreMaxSegmentDuration =
  568. this.config_.dash.ignoreMaxSegmentDuration;
  569. let maxSegmentDuration = null;
  570. if (!ignoreMaxSegmentDuration) {
  571. maxSegmentDuration = TXml.parseAttr(
  572. mpd, 'maxSegmentDuration', TXml.parseDuration);
  573. }
  574. const mpdType = mpd.attributes['type'] || 'static';
  575. if (this.manifest_ && this.manifest_.presentationTimeline) {
  576. this.isTransitionFromDynamicToStatic_ =
  577. this.manifest_.presentationTimeline.isLive() && mpdType == 'static';
  578. }
  579. this.manifestPatchContext_.type = mpdType;
  580. /** @type {!shaka.media.PresentationTimeline} */
  581. let presentationTimeline;
  582. if (this.manifest_) {
  583. presentationTimeline = this.manifest_.presentationTimeline;
  584. // Before processing an update, evict from all segment indexes. Some of
  585. // them may not get updated otherwise if their corresponding Period
  586. // element has been dropped from the manifest since the last update.
  587. // Without this, playback will still work, but this is necessary to
  588. // maintain conditions that we assert on for multi-Period content.
  589. // This gives us confidence that our state is maintained correctly, and
  590. // that the complex logic of multi-Period eviction and period-flattening
  591. // is correct. See also:
  592. // https://github.com/shaka-project/shaka-player/issues/3169#issuecomment-823580634
  593. for (const stream of Object.values(this.streamMap_)) {
  594. if (stream.segmentIndex) {
  595. stream.segmentIndex.evict(
  596. presentationTimeline.getSegmentAvailabilityStart());
  597. }
  598. }
  599. } else {
  600. // DASH IOP v3.0 suggests using a default delay between minBufferTime
  601. // and timeShiftBufferDepth. This is literally the range of all
  602. // feasible choices for the value. Nothing older than
  603. // timeShiftBufferDepth is still available, and anything less than
  604. // minBufferTime will cause buffering issues.
  605. //
  606. // We have decided that our default will be the configured value, or
  607. // 1.5 * minBufferTime if not configured. This is fairly conservative.
  608. // Content providers should provide a suggestedPresentationDelay whenever
  609. // possible to optimize the live streaming experience.
  610. const defaultPresentationDelay =
  611. this.config_.defaultPresentationDelay || minBufferTime * 1.5;
  612. const presentationDelay = suggestedPresentationDelay != null ?
  613. suggestedPresentationDelay : defaultPresentationDelay;
  614. presentationTimeline = new shaka.media.PresentationTimeline(
  615. presentationStartTime, presentationDelay,
  616. this.config_.dash.autoCorrectDrift);
  617. }
  618. presentationTimeline.setStatic(mpdType == 'static');
  619. const isLive = presentationTimeline.isLive();
  620. // If it's live, we check for an override.
  621. if (isLive && !isNaN(this.config_.availabilityWindowOverride)) {
  622. segmentAvailabilityDuration = this.config_.availabilityWindowOverride;
  623. }
  624. // If it's null, that means segments are always available. This is always
  625. // the case for VOD, and sometimes the case for live.
  626. if (segmentAvailabilityDuration == null) {
  627. segmentAvailabilityDuration = Infinity;
  628. }
  629. presentationTimeline.setSegmentAvailabilityDuration(
  630. segmentAvailabilityDuration);
  631. const profiles = mpd.attributes['profiles'] || '';
  632. this.manifestPatchContext_.profiles = profiles.split(',');
  633. /** @type {shaka.dash.DashParser.Context} */
  634. const context = {
  635. // Don't base on updatePeriod_ since emsg boxes can cause manifest
  636. // updates.
  637. dynamic: mpdType != 'static',
  638. presentationTimeline: presentationTimeline,
  639. period: null,
  640. periodInfo: null,
  641. adaptationSet: null,
  642. representation: null,
  643. bandwidth: 0,
  644. indexRangeWarningGiven: false,
  645. availabilityTimeOffset: availabilityTimeOffset,
  646. mediaPresentationDuration: null,
  647. profiles: profiles.split(','),
  648. roles: null,
  649. };
  650. this.gapCount_ = 0;
  651. const periodsAndDuration = this.parsePeriods_(context, getBaseUris, mpd);
  652. const duration = periodsAndDuration.duration;
  653. const periods = periodsAndDuration.periods;
  654. if ((mpdType == 'static' && !this.isTransitionFromDynamicToStatic_) ||
  655. !periodsAndDuration.durationDerivedFromPeriods) {
  656. // Ignore duration calculated from Period lengths if this is dynamic.
  657. presentationTimeline.setDuration(duration || Infinity);
  658. }
  659. // The segments are available earlier than the availability start time.
  660. // If the stream is low latency and the user has not configured the
  661. // lowLatencyMode, but if it has been configured to activate the
  662. // lowLatencyMode if a stream of this type is detected, we automatically
  663. // activate the lowLatencyMode.
  664. if (this.isLowLatency_ && !this.lowLatencyMode_) {
  665. const autoLowLatencyMode = this.playerInterface_.isAutoLowLatencyMode();
  666. if (autoLowLatencyMode) {
  667. this.playerInterface_.enableLowLatencyMode();
  668. this.lowLatencyMode_ = this.playerInterface_.isLowLatencyMode();
  669. }
  670. }
  671. if (this.lowLatencyMode_) {
  672. presentationTimeline.setAvailabilityTimeOffset(
  673. this.minTotalAvailabilityTimeOffset_);
  674. }
  675. // Use @maxSegmentDuration to override smaller, derived values.
  676. presentationTimeline.notifyMaxSegmentDuration(maxSegmentDuration || 1);
  677. if (goog.DEBUG && !this.isTransitionFromDynamicToStatic_) {
  678. presentationTimeline.assertIsValid();
  679. }
  680. await contentSteeringPromise;
  681. // Set minBufferTime to 0 for low-latency DASH live stream to achieve the
  682. // best latency
  683. if (this.lowLatencyMode_) {
  684. minBufferTime = 0;
  685. const presentationDelay = suggestedPresentationDelay != null ?
  686. suggestedPresentationDelay : this.config_.defaultPresentationDelay;
  687. presentationTimeline.setDelay(presentationDelay);
  688. }
  689. // These steps are not done on manifest update.
  690. if (!this.manifest_) {
  691. await this.periodCombiner_.combinePeriods(periods, context.dynamic);
  692. this.manifest_ = {
  693. presentationTimeline: presentationTimeline,
  694. variants: this.periodCombiner_.getVariants(),
  695. textStreams: this.periodCombiner_.getTextStreams(),
  696. imageStreams: this.periodCombiner_.getImageStreams(),
  697. offlineSessionIds: [],
  698. minBufferTime: minBufferTime || 0,
  699. sequenceMode: this.config_.dash.sequenceMode,
  700. ignoreManifestTimestampsInSegmentsMode: false,
  701. type: shaka.media.ManifestParser.DASH,
  702. serviceDescription: this.parseServiceDescription_(mpd),
  703. nextUrl: this.parseMpdChaining_(mpd),
  704. periodCount: periods.length,
  705. gapCount: this.gapCount_,
  706. isLowLatency: this.isLowLatency_,
  707. };
  708. // We only need to do clock sync when we're using presentation start
  709. // time. This condition also excludes VOD streams.
  710. if (presentationTimeline.usingPresentationStartTime()) {
  711. const TXml = shaka.util.TXml;
  712. const timingElements = TXml.findChildren(mpd, 'UTCTiming');
  713. const offset = await this.parseUtcTiming_(getBaseUris, timingElements);
  714. // Detect calls to stop().
  715. if (!this.playerInterface_) {
  716. return;
  717. }
  718. presentationTimeline.setClockOffset(offset);
  719. }
  720. // This is the first point where we have a meaningful presentation start
  721. // time, and we need to tell PresentationTimeline that so that it can
  722. // maintain consistency from here on.
  723. presentationTimeline.lockStartTime();
  724. } else {
  725. this.manifest_.periodCount = periods.length;
  726. this.manifest_.gapCount = this.gapCount_;
  727. await this.postPeriodProcessing_(periods, /* isPatchUpdate= */ false);
  728. }
  729. // Add text streams to correspond to closed captions. This happens right
  730. // after period combining, while we still have a direct reference, so that
  731. // any new streams will appear in the period combiner.
  732. this.playerInterface_.makeTextStreamsForClosedCaptions(this.manifest_);
  733. }
  734. /**
  735. * Handles common procedures after processing new periods.
  736. *
  737. * @param {!Array<shaka.extern.Period>} periods to be appended
  738. * @param {boolean} isPatchUpdate does call comes from mpd patch update
  739. * @private
  740. */
  741. async postPeriodProcessing_(periods, isPatchUpdate) {
  742. await this.periodCombiner_.combinePeriods(periods, true, isPatchUpdate);
  743. // Just update the variants and text streams, which may change as periods
  744. // are added or removed.
  745. this.manifest_.variants = this.periodCombiner_.getVariants();
  746. const textStreams = this.periodCombiner_.getTextStreams();
  747. if (textStreams.length > 0) {
  748. this.manifest_.textStreams = textStreams;
  749. }
  750. this.manifest_.imageStreams = this.periodCombiner_.getImageStreams();
  751. // Re-filter the manifest. This will check any configured restrictions on
  752. // new variants, and will pass any new init data to DrmEngine to ensure
  753. // that key rotation works correctly.
  754. this.playerInterface_.filter(this.manifest_);
  755. }
  756. /**
  757. * Takes a formatted Patch MPD and converts it into a manifest.
  758. *
  759. * @param {!shaka.extern.xml.Node} mpd
  760. * @return {!Promise}
  761. * @private
  762. */
  763. async processPatchManifest_(mpd) {
  764. const TXml = shaka.util.TXml;
  765. const mpdId = mpd.attributes['mpdId'];
  766. const originalPublishTime = TXml.parseAttr(mpd, 'originalPublishTime',
  767. TXml.parseDate);
  768. if (!mpdId || mpdId !== this.manifestPatchContext_.mpdId ||
  769. originalPublishTime !== this.manifestPatchContext_.publishTime) {
  770. // Clean patch location nodes, so it will force full MPD update.
  771. this.patchLocationNodes_ = [];
  772. throw new shaka.util.Error(
  773. shaka.util.Error.Severity.RECOVERABLE,
  774. shaka.util.Error.Category.MANIFEST,
  775. shaka.util.Error.Code.DASH_INVALID_PATCH);
  776. }
  777. /** @type {!Array<shaka.extern.Period>} */
  778. const newPeriods = [];
  779. /** @type {!Array<shaka.extern.xml.Node>} */
  780. const periodAdditions = [];
  781. /** @type {!Set<string>} */
  782. const modifiedTimelines = new Set();
  783. for (const patchNode of TXml.getChildNodes(mpd)) {
  784. let handled = true;
  785. const paths = TXml.parseXpath(patchNode.attributes['sel'] || '');
  786. const node = paths[paths.length - 1];
  787. const content = TXml.getContents(patchNode) || '';
  788. if (node.name === 'MPD') {
  789. if (node.attribute === 'mediaPresentationDuration') {
  790. const content = TXml.getContents(patchNode) || '';
  791. this.parsePatchMediaPresentationDurationChange_(content);
  792. } else if (node.attribute === 'type') {
  793. this.parsePatchMpdTypeChange_(content);
  794. } else if (node.attribute === 'publishTime') {
  795. this.manifestPatchContext_.publishTime = TXml.parseDate(content) || 0;
  796. } else if (node.attribute === null && patchNode.tagName === 'add') {
  797. periodAdditions.push(patchNode);
  798. } else {
  799. handled = false;
  800. }
  801. } else if (node.name === 'PatchLocation') {
  802. this.updatePatchLocationNodes_(patchNode);
  803. } else if (node.name === 'Period') {
  804. if (patchNode.tagName === 'add') {
  805. periodAdditions.push(patchNode);
  806. } else if (patchNode.tagName === 'remove' && node.id) {
  807. this.removePatchPeriod_(node.id);
  808. }
  809. } else if (node.name === 'SegmentTemplate') {
  810. const timelines = this.modifySegmentTemplate_(patchNode);
  811. for (const timeline of timelines) {
  812. modifiedTimelines.add(timeline);
  813. }
  814. } else if (node.name === 'SegmentTimeline' || node.name === 'S') {
  815. const timelines = this.modifyTimepoints_(patchNode);
  816. for (const timeline of timelines) {
  817. modifiedTimelines.add(timeline);
  818. }
  819. } else {
  820. handled = false;
  821. }
  822. if (!handled) {
  823. shaka.log.warning('Unhandled ' + patchNode.tagName + ' operation',
  824. patchNode.attributes['sel']);
  825. }
  826. }
  827. for (const timeline of modifiedTimelines) {
  828. this.parsePatchSegment_(timeline);
  829. }
  830. // Add new periods after extending timelines, as new periods
  831. // remove context cache of previous periods.
  832. for (const periodAddition of periodAdditions) {
  833. newPeriods.push(...this.parsePatchPeriod_(periodAddition));
  834. }
  835. if (newPeriods.length) {
  836. this.manifest_.periodCount += newPeriods.length;
  837. this.manifest_.gapCount = this.gapCount_;
  838. await this.postPeriodProcessing_(newPeriods, /* isPatchUpdate= */ true);
  839. }
  840. if (this.manifestPatchContext_.type == 'static') {
  841. const duration = this.manifestPatchContext_.mediaPresentationDuration;
  842. this.manifest_.presentationTimeline.setDuration(duration || Infinity);
  843. }
  844. }
  845. /**
  846. * Handles manifest type changes, this transition is expected to be
  847. * "dyanmic" to "static".
  848. *
  849. * @param {!string} mpdType
  850. * @private
  851. */
  852. parsePatchMpdTypeChange_(mpdType) {
  853. this.manifest_.presentationTimeline.setStatic(mpdType == 'static');
  854. this.manifestPatchContext_.type = mpdType;
  855. for (const context of this.contextCache_.values()) {
  856. context.dynamic = mpdType == 'dynamic';
  857. }
  858. if (mpdType == 'static') {
  859. // Manifest is no longer dynamic, so stop live updates.
  860. this.updatePeriod_ = -1;
  861. }
  862. }
  863. /**
  864. * @param {string} durationString
  865. * @private
  866. */
  867. parsePatchMediaPresentationDurationChange_(durationString) {
  868. const duration = shaka.util.TXml.parseDuration(durationString);
  869. if (duration == null) {
  870. return;
  871. }
  872. this.manifestPatchContext_.mediaPresentationDuration = duration;
  873. for (const context of this.contextCache_.values()) {
  874. context.mediaPresentationDuration = duration;
  875. }
  876. }
  877. /**
  878. * Ingests a full MPD period element from a patch update
  879. *
  880. * @param {!shaka.extern.xml.Node} periods
  881. * @private
  882. */
  883. parsePatchPeriod_(periods) {
  884. goog.asserts.assert(this.manifestPatchContext_.getBaseUris,
  885. 'Must provide getBaseUris on manifestPatchContext_');
  886. /** @type {shaka.dash.DashParser.Context} */
  887. const context = {
  888. dynamic: this.manifestPatchContext_.type == 'dynamic',
  889. presentationTimeline: this.manifest_.presentationTimeline,
  890. period: null,
  891. periodInfo: null,
  892. adaptationSet: null,
  893. representation: null,
  894. bandwidth: 0,
  895. indexRangeWarningGiven: false,
  896. availabilityTimeOffset: this.manifestPatchContext_.availabilityTimeOffset,
  897. profiles: this.manifestPatchContext_.profiles,
  898. mediaPresentationDuration:
  899. this.manifestPatchContext_.mediaPresentationDuration,
  900. roles: null,
  901. };
  902. const periodsAndDuration = this.parsePeriods_(context,
  903. this.manifestPatchContext_.getBaseUris, periods);
  904. return periodsAndDuration.periods;
  905. }
  906. /**
  907. * @param {string} periodId
  908. * @private
  909. */
  910. removePatchPeriod_(periodId) {
  911. const SegmentTemplate = shaka.dash.SegmentTemplate;
  912. this.manifest_.periodCount--;
  913. for (const contextId of this.contextCache_.keys()) {
  914. if (contextId.startsWith(periodId)) {
  915. const context = this.contextCache_.get(contextId);
  916. SegmentTemplate.removeTimepoints(context);
  917. this.parsePatchSegment_(contextId);
  918. this.contextCache_.delete(contextId);
  919. }
  920. }
  921. }
  922. /**
  923. * @param {!Array<shaka.util.TXml.PathNode>} paths
  924. * @return {!Array<string>}
  925. * @private
  926. */
  927. getContextIdsFromPath_(paths) {
  928. let periodId = '';
  929. let adaptationSetId = '';
  930. let adaptationSetPosition = -1;
  931. let representationId = '';
  932. for (const node of paths) {
  933. if (node.name === 'Period') {
  934. periodId = node.id;
  935. } else if (node.name === 'AdaptationSet') {
  936. adaptationSetId = node.id;
  937. if (node.position !== null) {
  938. adaptationSetPosition = node.position;
  939. }
  940. } else if (node.name === 'Representation') {
  941. representationId = node.id;
  942. }
  943. }
  944. /** @type {!Array<string>} */
  945. const contextIds = [];
  946. if (representationId) {
  947. contextIds.push(periodId + ',' + representationId);
  948. } else {
  949. if (adaptationSetId) {
  950. for (const context of this.contextCache_.values()) {
  951. if (context.period.id === periodId &&
  952. context.adaptationSet.id === adaptationSetId &&
  953. context.representation.id) {
  954. contextIds.push(periodId + ',' + context.representation.id);
  955. }
  956. }
  957. } else {
  958. if (adaptationSetPosition > -1) {
  959. for (const context of this.contextCache_.values()) {
  960. if (context.period.id === periodId &&
  961. context.adaptationSet.position === adaptationSetPosition &&
  962. context.representation.id) {
  963. contextIds.push(periodId + ',' + context.representation.id);
  964. }
  965. }
  966. }
  967. }
  968. }
  969. return contextIds;
  970. }
  971. /**
  972. * Modifies SegmentTemplate based on MPD patch.
  973. *
  974. * @param {!shaka.extern.xml.Node} patchNode
  975. * @return {!Array<string>} context ids with updated timeline
  976. * @private
  977. */
  978. modifySegmentTemplate_(patchNode) {
  979. const TXml = shaka.util.TXml;
  980. const paths = TXml.parseXpath(patchNode.attributes['sel'] || '');
  981. const lastPath = paths[paths.length - 1];
  982. if (!lastPath.attribute) {
  983. return [];
  984. }
  985. const contextIds = this.getContextIdsFromPath_(paths);
  986. const content = TXml.getContents(patchNode) || '';
  987. for (const contextId of contextIds) {
  988. /** @type {shaka.dash.DashParser.Context} */
  989. const context = this.contextCache_.get(contextId);
  990. goog.asserts.assert(context && context.representation.segmentTemplate,
  991. 'cannot modify segment template');
  992. TXml.modifyNodeAttribute(context.representation.segmentTemplate,
  993. patchNode.tagName, lastPath.attribute, content);
  994. }
  995. return contextIds;
  996. }
  997. /**
  998. * Ingests Patch MPD segments into timeline.
  999. *
  1000. * @param {!shaka.extern.xml.Node} patchNode
  1001. * @return {!Array<string>} context ids with updated timeline
  1002. * @private
  1003. */
  1004. modifyTimepoints_(patchNode) {
  1005. const TXml = shaka.util.TXml;
  1006. const SegmentTemplate = shaka.dash.SegmentTemplate;
  1007. const paths = TXml.parseXpath(patchNode.attributes['sel'] || '');
  1008. const contextIds = this.getContextIdsFromPath_(paths);
  1009. for (const contextId of contextIds) {
  1010. /** @type {shaka.dash.DashParser.Context} */
  1011. const context = this.contextCache_.get(contextId);
  1012. SegmentTemplate.modifyTimepoints(context, patchNode);
  1013. }
  1014. return contextIds;
  1015. }
  1016. /**
  1017. * Parses modified segments.
  1018. *
  1019. * @param {string} contextId
  1020. * @private
  1021. */
  1022. parsePatchSegment_(contextId) {
  1023. /** @type {shaka.dash.DashParser.Context} */
  1024. const context = this.contextCache_.get(contextId);
  1025. const currentStream = this.streamMap_[contextId];
  1026. goog.asserts.assert(currentStream, 'stream should exist');
  1027. if (currentStream.segmentIndex) {
  1028. currentStream.segmentIndex.evict(
  1029. this.manifest_.presentationTimeline.getSegmentAvailabilityStart());
  1030. }
  1031. try {
  1032. const requestSegment = (uris, startByte, endByte, isInit) => {
  1033. return this.requestSegment_(uris, startByte, endByte, isInit);
  1034. };
  1035. // TODO we should obtain lastSegmentNumber if possible
  1036. const streamInfo = shaka.dash.SegmentTemplate.createStreamInfo(
  1037. context, requestSegment, this.streamMap_, /* isUpdate= */ true,
  1038. this.config_.dash.initialSegmentLimit, this.periodDurations_,
  1039. context.representation.aesKey, /* lastSegmentNumber= */ null,
  1040. /* isPatchUpdate= */ true);
  1041. currentStream.createSegmentIndex = async () => {
  1042. if (!currentStream.segmentIndex) {
  1043. currentStream.segmentIndex =
  1044. await streamInfo.generateSegmentIndex();
  1045. }
  1046. };
  1047. } catch (error) {
  1048. const ContentType = shaka.util.ManifestParserUtils.ContentType;
  1049. const contentType = context.representation.contentType;
  1050. const isText = contentType == ContentType.TEXT ||
  1051. contentType == ContentType.APPLICATION;
  1052. const isImage = contentType == ContentType.IMAGE;
  1053. if (!(isText || isImage) ||
  1054. error.code != shaka.util.Error.Code.DASH_NO_SEGMENT_INFO) {
  1055. // We will ignore any DASH_NO_SEGMENT_INFO errors for text/image
  1056. throw error;
  1057. }
  1058. }
  1059. }
  1060. /**
  1061. * Reads maxLatency and maxPlaybackRate properties from service
  1062. * description element.
  1063. *
  1064. * @param {!shaka.extern.xml.Node} mpd
  1065. * @return {?shaka.extern.ServiceDescription}
  1066. * @private
  1067. */
  1068. parseServiceDescription_(mpd) {
  1069. const TXml = shaka.util.TXml;
  1070. const elem = TXml.findChild(mpd, 'ServiceDescription');
  1071. if (!elem ) {
  1072. return null;
  1073. }
  1074. const latencyNode = TXml.findChild(elem, 'Latency');
  1075. const playbackRateNode = TXml.findChild(elem, 'PlaybackRate');
  1076. if (!latencyNode && !playbackRateNode) {
  1077. return null;
  1078. }
  1079. const description = {};
  1080. if (latencyNode) {
  1081. if ('target' in latencyNode.attributes) {
  1082. description.targetLatency =
  1083. parseInt(latencyNode.attributes['target'], 10) / 1000;
  1084. }
  1085. if ('max' in latencyNode.attributes) {
  1086. description.maxLatency =
  1087. parseInt(latencyNode.attributes['max'], 10) / 1000;
  1088. }
  1089. if ('min' in latencyNode.attributes) {
  1090. description.minLatency =
  1091. parseInt(latencyNode.attributes['min'], 10) / 1000;
  1092. }
  1093. }
  1094. if (playbackRateNode) {
  1095. if ('max' in playbackRateNode.attributes) {
  1096. description.maxPlaybackRate =
  1097. parseFloat(playbackRateNode.attributes['max']);
  1098. }
  1099. if ('min' in playbackRateNode.attributes) {
  1100. description.minPlaybackRate =
  1101. parseFloat(playbackRateNode.attributes['min']);
  1102. }
  1103. }
  1104. return description;
  1105. }
  1106. /**
  1107. * Reads chaining url.
  1108. *
  1109. * @param {!shaka.extern.xml.Node} mpd
  1110. * @return {?string}
  1111. * @private
  1112. */
  1113. parseMpdChaining_(mpd) {
  1114. const TXml = shaka.util.TXml;
  1115. const supplementalProperties =
  1116. TXml.findChildren(mpd, 'SupplementalProperty');
  1117. if (!supplementalProperties.length) {
  1118. return null;
  1119. }
  1120. for (const prop of supplementalProperties) {
  1121. const schemeId = prop.attributes['schemeIdUri'];
  1122. if (schemeId == 'urn:mpeg:dash:chaining:2016') {
  1123. return prop.attributes['value'];
  1124. }
  1125. }
  1126. return null;
  1127. }
  1128. /**
  1129. * Reads and parses the periods from the manifest. This first does some
  1130. * partial parsing so the start and duration is available when parsing
  1131. * children.
  1132. *
  1133. * @param {shaka.dash.DashParser.Context} context
  1134. * @param {function():!Array.<string>} getBaseUris
  1135. * @param {!shaka.extern.xml.Node} mpd
  1136. * @return {{
  1137. * periods: !Array.<shaka.extern.Period>,
  1138. * duration: ?number,
  1139. * durationDerivedFromPeriods: boolean
  1140. * }}
  1141. * @private
  1142. */
  1143. parsePeriods_(context, getBaseUris, mpd) {
  1144. const TXml = shaka.util.TXml;
  1145. let presentationDuration = context.mediaPresentationDuration;
  1146. if (!presentationDuration) {
  1147. presentationDuration = TXml.parseAttr(
  1148. mpd, 'mediaPresentationDuration', TXml.parseDuration);
  1149. this.manifestPatchContext_.mediaPresentationDuration =
  1150. presentationDuration;
  1151. }
  1152. let seekRangeStart = 0;
  1153. if (this.manifest_ && this.manifest_.presentationTimeline &&
  1154. this.isTransitionFromDynamicToStatic_) {
  1155. seekRangeStart = this.manifest_.presentationTimeline.getSeekRangeStart();
  1156. }
  1157. const periods = [];
  1158. let prevEnd = seekRangeStart;
  1159. const periodNodes = TXml.findChildren(mpd, 'Period');
  1160. for (let i = 0; i < periodNodes.length; i++) {
  1161. const elem = periodNodes[i];
  1162. const next = periodNodes[i + 1];
  1163. const start = /** @type {number} */ (
  1164. TXml.parseAttr(elem, 'start', TXml.parseDuration, prevEnd));
  1165. const periodId = elem.attributes['id'];
  1166. const givenDuration =
  1167. TXml.parseAttr(elem, 'duration', TXml.parseDuration);
  1168. let periodDuration = null;
  1169. if (next) {
  1170. // "The difference between the start time of a Period and the start time
  1171. // of the following Period is the duration of the media content
  1172. // represented by this Period."
  1173. const nextStart =
  1174. TXml.parseAttr(next, 'start', TXml.parseDuration);
  1175. if (nextStart != null) {
  1176. periodDuration = nextStart - start;
  1177. }
  1178. } else if (presentationDuration != null) {
  1179. // "The Period extends until the Period.start of the next Period, or
  1180. // until the end of the Media Presentation in the case of the last
  1181. // Period."
  1182. periodDuration = presentationDuration - start + seekRangeStart;
  1183. }
  1184. const threshold =
  1185. shaka.util.ManifestParserUtils.GAP_OVERLAP_TOLERANCE_SECONDS;
  1186. if (periodDuration && givenDuration &&
  1187. Math.abs(periodDuration - givenDuration) > threshold) {
  1188. shaka.log.warning('There is a gap/overlap between Periods', elem);
  1189. // This means it's a gap, the distance between period starts is
  1190. // larger than the period's duration
  1191. if (periodDuration > givenDuration) {
  1192. this.gapCount_++;
  1193. }
  1194. }
  1195. // Only use the @duration in the MPD if we can't calculate it. We should
  1196. // favor the @start of the following Period. This ensures that there
  1197. // aren't gaps between Periods.
  1198. if (periodDuration == null) {
  1199. periodDuration = givenDuration;
  1200. }
  1201. /**
  1202. * This is to improve robustness when the player observes manifest with
  1203. * past periods that are inconsistent to previous ones.
  1204. *
  1205. * This may happen when a CDN or proxy server switches its upstream from
  1206. * one encoder to another redundant encoder.
  1207. *
  1208. * Skip periods that match all of the following criteria:
  1209. * - Start time is earlier than latest period start time ever seen
  1210. * - Period ID is never seen in the previous manifest
  1211. * - Not the last period in the manifest
  1212. *
  1213. * Periods that meet the aforementioned criteria are considered invalid
  1214. * and should be safe to discard.
  1215. */
  1216. if (this.largestPeriodStartTime_ !== null &&
  1217. periodId !== null && start !== null &&
  1218. start < this.largestPeriodStartTime_ &&
  1219. !this.lastManifestUpdatePeriodIds_.includes(periodId) &&
  1220. i + 1 != periodNodes.length) {
  1221. shaka.log.debug(
  1222. `Skipping Period with ID ${periodId} as its start time is smaller` +
  1223. ' than the largest period start time that has been seen, and ID ' +
  1224. 'is unseen before');
  1225. continue;
  1226. }
  1227. // Save maximum period start time if it is the last period
  1228. if (start !== null &&
  1229. (this.largestPeriodStartTime_ === null ||
  1230. start > this.largestPeriodStartTime_)) {
  1231. this.largestPeriodStartTime_ = start;
  1232. }
  1233. // Parse child nodes.
  1234. const info = {
  1235. start: start,
  1236. duration: periodDuration,
  1237. node: elem,
  1238. isLastPeriod: periodDuration == null || !next,
  1239. };
  1240. const period = this.parsePeriod_(context, getBaseUris, info);
  1241. periods.push(period);
  1242. if (context.period.id && periodDuration) {
  1243. this.periodDurations_[context.period.id] = periodDuration;
  1244. }
  1245. if (periodDuration == null) {
  1246. if (next) {
  1247. // If the duration is still null and we aren't at the end, then we
  1248. // will skip any remaining periods.
  1249. shaka.log.warning(
  1250. 'Skipping Period', i + 1, 'and any subsequent Periods:', 'Period',
  1251. i + 1, 'does not have a valid start time.', next);
  1252. }
  1253. // The duration is unknown, so the end is unknown.
  1254. prevEnd = null;
  1255. break;
  1256. }
  1257. prevEnd = start + periodDuration;
  1258. } // end of period parsing loop
  1259. // Replace previous seen periods with the current one.
  1260. this.lastManifestUpdatePeriodIds_ = periods.map((el) => el.id);
  1261. if (presentationDuration != null) {
  1262. if (prevEnd != null) {
  1263. const threshold =
  1264. shaka.util.ManifestParserUtils.GAP_OVERLAP_TOLERANCE_SECONDS;
  1265. const diference = prevEnd - seekRangeStart - presentationDuration;
  1266. if (Math.abs(diference) > threshold) {
  1267. shaka.log.warning(
  1268. '@mediaPresentationDuration does not match the total duration ',
  1269. 'of all Periods.');
  1270. // Assume @mediaPresentationDuration is correct.
  1271. }
  1272. }
  1273. return {
  1274. periods: periods,
  1275. duration: presentationDuration + seekRangeStart,
  1276. durationDerivedFromPeriods: false,
  1277. };
  1278. } else {
  1279. return {
  1280. periods: periods,
  1281. duration: prevEnd,
  1282. durationDerivedFromPeriods: true,
  1283. };
  1284. }
  1285. }
  1286. /**
  1287. * Parses a Period XML element. Unlike the other parse methods, this is not
  1288. * given the Node; it is given a PeriodInfo structure. Also, partial parsing
  1289. * was done before this was called so start and duration are valid.
  1290. *
  1291. * @param {shaka.dash.DashParser.Context} context
  1292. * @param {function():!Array.<string>} getBaseUris
  1293. * @param {shaka.dash.DashParser.PeriodInfo} periodInfo
  1294. * @return {shaka.extern.Period}
  1295. * @private
  1296. */
  1297. parsePeriod_(context, getBaseUris, periodInfo) {
  1298. const Functional = shaka.util.Functional;
  1299. const TXml = shaka.util.TXml;
  1300. const ContentType = shaka.util.ManifestParserUtils.ContentType;
  1301. context.period = this.createFrame_(periodInfo.node, null, getBaseUris);
  1302. context.periodInfo = periodInfo;
  1303. context.period.availabilityTimeOffset = context.availabilityTimeOffset;
  1304. // If the period doesn't have an ID, give it one based on its start time.
  1305. if (!context.period.id) {
  1306. shaka.log.info(
  1307. 'No Period ID given for Period with start time ' + periodInfo.start +
  1308. ', Assigning a default');
  1309. context.period.id = '__shaka_period_' + periodInfo.start;
  1310. }
  1311. const eventStreamNodes =
  1312. TXml.findChildren(periodInfo.node, 'EventStream');
  1313. const availabilityStart =
  1314. context.presentationTimeline.getSegmentAvailabilityStart();
  1315. for (const node of eventStreamNodes) {
  1316. this.parseEventStream_(
  1317. periodInfo.start, periodInfo.duration, node, availabilityStart);
  1318. }
  1319. const adaptationSetNodes =
  1320. TXml.findChildren(periodInfo.node, 'AdaptationSet');
  1321. const adaptationSets = adaptationSetNodes
  1322. .map((node, position) =>
  1323. this.parseAdaptationSet_(context, position, node))
  1324. .filter(Functional.isNotNull);
  1325. // For dynamic manifests, we use rep IDs internally, and they must be
  1326. // unique.
  1327. if (context.dynamic) {
  1328. const ids = [];
  1329. for (const set of adaptationSets) {
  1330. for (const id of set.representationIds) {
  1331. ids.push(id);
  1332. }
  1333. }
  1334. const uniqueIds = new Set(ids);
  1335. if (ids.length != uniqueIds.size) {
  1336. throw new shaka.util.Error(
  1337. shaka.util.Error.Severity.CRITICAL,
  1338. shaka.util.Error.Category.MANIFEST,
  1339. shaka.util.Error.Code.DASH_DUPLICATE_REPRESENTATION_ID);
  1340. }
  1341. }
  1342. const normalAdaptationSets = adaptationSets
  1343. .filter((as) => { return !as.trickModeFor; });
  1344. const trickModeAdaptationSets = adaptationSets
  1345. .filter((as) => { return as.trickModeFor; });
  1346. // Attach trick mode tracks to normal tracks.
  1347. for (const trickModeSet of trickModeAdaptationSets) {
  1348. const targetIds = trickModeSet.trickModeFor.split(' ');
  1349. for (const normalSet of normalAdaptationSets) {
  1350. if (targetIds.includes(normalSet.id)) {
  1351. for (const stream of normalSet.streams) {
  1352. // There may be multiple trick mode streams, but we do not
  1353. // currently support that. Just choose one.
  1354. // TODO: https://github.com/shaka-project/shaka-player/issues/1528
  1355. stream.trickModeVideo = trickModeSet.streams.find((trickStream) =>
  1356. shaka.util.MimeUtils.getNormalizedCodec(stream.codecs) ==
  1357. shaka.util.MimeUtils.getNormalizedCodec(trickStream.codecs));
  1358. }
  1359. }
  1360. }
  1361. }
  1362. const audioStreams = this.getStreamsFromSets_(
  1363. this.config_.disableAudio,
  1364. normalAdaptationSets,
  1365. ContentType.AUDIO);
  1366. const videoStreams = this.getStreamsFromSets_(
  1367. this.config_.disableVideo,
  1368. normalAdaptationSets,
  1369. ContentType.VIDEO);
  1370. const textStreams = this.getStreamsFromSets_(
  1371. this.config_.disableText,
  1372. normalAdaptationSets,
  1373. ContentType.TEXT);
  1374. const imageStreams = this.getStreamsFromSets_(
  1375. this.config_.disableThumbnails,
  1376. normalAdaptationSets,
  1377. ContentType.IMAGE);
  1378. if (videoStreams.length === 0 && audioStreams.length === 0) {
  1379. throw new shaka.util.Error(
  1380. shaka.util.Error.Severity.CRITICAL,
  1381. shaka.util.Error.Category.MANIFEST,
  1382. shaka.util.Error.Code.DASH_EMPTY_PERIOD,
  1383. );
  1384. }
  1385. return {
  1386. id: context.period.id,
  1387. audioStreams,
  1388. videoStreams,
  1389. textStreams,
  1390. imageStreams,
  1391. };
  1392. }
  1393. /**
  1394. * Gets the streams from the given sets or returns an empty array if disabled
  1395. * or no streams are found.
  1396. * @param {boolean} disabled
  1397. * @param {!Array.<!shaka.dash.DashParser.AdaptationInfo>} adaptationSets
  1398. * @param {string} contentType
  1399. @private
  1400. */
  1401. getStreamsFromSets_(disabled, adaptationSets, contentType) {
  1402. if (disabled || !adaptationSets.length) {
  1403. return [];
  1404. }
  1405. return adaptationSets.reduce((all, part) => {
  1406. if (part.contentType != contentType) {
  1407. return all;
  1408. }
  1409. all.push(...part.streams);
  1410. return all;
  1411. }, []);
  1412. }
  1413. /**
  1414. * Parses an AdaptationSet XML element.
  1415. *
  1416. * @param {shaka.dash.DashParser.Context} context
  1417. * @param {number} position
  1418. * @param {!shaka.extern.xml.Node} elem The AdaptationSet element.
  1419. * @return {?shaka.dash.DashParser.AdaptationInfo}
  1420. * @private
  1421. */
  1422. parseAdaptationSet_(context, position, elem) {
  1423. const TXml = shaka.util.TXml;
  1424. const Functional = shaka.util.Functional;
  1425. const ManifestParserUtils = shaka.util.ManifestParserUtils;
  1426. const ContentType = ManifestParserUtils.ContentType;
  1427. const ContentProtection = shaka.dash.ContentProtection;
  1428. context.adaptationSet = this.createFrame_(elem, context.period, null);
  1429. context.adaptationSet.position = position;
  1430. let main = false;
  1431. const roleElements = TXml.findChildren(elem, 'Role');
  1432. const roleValues = roleElements.map((role) => {
  1433. return role.attributes['value'];
  1434. }).filter(Functional.isNotNull);
  1435. // Default kind for text streams is 'subtitle' if unspecified in the
  1436. // manifest.
  1437. let kind = undefined;
  1438. const isText = context.adaptationSet.contentType == ContentType.TEXT;
  1439. if (isText) {
  1440. kind = ManifestParserUtils.TextStreamKind.SUBTITLE;
  1441. }
  1442. for (const roleElement of roleElements) {
  1443. const scheme = roleElement.attributes['schemeIdUri'];
  1444. if (scheme == null || scheme == 'urn:mpeg:dash:role:2011') {
  1445. // These only apply for the given scheme, but allow them to be specified
  1446. // if there is no scheme specified.
  1447. // See: DASH section 5.8.5.5
  1448. const value = roleElement.attributes['value'];
  1449. switch (value) {
  1450. case 'main':
  1451. main = true;
  1452. break;
  1453. case 'caption':
  1454. case 'subtitle':
  1455. kind = value;
  1456. break;
  1457. }
  1458. }
  1459. }
  1460. // Parallel for HLS VIDEO-RANGE as defined in DASH-IF IOP v4.3 6.2.5.1.
  1461. let videoRange;
  1462. let colorGamut;
  1463. // Ref. https://dashif.org/docs/DASH-IF-IOP-v4.3.pdf
  1464. // If signaled, a Supplemental or Essential Property descriptor
  1465. // shall be used, with the schemeIdUri set to
  1466. // urn:mpeg:mpegB:cicp:<Parameter> as defined in
  1467. // ISO/IEC 23001-8 [49] and <Parameter> one of the
  1468. // following: ColourPrimaries, TransferCharacteristics,
  1469. // or MatrixCoefficients.
  1470. const scheme = 'urn:mpeg:mpegB:cicp';
  1471. const transferCharacteristicsScheme = `${scheme}:TransferCharacteristics`;
  1472. const colourPrimariesScheme = `${scheme}:ColourPrimaries`;
  1473. const matrixCoefficientsScheme = `${scheme}:MatrixCoefficients`;
  1474. const getVideoRangeFromTransferCharacteristicCICP = (cicp) => {
  1475. switch (cicp) {
  1476. case 1:
  1477. case 6:
  1478. case 13:
  1479. case 14:
  1480. case 15:
  1481. return 'SDR';
  1482. case 16:
  1483. return 'PQ';
  1484. case 18:
  1485. return 'HLG';
  1486. }
  1487. return undefined;
  1488. };
  1489. const getColorGamutFromColourPrimariesCICP = (cicp) => {
  1490. switch (cicp) {
  1491. case 1:
  1492. case 5:
  1493. case 6:
  1494. case 7:
  1495. return 'srgb';
  1496. case 9:
  1497. return 'rec2020';
  1498. case 11:
  1499. case 12:
  1500. return 'p3';
  1501. }
  1502. return undefined;
  1503. };
  1504. const essentialProperties =
  1505. TXml.findChildren(elem, 'EssentialProperty');
  1506. // ID of real AdaptationSet if this is a trick mode set:
  1507. let trickModeFor = null;
  1508. let isFastSwitching = false;
  1509. let unrecognizedEssentialProperty = false;
  1510. for (const prop of essentialProperties) {
  1511. const schemeId = prop.attributes['schemeIdUri'];
  1512. if (schemeId == 'http://dashif.org/guidelines/trickmode') {
  1513. trickModeFor = prop.attributes['value'];
  1514. } else if (schemeId == transferCharacteristicsScheme) {
  1515. videoRange = getVideoRangeFromTransferCharacteristicCICP(
  1516. parseInt(prop.attributes['value'], 10),
  1517. );
  1518. } else if (schemeId == colourPrimariesScheme) {
  1519. colorGamut = getColorGamutFromColourPrimariesCICP(
  1520. parseInt(prop.attributes['value'], 10),
  1521. );
  1522. } else if (schemeId == matrixCoefficientsScheme) {
  1523. continue;
  1524. } else if (schemeId == 'urn:mpeg:dash:ssr:2023' &&
  1525. this.config_.dash.enableFastSwitching) {
  1526. isFastSwitching = true;
  1527. } else {
  1528. unrecognizedEssentialProperty = true;
  1529. }
  1530. }
  1531. let lastSegmentNumber = null;
  1532. const supplementalProperties =
  1533. TXml.findChildren(elem, 'SupplementalProperty');
  1534. for (const prop of supplementalProperties) {
  1535. const schemeId = prop.attributes['schemeIdUri'];
  1536. if (schemeId == 'http://dashif.org/guidelines/last-segment-number') {
  1537. lastSegmentNumber = parseInt(prop.attributes['value'], 10) - 1;
  1538. } else if (schemeId == transferCharacteristicsScheme) {
  1539. videoRange = getVideoRangeFromTransferCharacteristicCICP(
  1540. parseInt(prop.attributes['value'], 10),
  1541. );
  1542. } else if (schemeId == colourPrimariesScheme) {
  1543. colorGamut = getColorGamutFromColourPrimariesCICP(
  1544. parseInt(prop.attributes['value'], 10),
  1545. );
  1546. }
  1547. }
  1548. const accessibilities = TXml.findChildren(elem, 'Accessibility');
  1549. const LanguageUtils = shaka.util.LanguageUtils;
  1550. const closedCaptions = new Map();
  1551. /** @type {?shaka.media.ManifestParser.AccessibilityPurpose} */
  1552. let accessibilityPurpose;
  1553. for (const prop of accessibilities) {
  1554. const schemeId = prop.attributes['schemeIdUri'];
  1555. const value = prop.attributes['value'];
  1556. if (schemeId == 'urn:scte:dash:cc:cea-608:2015' &&
  1557. !this.config_.disableText) {
  1558. let channelId = 1;
  1559. if (value != null) {
  1560. const channelAssignments = value.split(';');
  1561. for (const captionStr of channelAssignments) {
  1562. let channel;
  1563. let language;
  1564. // Some closed caption descriptions have channel number and
  1565. // language ("CC1=eng") others may only have language ("eng,spa").
  1566. if (!captionStr.includes('=')) {
  1567. // When the channel assignemnts are not explicitly provided and
  1568. // there are only 2 values provided, it is highly likely that the
  1569. // assignments are CC1 and CC3 (most commonly used CC streams).
  1570. // Otherwise, cycle through all channels arbitrarily (CC1 - CC4)
  1571. // in order of provided langs.
  1572. channel = `CC${channelId}`;
  1573. if (channelAssignments.length == 2) {
  1574. channelId += 2;
  1575. } else {
  1576. channelId ++;
  1577. }
  1578. language = captionStr;
  1579. } else {
  1580. const channelAndLanguage = captionStr.split('=');
  1581. // The channel info can be '1' or 'CC1'.
  1582. // If the channel info only has channel number(like '1'), add 'CC'
  1583. // as prefix so that it can be a full channel id (like 'CC1').
  1584. channel = channelAndLanguage[0].startsWith('CC') ?
  1585. channelAndLanguage[0] : `CC${channelAndLanguage[0]}`;
  1586. // 3 letters (ISO 639-2). In b/187442669, we saw a blank string
  1587. // (CC2=;CC3=), so default to "und" (the code for "undetermined").
  1588. language = channelAndLanguage[1] || 'und';
  1589. }
  1590. closedCaptions.set(channel, LanguageUtils.normalize(language));
  1591. }
  1592. } else {
  1593. // If channel and language information has not been provided, assign
  1594. // 'CC1' as channel id and 'und' as language info.
  1595. closedCaptions.set('CC1', 'und');
  1596. }
  1597. } else if (schemeId == 'urn:scte:dash:cc:cea-708:2015' &&
  1598. !this.config_.disableText) {
  1599. let serviceNumber = 1;
  1600. if (value != null) {
  1601. for (const captionStr of value.split(';')) {
  1602. let service;
  1603. let language;
  1604. // Similar to CEA-608, it is possible that service # assignments
  1605. // are not explicitly provided e.g. "eng;deu;swe" In this case,
  1606. // we just cycle through the services for each language one by one.
  1607. if (!captionStr.includes('=')) {
  1608. service = `svc${serviceNumber}`;
  1609. serviceNumber ++;
  1610. language = captionStr;
  1611. } else {
  1612. // Otherwise, CEA-708 caption values take the form "
  1613. // 1=lang:eng;2=lang:deu" i.e. serviceNumber=lang:threelettercode.
  1614. const serviceAndLanguage = captionStr.split('=');
  1615. service = `svc${serviceAndLanguage[0]}`;
  1616. // The language info can be different formats, lang:eng',
  1617. // or 'lang:eng,war:1,er:1'. Extract the language info.
  1618. language = serviceAndLanguage[1].split(',')[0].split(':').pop();
  1619. }
  1620. closedCaptions.set(service, LanguageUtils.normalize(language));
  1621. }
  1622. } else {
  1623. // If service and language information has not been provided, assign
  1624. // 'svc1' as service number and 'und' as language info.
  1625. closedCaptions.set('svc1', 'und');
  1626. }
  1627. } else if (schemeId == 'urn:mpeg:dash:role:2011') {
  1628. // See DASH IOP 3.9.2 Table 4.
  1629. if (value != null) {
  1630. roleValues.push(value);
  1631. if (value == 'captions') {
  1632. kind = ManifestParserUtils.TextStreamKind.CLOSED_CAPTION;
  1633. }
  1634. }
  1635. } else if (schemeId == 'urn:tva:metadata:cs:AudioPurposeCS:2007') {
  1636. // See DASH DVB Document A168 Rev.6 Table 5.
  1637. if (value == '1') {
  1638. accessibilityPurpose =
  1639. shaka.media.ManifestParser.AccessibilityPurpose.VISUALLY_IMPAIRED;
  1640. } else if (value == '2') {
  1641. accessibilityPurpose =
  1642. shaka.media.ManifestParser.AccessibilityPurpose.HARD_OF_HEARING;
  1643. }
  1644. }
  1645. }
  1646. // According to DASH spec (2014) section 5.8.4.8, "the successful processing
  1647. // of the descriptor is essential to properly use the information in the
  1648. // parent element". According to DASH IOP v3.3, section 3.3.4, "if the
  1649. // scheme or the value" for EssentialProperty is not recognized, "the DASH
  1650. // client shall ignore the parent element."
  1651. if (unrecognizedEssentialProperty) {
  1652. // Stop parsing this AdaptationSet and let the caller filter out the
  1653. // nulls.
  1654. return null;
  1655. }
  1656. const contentProtectionElems =
  1657. TXml.findChildren(elem, 'ContentProtection');
  1658. const contentProtection = ContentProtection.parseFromAdaptationSet(
  1659. contentProtectionElems,
  1660. this.config_.dash.ignoreDrmInfo,
  1661. this.config_.dash.keySystemsByURI);
  1662. const language = shaka.util.LanguageUtils.normalize(
  1663. context.adaptationSet.language || 'und');
  1664. const label = context.adaptationSet.label;
  1665. // Parse Representations into Streams.
  1666. const representations = TXml.findChildren(elem, 'Representation');
  1667. const streams = representations.map((representation) => {
  1668. const parsedRepresentation = this.parseRepresentation_(context,
  1669. contentProtection, kind, language, label, main, roleValues,
  1670. closedCaptions, representation, accessibilityPurpose,
  1671. lastSegmentNumber);
  1672. if (parsedRepresentation) {
  1673. parsedRepresentation.hdr = parsedRepresentation.hdr || videoRange;
  1674. parsedRepresentation.colorGamut =
  1675. parsedRepresentation.colorGamut || colorGamut;
  1676. parsedRepresentation.fastSwitching = isFastSwitching;
  1677. }
  1678. return parsedRepresentation;
  1679. }).filter((s) => !!s);
  1680. if (streams.length == 0) {
  1681. const isImage = context.adaptationSet.contentType == ContentType.IMAGE;
  1682. // Ignore empty AdaptationSets if ignoreEmptyAdaptationSet is true
  1683. // or they are for text/image content.
  1684. if (this.config_.dash.ignoreEmptyAdaptationSet || isText || isImage) {
  1685. return null;
  1686. }
  1687. throw new shaka.util.Error(
  1688. shaka.util.Error.Severity.CRITICAL,
  1689. shaka.util.Error.Category.MANIFEST,
  1690. shaka.util.Error.Code.DASH_EMPTY_ADAPTATION_SET);
  1691. }
  1692. // If AdaptationSet's type is unknown or is ambiguously "application",
  1693. // guess based on the information in the first stream. If the attributes
  1694. // mimeType and codecs are split across levels, they will both be inherited
  1695. // down to the stream level by this point, so the stream will have all the
  1696. // necessary information.
  1697. if (!context.adaptationSet.contentType ||
  1698. context.adaptationSet.contentType == ContentType.APPLICATION) {
  1699. const mimeType = streams[0].mimeType;
  1700. const codecs = streams[0].codecs;
  1701. context.adaptationSet.contentType =
  1702. shaka.dash.DashParser.guessContentType_(mimeType, codecs);
  1703. for (const stream of streams) {
  1704. stream.type = context.adaptationSet.contentType;
  1705. }
  1706. }
  1707. const adaptationId = context.adaptationSet.id ||
  1708. ('__fake__' + this.globalId_++);
  1709. for (const stream of streams) {
  1710. // Some DRM license providers require that we have a default
  1711. // key ID from the manifest in the wrapped license request.
  1712. // Thus, it should be put in drmInfo to be accessible to request filters.
  1713. for (const drmInfo of contentProtection.drmInfos) {
  1714. drmInfo.keyIds = drmInfo.keyIds && stream.keyIds ?
  1715. new Set([...drmInfo.keyIds, ...stream.keyIds]) :
  1716. drmInfo.keyIds || stream.keyIds;
  1717. }
  1718. if (this.config_.dash.enableAudioGroups) {
  1719. stream.groupId = adaptationId;
  1720. }
  1721. }
  1722. const repIds = representations
  1723. .map((node) => { return node.attributes['id']; })
  1724. .filter(shaka.util.Functional.isNotNull);
  1725. return {
  1726. id: adaptationId,
  1727. contentType: context.adaptationSet.contentType,
  1728. language: language,
  1729. main: main,
  1730. streams: streams,
  1731. drmInfos: contentProtection.drmInfos,
  1732. trickModeFor: trickModeFor,
  1733. representationIds: repIds,
  1734. };
  1735. }
  1736. /**
  1737. * Parses a Representation XML element.
  1738. *
  1739. * @param {shaka.dash.DashParser.Context} context
  1740. * @param {shaka.dash.ContentProtection.Context} contentProtection
  1741. * @param {(string|undefined)} kind
  1742. * @param {string} language
  1743. * @param {?string} label
  1744. * @param {boolean} isPrimary
  1745. * @param {!Array.<string>} roles
  1746. * @param {Map.<string, string>} closedCaptions
  1747. * @param {!shaka.extern.xml.Node} node
  1748. * @param {?shaka.media.ManifestParser.AccessibilityPurpose}
  1749. * accessibilityPurpose
  1750. * @param {?number} lastSegmentNumber
  1751. *
  1752. * @return {?shaka.extern.Stream} The Stream, or null when there is a
  1753. * non-critical parsing error.
  1754. * @private
  1755. */
  1756. parseRepresentation_(context, contentProtection, kind, language, label,
  1757. isPrimary, roles, closedCaptions, node, accessibilityPurpose,
  1758. lastSegmentNumber) {
  1759. const TXml = shaka.util.TXml;
  1760. const ContentType = shaka.util.ManifestParserUtils.ContentType;
  1761. context.representation =
  1762. this.createFrame_(node, context.adaptationSet, null);
  1763. const representationId = context.representation.id;
  1764. this.minTotalAvailabilityTimeOffset_ =
  1765. Math.min(this.minTotalAvailabilityTimeOffset_,
  1766. context.representation.availabilityTimeOffset);
  1767. this.isLowLatency_ = this.minTotalAvailabilityTimeOffset_ > 0;
  1768. if (!this.verifyRepresentation_(context.representation)) {
  1769. shaka.log.warning('Skipping Representation', context.representation);
  1770. return null;
  1771. }
  1772. const periodStart = context.periodInfo.start;
  1773. // NOTE: bandwidth is a mandatory attribute according to the spec, and zero
  1774. // does not make sense in the DASH spec's bandwidth formulas.
  1775. // In some content, however, the attribute is missing or zero.
  1776. // To avoid NaN at the variant level on broken content, fall back to zero.
  1777. // https://github.com/shaka-project/shaka-player/issues/938#issuecomment-317278180
  1778. context.bandwidth =
  1779. TXml.parseAttr(node, 'bandwidth', TXml.parsePositiveInt) || 0;
  1780. context.roles = roles;
  1781. /** @type {?shaka.dash.DashParser.StreamInfo} */
  1782. let streamInfo;
  1783. const contentType = context.representation.contentType;
  1784. const isText = contentType == ContentType.TEXT ||
  1785. contentType == ContentType.APPLICATION;
  1786. const isImage = contentType == ContentType.IMAGE;
  1787. try {
  1788. /** @type {shaka.extern.aesKey|undefined} */
  1789. let aesKey = undefined;
  1790. if (contentProtection.aes128Info) {
  1791. const getBaseUris = context.representation.getBaseUris;
  1792. const uris = shaka.util.ManifestParserUtils.resolveUris(
  1793. getBaseUris(), [contentProtection.aes128Info.keyUri]);
  1794. const requestType = shaka.net.NetworkingEngine.RequestType.KEY;
  1795. const request = shaka.net.NetworkingEngine.makeRequest(
  1796. uris, this.config_.retryParameters);
  1797. aesKey = {
  1798. bitsKey: 128,
  1799. blockCipherMode: 'CBC',
  1800. iv: contentProtection.aes128Info.iv,
  1801. firstMediaSequenceNumber: 0,
  1802. };
  1803. // Don't download the key object until the segment is parsed, to
  1804. // avoid a startup delay for long manifests with lots of keys.
  1805. aesKey.fetchKey = async () => {
  1806. const keyResponse =
  1807. await this.makeNetworkRequest_(request, requestType);
  1808. // keyResponse.status is undefined when URI is
  1809. // "data:text/plain;base64,"
  1810. if (!keyResponse.data || keyResponse.data.byteLength != 16) {
  1811. throw new shaka.util.Error(
  1812. shaka.util.Error.Severity.CRITICAL,
  1813. shaka.util.Error.Category.MANIFEST,
  1814. shaka.util.Error.Code.AES_128_INVALID_KEY_LENGTH);
  1815. }
  1816. const algorithm = {
  1817. name: 'AES-CBC',
  1818. };
  1819. aesKey.cryptoKey = await window.crypto.subtle.importKey(
  1820. 'raw', keyResponse.data, algorithm, true, ['decrypt']);
  1821. aesKey.fetchKey = undefined; // No longer needed.
  1822. };
  1823. }
  1824. context.representation.aesKey = aesKey;
  1825. const requestSegment = (uris, startByte, endByte, isInit) => {
  1826. return this.requestSegment_(uris, startByte, endByte, isInit);
  1827. };
  1828. if (context.representation.segmentBase) {
  1829. streamInfo = shaka.dash.SegmentBase.createStreamInfo(
  1830. context, requestSegment, aesKey);
  1831. } else if (context.representation.segmentList) {
  1832. streamInfo = shaka.dash.SegmentList.createStreamInfo(
  1833. context, this.streamMap_, aesKey);
  1834. } else if (context.representation.segmentTemplate) {
  1835. const hasManifest = !!this.manifest_;
  1836. streamInfo = shaka.dash.SegmentTemplate.createStreamInfo(
  1837. context, requestSegment, this.streamMap_, hasManifest,
  1838. this.config_.dash.initialSegmentLimit, this.periodDurations_,
  1839. aesKey, lastSegmentNumber, /* isPatchUpdate= */ false);
  1840. } else {
  1841. goog.asserts.assert(isText,
  1842. 'Must have Segment* with non-text streams.');
  1843. const duration = context.periodInfo.duration || 0;
  1844. const getBaseUris = context.representation.getBaseUris;
  1845. const mimeType = context.representation.mimeType;
  1846. const codecs = context.representation.codecs;
  1847. streamInfo = {
  1848. generateSegmentIndex: () => {
  1849. const segmentIndex = shaka.media.SegmentIndex.forSingleSegment(
  1850. periodStart, duration, getBaseUris());
  1851. segmentIndex.forEachTopLevelReference((ref) => {
  1852. ref.mimeType = mimeType;
  1853. ref.codecs = codecs;
  1854. });
  1855. return Promise.resolve(segmentIndex);
  1856. },
  1857. };
  1858. }
  1859. } catch (error) {
  1860. if ((isText || isImage) &&
  1861. error.code == shaka.util.Error.Code.DASH_NO_SEGMENT_INFO) {
  1862. // We will ignore any DASH_NO_SEGMENT_INFO errors for text/image
  1863. // streams.
  1864. return null;
  1865. }
  1866. // For anything else, re-throw.
  1867. throw error;
  1868. }
  1869. const contentProtectionElems =
  1870. TXml.findChildren(node, 'ContentProtection');
  1871. const keyId = shaka.dash.ContentProtection.parseFromRepresentation(
  1872. contentProtectionElems, contentProtection,
  1873. this.config_.dash.ignoreDrmInfo,
  1874. this.config_.dash.keySystemsByURI);
  1875. const keyIds = new Set(keyId ? [keyId] : []);
  1876. // Detect the presence of E-AC3 JOC audio content, using DD+JOC signaling.
  1877. // See: ETSI TS 103 420 V1.2.1 (2018-10)
  1878. const supplementalPropertyElems =
  1879. TXml.findChildren(node, 'SupplementalProperty');
  1880. const hasJoc = supplementalPropertyElems.some((element) => {
  1881. const expectedUri = 'tag:dolby.com,2018:dash:EC3_ExtensionType:2018';
  1882. const expectedValue = 'JOC';
  1883. return element.attributes['schemeIdUri'] == expectedUri &&
  1884. element.attributes['value'] == expectedValue;
  1885. });
  1886. let spatialAudio = false;
  1887. if (hasJoc) {
  1888. spatialAudio = true;
  1889. }
  1890. let forced = false;
  1891. if (isText) {
  1892. // See: https://github.com/shaka-project/shaka-player/issues/2122 and
  1893. // https://github.com/Dash-Industry-Forum/DASH-IF-IOP/issues/165
  1894. forced = roles.includes('forced_subtitle') ||
  1895. roles.includes('forced-subtitle');
  1896. }
  1897. let tilesLayout;
  1898. if (isImage) {
  1899. const essentialPropertyElems =
  1900. TXml.findChildren(node, 'EssentialProperty');
  1901. const thumbnailTileElem = essentialPropertyElems.find((element) => {
  1902. const expectedUris = [
  1903. 'http://dashif.org/thumbnail_tile',
  1904. 'http://dashif.org/guidelines/thumbnail_tile',
  1905. ];
  1906. return expectedUris.includes(element.attributes['schemeIdUri']);
  1907. });
  1908. if (thumbnailTileElem) {
  1909. tilesLayout = thumbnailTileElem.attributes['value'];
  1910. }
  1911. // Filter image adaptation sets that has no tilesLayout.
  1912. if (!tilesLayout) {
  1913. return null;
  1914. }
  1915. }
  1916. let hdr;
  1917. const profiles = context.profiles;
  1918. const codecs = context.representation.codecs;
  1919. const hevcHDR = 'http://dashif.org/guidelines/dash-if-uhd#hevc-hdr-pq10';
  1920. if (profiles.includes(hevcHDR) && (codecs.includes('hvc1.2.4.L153.B0') ||
  1921. codecs.includes('hev1.2.4.L153.B0'))) {
  1922. hdr = 'PQ';
  1923. }
  1924. const contextId = context.representation.id ?
  1925. context.period.id + ',' + context.representation.id : '';
  1926. if (this.patchLocationNodes_.length && representationId) {
  1927. this.contextCache_.set(`${context.period.id},${representationId}`,
  1928. this.cloneContext_(context));
  1929. }
  1930. /** @type {shaka.extern.Stream} */
  1931. let stream;
  1932. if (contextId && this.streamMap_[contextId]) {
  1933. stream = this.streamMap_[contextId];
  1934. } else {
  1935. stream = {
  1936. id: this.globalId_++,
  1937. originalId: context.representation.id,
  1938. groupId: null,
  1939. createSegmentIndex: () => Promise.resolve(),
  1940. closeSegmentIndex: () => {
  1941. if (stream.segmentIndex) {
  1942. stream.segmentIndex.release();
  1943. stream.segmentIndex = null;
  1944. }
  1945. },
  1946. segmentIndex: null,
  1947. mimeType: context.representation.mimeType,
  1948. codecs,
  1949. frameRate: context.representation.frameRate,
  1950. pixelAspectRatio: context.representation.pixelAspectRatio,
  1951. bandwidth: context.bandwidth,
  1952. width: context.representation.width,
  1953. height: context.representation.height,
  1954. kind,
  1955. encrypted: contentProtection.drmInfos.length > 0,
  1956. drmInfos: contentProtection.drmInfos,
  1957. keyIds,
  1958. language,
  1959. originalLanguage: context.adaptationSet.language,
  1960. label,
  1961. type: context.adaptationSet.contentType,
  1962. primary: isPrimary,
  1963. trickModeVideo: null,
  1964. emsgSchemeIdUris:
  1965. context.representation.emsgSchemeIdUris,
  1966. roles,
  1967. forced,
  1968. channelsCount: context.representation.numChannels,
  1969. audioSamplingRate: context.representation.audioSamplingRate,
  1970. spatialAudio,
  1971. closedCaptions,
  1972. hdr,
  1973. colorGamut: undefined,
  1974. videoLayout: undefined,
  1975. tilesLayout,
  1976. accessibilityPurpose,
  1977. external: false,
  1978. fastSwitching: false,
  1979. fullMimeTypes: new Set([shaka.util.MimeUtils.getFullType(
  1980. context.representation.mimeType, context.representation.codecs)]),
  1981. };
  1982. }
  1983. stream.createSegmentIndex = async () => {
  1984. if (!stream.segmentIndex) {
  1985. stream.segmentIndex = await streamInfo.generateSegmentIndex();
  1986. }
  1987. };
  1988. if (contextId && context.dynamic && !this.streamMap_[contextId]) {
  1989. this.streamMap_[contextId] = stream;
  1990. }
  1991. return stream;
  1992. }
  1993. /**
  1994. * Clone context and remove xml document references.
  1995. *
  1996. * @param {!shaka.dash.DashParser.Context} context
  1997. * @return {!shaka.dash.DashParser.Context}
  1998. * @private
  1999. */
  2000. cloneContext_(context) {
  2001. const contextClone = /** @type {!shaka.dash.DashParser.Context} */({});
  2002. for (const k of Object.keys(context)) {
  2003. if (['period', 'adaptationSet', 'representation'].includes(k)) {
  2004. /** @type {shaka.dash.DashParser.InheritanceFrame} */
  2005. const frameRef = context[k];
  2006. contextClone[k] = {
  2007. segmentBase: null,
  2008. segmentList: null,
  2009. segmentTemplate: frameRef.segmentTemplate,
  2010. getBaseUris: frameRef.getBaseUris,
  2011. width: frameRef.width,
  2012. height: frameRef.height,
  2013. contentType: frameRef.contentType,
  2014. mimeType: frameRef.mimeType,
  2015. language: frameRef.language,
  2016. codecs: frameRef.codecs,
  2017. frameRate: frameRef.frameRate,
  2018. pixelAspectRatio: frameRef.pixelAspectRatio,
  2019. emsgSchemeIdUris: frameRef.emsgSchemeIdUris,
  2020. id: frameRef.id,
  2021. position: frameRef.position,
  2022. numChannels: frameRef.numChannels,
  2023. audioSamplingRate: frameRef.audioSamplingRate,
  2024. availabilityTimeOffset: frameRef.availabilityTimeOffset,
  2025. initialization: frameRef.initialization,
  2026. };
  2027. } else if (k == 'periodInfo') {
  2028. /** @type {shaka.dash.DashParser.PeriodInfo} */
  2029. const frameRef = context[k];
  2030. contextClone[k] = {
  2031. start: frameRef.start,
  2032. duration: frameRef.duration,
  2033. node: null,
  2034. isLastPeriod: frameRef.isLastPeriod,
  2035. };
  2036. } else {
  2037. contextClone[k] = context[k];
  2038. }
  2039. }
  2040. return contextClone;
  2041. }
  2042. /**
  2043. * Called when the update timer ticks.
  2044. *
  2045. * @return {!Promise}
  2046. * @private
  2047. */
  2048. async onUpdate_() {
  2049. goog.asserts.assert(this.updatePeriod_ >= 0,
  2050. 'There should be an update period');
  2051. shaka.log.info('Updating manifest...');
  2052. // Default the update delay to 0 seconds so that if there is an error we can
  2053. // try again right away.
  2054. let updateDelay = 0;
  2055. try {
  2056. updateDelay = await this.requestManifest_();
  2057. } catch (error) {
  2058. goog.asserts.assert(error instanceof shaka.util.Error,
  2059. 'Should only receive a Shaka error');
  2060. // Try updating again, but ensure we haven't been destroyed.
  2061. if (this.playerInterface_) {
  2062. if (this.config_.raiseFatalErrorOnManifestUpdateRequestFailure) {
  2063. this.playerInterface_.onError(error);
  2064. return;
  2065. }
  2066. // We will retry updating, so override the severity of the error.
  2067. error.severity = shaka.util.Error.Severity.RECOVERABLE;
  2068. this.playerInterface_.onError(error);
  2069. }
  2070. }
  2071. // Detect a call to stop()
  2072. if (!this.playerInterface_) {
  2073. return;
  2074. }
  2075. this.playerInterface_.onManifestUpdated();
  2076. this.setUpdateTimer_(updateDelay);
  2077. }
  2078. /**
  2079. * Update now the manifest
  2080. *
  2081. * @private
  2082. */
  2083. updateNow_() {
  2084. this.updateTimer_.tickNow();
  2085. }
  2086. /**
  2087. * Sets the update timer. Does nothing if the manifest does not specify an
  2088. * update period.
  2089. *
  2090. * @param {number} offset An offset, in seconds, to apply to the manifest's
  2091. * update period.
  2092. * @private
  2093. */
  2094. setUpdateTimer_(offset) {
  2095. // NOTE: An updatePeriod_ of -1 means the attribute was missing.
  2096. // An attribute which is present and set to 0 should still result in
  2097. // periodic updates. For more, see:
  2098. // https://github.com/Dash-Industry-Forum/Guidelines-TimingModel/issues/48
  2099. if (this.updatePeriod_ < 0) {
  2100. return;
  2101. }
  2102. let updateTime = this.updatePeriod_;
  2103. if (this.config_.dash.updatePeriod >= 0) {
  2104. updateTime = this.config_.dash.updatePeriod;
  2105. }
  2106. const finalDelay = Math.max(
  2107. updateTime - offset,
  2108. this.averageUpdateDuration_.getEstimate());
  2109. // We do not run the timer as repeating because part of update is async and
  2110. // we need schedule the update after it finished.
  2111. this.updateTimer_.tickAfter(/* seconds= */ finalDelay);
  2112. }
  2113. /**
  2114. * Creates a new inheritance frame for the given element.
  2115. *
  2116. * @param {!shaka.extern.xml.Node} elem
  2117. * @param {?shaka.dash.DashParser.InheritanceFrame} parent
  2118. * @param {?function():!Array.<string>} getBaseUris
  2119. * @return {shaka.dash.DashParser.InheritanceFrame}
  2120. * @private
  2121. */
  2122. createFrame_(elem, parent, getBaseUris) {
  2123. goog.asserts.assert(parent || getBaseUris,
  2124. 'Must provide either parent or getBaseUris');
  2125. const SCTE214 = shaka.dash.DashParser.SCTE214_;
  2126. const SegmentUtils = shaka.media.SegmentUtils;
  2127. const ManifestParserUtils = shaka.util.ManifestParserUtils;
  2128. const TXml = shaka.util.TXml;
  2129. parent = parent || /** @type {shaka.dash.DashParser.InheritanceFrame} */ ({
  2130. contentType: '',
  2131. mimeType: '',
  2132. codecs: '',
  2133. emsgSchemeIdUris: [],
  2134. frameRate: undefined,
  2135. pixelAspectRatio: undefined,
  2136. numChannels: null,
  2137. audioSamplingRate: null,
  2138. availabilityTimeOffset: 0,
  2139. segmentSequenceCadence: 0,
  2140. });
  2141. getBaseUris = getBaseUris || parent.getBaseUris;
  2142. const parseNumber = TXml.parseNonNegativeInt;
  2143. const evalDivision = TXml.evalDivision;
  2144. const id = elem.attributes['id'];
  2145. const uriObjs = TXml.findChildren(elem, 'BaseURL');
  2146. let calculatedBaseUris;
  2147. let someLocationValid = false;
  2148. if (this.contentSteeringManager_) {
  2149. for (const uriObj of uriObjs) {
  2150. const serviceLocation = uriObj.attributes['serviceLocation'];
  2151. const uri = TXml.getContents(uriObj);
  2152. if (serviceLocation && uri) {
  2153. this.contentSteeringManager_.addLocation(
  2154. id, serviceLocation, uri);
  2155. someLocationValid = true;
  2156. }
  2157. }
  2158. }
  2159. if (!someLocationValid || !this.contentSteeringManager_) {
  2160. calculatedBaseUris = uriObjs.map(TXml.getContents);
  2161. }
  2162. const getFrameUris = () => {
  2163. if (!uriObjs.length) {
  2164. return [];
  2165. }
  2166. if (this.contentSteeringManager_ && someLocationValid) {
  2167. return this.contentSteeringManager_.getLocations(id);
  2168. }
  2169. if (calculatedBaseUris) {
  2170. return calculatedBaseUris;
  2171. }
  2172. return [];
  2173. };
  2174. let contentType = elem.attributes['contentType'] || parent.contentType;
  2175. const mimeType = elem.attributes['mimeType'] || parent.mimeType;
  2176. const allCodecs = [
  2177. elem.attributes['codecs'] || parent.codecs,
  2178. ];
  2179. const supplementalCodecs =
  2180. TXml.getAttributeNS(elem, SCTE214, 'supplementalCodecs');
  2181. if (supplementalCodecs) {
  2182. allCodecs.push(supplementalCodecs);
  2183. }
  2184. const codecs = SegmentUtils.codecsFiltering(allCodecs).join(',');
  2185. const frameRate =
  2186. TXml.parseAttr(elem, 'frameRate', evalDivision) || parent.frameRate;
  2187. const pixelAspectRatio =
  2188. elem.attributes['sar'] || parent.pixelAspectRatio;
  2189. const emsgSchemeIdUris = this.emsgSchemeIdUris_(
  2190. TXml.findChildren(elem, 'InbandEventStream'),
  2191. parent.emsgSchemeIdUris);
  2192. const audioChannelConfigs =
  2193. TXml.findChildren(elem, 'AudioChannelConfiguration');
  2194. const numChannels =
  2195. this.parseAudioChannels_(audioChannelConfigs) || parent.numChannels;
  2196. const audioSamplingRate =
  2197. TXml.parseAttr(elem, 'audioSamplingRate', parseNumber) ||
  2198. parent.audioSamplingRate;
  2199. if (!contentType) {
  2200. contentType = shaka.dash.DashParser.guessContentType_(mimeType, codecs);
  2201. }
  2202. const segmentBase = TXml.findChild(elem, 'SegmentBase');
  2203. const segmentTemplate = TXml.findChild(elem, 'SegmentTemplate');
  2204. // The availabilityTimeOffset is the sum of all @availabilityTimeOffset
  2205. // values that apply to the adaptation set, via BaseURL, SegmentBase,
  2206. // or SegmentTemplate elements.
  2207. const segmentBaseAto = segmentBase ?
  2208. (TXml.parseAttr(segmentBase, 'availabilityTimeOffset',
  2209. TXml.parseFloat) || 0) : 0;
  2210. const segmentTemplateAto = segmentTemplate ?
  2211. (TXml.parseAttr(segmentTemplate, 'availabilityTimeOffset',
  2212. TXml.parseFloat) || 0) : 0;
  2213. const baseUriAto = uriObjs && uriObjs.length ?
  2214. (TXml.parseAttr(uriObjs[0], 'availabilityTimeOffset',
  2215. TXml.parseFloat) || 0) : 0;
  2216. const availabilityTimeOffset = parent.availabilityTimeOffset + baseUriAto +
  2217. segmentBaseAto + segmentTemplateAto;
  2218. let segmentSequenceCadence = null;
  2219. const segmentSequenceProperties =
  2220. TXml.findChild(elem, 'SegmentSequenceProperties');
  2221. if (segmentSequenceProperties) {
  2222. const sap = TXml.findChild(segmentSequenceProperties, 'SAP');
  2223. if (sap) {
  2224. segmentSequenceCadence = TXml.parseAttr(sap, 'cadence',
  2225. TXml.parseInt);
  2226. }
  2227. }
  2228. // This attribute is currently non-standard, but it is supported by Kaltura.
  2229. let label = elem.attributes['label'];
  2230. // See DASH IOP 4.3 here https://dashif.org/docs/DASH-IF-IOP-v4.3.pdf (page 35)
  2231. const labelElements = TXml.findChildren(elem, 'Label');
  2232. if (labelElements && labelElements.length) {
  2233. // NOTE: Right now only one label field is supported.
  2234. const firstLabelElement = labelElements[0];
  2235. if (TXml.getTextContents(firstLabelElement)) {
  2236. label = TXml.getTextContents(firstLabelElement);
  2237. }
  2238. }
  2239. return {
  2240. getBaseUris:
  2241. () => ManifestParserUtils.resolveUris(getBaseUris(), getFrameUris()),
  2242. segmentBase: segmentBase || parent.segmentBase,
  2243. segmentList:
  2244. TXml.findChild(elem, 'SegmentList') || parent.segmentList,
  2245. segmentTemplate: segmentTemplate || parent.segmentTemplate,
  2246. width: TXml.parseAttr(elem, 'width', parseNumber) || parent.width,
  2247. height: TXml.parseAttr(elem, 'height', parseNumber) || parent.height,
  2248. contentType: contentType,
  2249. mimeType: mimeType,
  2250. codecs: codecs,
  2251. frameRate: frameRate,
  2252. pixelAspectRatio: pixelAspectRatio,
  2253. emsgSchemeIdUris: emsgSchemeIdUris,
  2254. id: id,
  2255. language: elem.attributes['lang'],
  2256. numChannels: numChannels,
  2257. audioSamplingRate: audioSamplingRate,
  2258. availabilityTimeOffset: availabilityTimeOffset,
  2259. initialization: null,
  2260. segmentSequenceCadence:
  2261. segmentSequenceCadence || parent.segmentSequenceCadence,
  2262. label: label || null,
  2263. };
  2264. }
  2265. /**
  2266. * Returns a new array of InbandEventStream schemeIdUri containing the union
  2267. * of the ones parsed from inBandEventStreams and the ones provided in
  2268. * emsgSchemeIdUris.
  2269. *
  2270. * @param {!Array.<!shaka.extern.xml.Node>} inBandEventStreams
  2271. * Array of InbandEventStream
  2272. * elements to parse and add to the returned array.
  2273. * @param {!Array.<string>} emsgSchemeIdUris Array of parsed
  2274. * InbandEventStream schemeIdUri attributes to add to the returned array.
  2275. * @return {!Array.<string>} schemeIdUris Array of parsed
  2276. * InbandEventStream schemeIdUri attributes.
  2277. * @private
  2278. */
  2279. emsgSchemeIdUris_(inBandEventStreams, emsgSchemeIdUris) {
  2280. const schemeIdUris = emsgSchemeIdUris.slice();
  2281. for (const event of inBandEventStreams) {
  2282. const schemeIdUri = event.attributes['schemeIdUri'];
  2283. if (!schemeIdUris.includes(schemeIdUri)) {
  2284. schemeIdUris.push(schemeIdUri);
  2285. }
  2286. }
  2287. return schemeIdUris;
  2288. }
  2289. /**
  2290. * @param {!Array.<!shaka.extern.xml.Node>} audioChannelConfigs An array of
  2291. * AudioChannelConfiguration elements.
  2292. * @return {?number} The number of audio channels, or null if unknown.
  2293. * @private
  2294. */
  2295. parseAudioChannels_(audioChannelConfigs) {
  2296. for (const elem of audioChannelConfigs) {
  2297. const scheme = elem.attributes['schemeIdUri'];
  2298. if (!scheme) {
  2299. continue;
  2300. }
  2301. const value = elem.attributes['value'];
  2302. if (!value) {
  2303. continue;
  2304. }
  2305. switch (scheme) {
  2306. case 'urn:mpeg:dash:outputChannelPositionList:2012':
  2307. // A space-separated list of speaker positions, so the number of
  2308. // channels is the length of this list.
  2309. return value.trim().split(/ +/).length;
  2310. case 'urn:mpeg:dash:23003:3:audio_channel_configuration:2011':
  2311. case 'urn:dts:dash:audio_channel_configuration:2012': {
  2312. // As far as we can tell, this is a number of channels.
  2313. const intValue = parseInt(value, 10);
  2314. if (!intValue) { // 0 or NaN
  2315. shaka.log.warning('Channel parsing failure! ' +
  2316. 'Ignoring scheme and value', scheme, value);
  2317. continue;
  2318. }
  2319. return intValue;
  2320. }
  2321. case 'tag:dolby.com,2014:dash:audio_channel_configuration:2011':
  2322. case 'urn:dolby:dash:audio_channel_configuration:2011': {
  2323. // A hex-encoded 16-bit integer, in which each bit represents a
  2324. // channel.
  2325. let hexValue = parseInt(value, 16);
  2326. if (!hexValue) { // 0 or NaN
  2327. shaka.log.warning('Channel parsing failure! ' +
  2328. 'Ignoring scheme and value', scheme, value);
  2329. continue;
  2330. }
  2331. // Count the 1-bits in hexValue.
  2332. let numBits = 0;
  2333. while (hexValue) {
  2334. if (hexValue & 1) {
  2335. ++numBits;
  2336. }
  2337. hexValue >>= 1;
  2338. }
  2339. return numBits;
  2340. }
  2341. // Defined by https://dashif.org/identifiers/audio_source_metadata/ and clause 8.2, in ISO/IEC 23001-8.
  2342. case 'urn:mpeg:mpegB:cicp:ChannelConfiguration': {
  2343. const noValue = 0;
  2344. const channelCountMapping = [
  2345. noValue, 1, 2, 3, 4, 5, 6, 8, 2, 3, /* 0--9 */
  2346. 4, 7, 8, 24, 8, 12, 10, 12, 14, 12, /* 10--19 */
  2347. 14, /* 20 */
  2348. ];
  2349. const intValue = parseInt(value, 10);
  2350. if (!intValue) { // 0 or NaN
  2351. shaka.log.warning('Channel parsing failure! ' +
  2352. 'Ignoring scheme and value', scheme, value);
  2353. continue;
  2354. }
  2355. if (intValue > noValue && intValue < channelCountMapping.length) {
  2356. return channelCountMapping[intValue];
  2357. }
  2358. continue;
  2359. }
  2360. default:
  2361. shaka.log.warning(
  2362. 'Unrecognized audio channel scheme:', scheme, value);
  2363. continue;
  2364. }
  2365. }
  2366. return null;
  2367. }
  2368. /**
  2369. * Verifies that a Representation has exactly one Segment* element. Prints
  2370. * warnings if there is a problem.
  2371. *
  2372. * @param {shaka.dash.DashParser.InheritanceFrame} frame
  2373. * @return {boolean} True if the Representation is usable; otherwise return
  2374. * false.
  2375. * @private
  2376. */
  2377. verifyRepresentation_(frame) {
  2378. const ContentType = shaka.util.ManifestParserUtils.ContentType;
  2379. let n = 0;
  2380. n += frame.segmentBase ? 1 : 0;
  2381. n += frame.segmentList ? 1 : 0;
  2382. n += frame.segmentTemplate ? 1 : 0;
  2383. if (n == 0) {
  2384. // TODO: Extend with the list of MIME types registered to TextEngine.
  2385. if (frame.contentType == ContentType.TEXT ||
  2386. frame.contentType == ContentType.APPLICATION) {
  2387. return true;
  2388. } else {
  2389. shaka.log.warning(
  2390. 'Representation does not contain a segment information source:',
  2391. 'the Representation must contain one of SegmentBase, SegmentList,',
  2392. 'SegmentTemplate, or explicitly indicate that it is "text".',
  2393. frame);
  2394. return false;
  2395. }
  2396. }
  2397. if (n != 1) {
  2398. shaka.log.warning(
  2399. 'Representation contains multiple segment information sources:',
  2400. 'the Representation should only contain one of SegmentBase,',
  2401. 'SegmentList, or SegmentTemplate.',
  2402. frame);
  2403. if (frame.segmentBase) {
  2404. shaka.log.info('Using SegmentBase by default.');
  2405. frame.segmentList = null;
  2406. frame.segmentTemplate = null;
  2407. } else {
  2408. goog.asserts.assert(frame.segmentList, 'There should be a SegmentList');
  2409. shaka.log.info('Using SegmentList by default.');
  2410. frame.segmentTemplate = null;
  2411. }
  2412. }
  2413. return true;
  2414. }
  2415. /**
  2416. * Makes a request to the given URI and calculates the clock offset.
  2417. *
  2418. * @param {function():!Array.<string>} getBaseUris
  2419. * @param {string} uri
  2420. * @param {string} method
  2421. * @return {!Promise.<number>}
  2422. * @private
  2423. */
  2424. async requestForTiming_(getBaseUris, uri, method) {
  2425. const uris = [shaka.util.StringUtils.htmlUnescape(uri)];
  2426. const requestUris =
  2427. shaka.util.ManifestParserUtils.resolveUris(getBaseUris(), uris);
  2428. const request = shaka.net.NetworkingEngine.makeRequest(
  2429. requestUris, this.config_.retryParameters);
  2430. request.method = method;
  2431. const type = shaka.net.NetworkingEngine.RequestType.TIMING;
  2432. const operation =
  2433. this.playerInterface_.networkingEngine.request(type, request);
  2434. this.operationManager_.manage(operation);
  2435. const response = await operation.promise;
  2436. let text;
  2437. if (method == 'HEAD') {
  2438. if (!response.headers || !response.headers['date']) {
  2439. shaka.log.warning('UTC timing response is missing',
  2440. 'expected date header');
  2441. return 0;
  2442. }
  2443. text = response.headers['date'];
  2444. } else {
  2445. text = shaka.util.StringUtils.fromUTF8(response.data);
  2446. }
  2447. const date = Date.parse(text);
  2448. if (isNaN(date)) {
  2449. shaka.log.warning('Unable to parse date from UTC timing response');
  2450. return 0;
  2451. }
  2452. return (date - Date.now());
  2453. }
  2454. /**
  2455. * Parses an array of UTCTiming elements.
  2456. *
  2457. * @param {function():!Array.<string>} getBaseUris
  2458. * @param {!Array.<!shaka.extern.xml.Node>} elems
  2459. * @return {!Promise.<number>}
  2460. * @private
  2461. */
  2462. async parseUtcTiming_(getBaseUris, elems) {
  2463. const schemesAndValues = elems.map((elem) => {
  2464. return {
  2465. scheme: elem.attributes['schemeIdUri'],
  2466. value: elem.attributes['value'],
  2467. };
  2468. });
  2469. // If there's nothing specified in the manifest, but we have a default from
  2470. // the config, use that.
  2471. const clockSyncUri = this.config_.dash.clockSyncUri;
  2472. if (!schemesAndValues.length && clockSyncUri) {
  2473. schemesAndValues.push({
  2474. scheme: 'urn:mpeg:dash:utc:http-head:2014',
  2475. value: clockSyncUri,
  2476. });
  2477. }
  2478. for (const sv of schemesAndValues) {
  2479. try {
  2480. const scheme = sv.scheme;
  2481. const value = sv.value;
  2482. switch (scheme) {
  2483. // See DASH IOP Guidelines Section 4.7
  2484. // https://bit.ly/DashIop3-2
  2485. // Some old ISO23009-1 drafts used 2012.
  2486. case 'urn:mpeg:dash:utc:http-head:2014':
  2487. case 'urn:mpeg:dash:utc:http-head:2012':
  2488. // eslint-disable-next-line no-await-in-loop
  2489. return await this.requestForTiming_(getBaseUris, value, 'HEAD');
  2490. case 'urn:mpeg:dash:utc:http-xsdate:2014':
  2491. case 'urn:mpeg:dash:utc:http-iso:2014':
  2492. case 'urn:mpeg:dash:utc:http-xsdate:2012':
  2493. case 'urn:mpeg:dash:utc:http-iso:2012':
  2494. // eslint-disable-next-line no-await-in-loop
  2495. return await this.requestForTiming_(getBaseUris, value, 'GET');
  2496. case 'urn:mpeg:dash:utc:direct:2014':
  2497. case 'urn:mpeg:dash:utc:direct:2012': {
  2498. const date = Date.parse(value);
  2499. return isNaN(date) ? 0 : (date - Date.now());
  2500. }
  2501. case 'urn:mpeg:dash:utc:http-ntp:2014':
  2502. case 'urn:mpeg:dash:utc:ntp:2014':
  2503. case 'urn:mpeg:dash:utc:sntp:2014':
  2504. shaka.log.alwaysWarn('NTP UTCTiming scheme is not supported');
  2505. break;
  2506. default:
  2507. shaka.log.alwaysWarn(
  2508. 'Unrecognized scheme in UTCTiming element', scheme);
  2509. break;
  2510. }
  2511. } catch (e) {
  2512. shaka.log.warning('Error fetching time from UTCTiming elem', e.message);
  2513. }
  2514. }
  2515. shaka.log.alwaysWarn(
  2516. 'A UTCTiming element should always be given in live manifests! ' +
  2517. 'This content may not play on clients with bad clocks!');
  2518. return 0;
  2519. }
  2520. /**
  2521. * Parses an EventStream element.
  2522. *
  2523. * @param {number} periodStart
  2524. * @param {?number} periodDuration
  2525. * @param {!shaka.extern.xml.Node} elem
  2526. * @param {number} availabilityStart
  2527. * @private
  2528. */
  2529. parseEventStream_(periodStart, periodDuration, elem, availabilityStart) {
  2530. const TXml = shaka.util.TXml;
  2531. const parseNumber = shaka.util.TXml.parseNonNegativeInt;
  2532. const schemeIdUri = elem.attributes['schemeIdUri'] || '';
  2533. const value = elem.attributes['value'] || '';
  2534. const timescale = TXml.parseAttr(elem, 'timescale', parseNumber) || 1;
  2535. for (const eventNode of TXml.findChildren(elem, 'Event')) {
  2536. const presentationTime =
  2537. TXml.parseAttr(eventNode, 'presentationTime', parseNumber) || 0;
  2538. const duration =
  2539. TXml.parseAttr(eventNode, 'duration', parseNumber) || 0;
  2540. let startTime = presentationTime / timescale + periodStart;
  2541. let endTime = startTime + (duration / timescale);
  2542. if (periodDuration != null) {
  2543. // An event should not go past the Period, even if the manifest says so.
  2544. // See: Dash sec. 5.10.2.1
  2545. startTime = Math.min(startTime, periodStart + periodDuration);
  2546. endTime = Math.min(endTime, periodStart + periodDuration);
  2547. }
  2548. // Don't add unavailable regions to the timeline.
  2549. if (endTime < availabilityStart) {
  2550. continue;
  2551. }
  2552. /** @type {shaka.extern.TimelineRegionInfo} */
  2553. const region = {
  2554. schemeIdUri: schemeIdUri,
  2555. value: value,
  2556. startTime: startTime,
  2557. endTime: endTime,
  2558. id: eventNode.attributes['id'] || '',
  2559. eventElement: TXml.txmlNodeToDomElement(eventNode),
  2560. eventNode: eventNode,
  2561. };
  2562. this.playerInterface_.onTimelineRegionAdded(region);
  2563. }
  2564. }
  2565. /**
  2566. * Makes a network request on behalf of SegmentBase.createStreamInfo.
  2567. *
  2568. * @param {!Array.<string>} uris
  2569. * @param {?number} startByte
  2570. * @param {?number} endByte
  2571. * @param {boolean} isInit
  2572. * @return {!Promise.<BufferSource>}
  2573. * @private
  2574. */
  2575. async requestSegment_(uris, startByte, endByte, isInit) {
  2576. const requestType = shaka.net.NetworkingEngine.RequestType.SEGMENT;
  2577. const type = isInit ?
  2578. shaka.net.NetworkingEngine.AdvancedRequestType.INIT_SEGMENT :
  2579. shaka.net.NetworkingEngine.AdvancedRequestType.MEDIA_SEGMENT;
  2580. const request = shaka.util.Networking.createSegmentRequest(
  2581. uris,
  2582. startByte,
  2583. endByte,
  2584. this.config_.retryParameters);
  2585. const response = await this.makeNetworkRequest_(
  2586. request, requestType, {type});
  2587. return response.data;
  2588. }
  2589. /**
  2590. * Guess the content type based on MIME type and codecs.
  2591. *
  2592. * @param {string} mimeType
  2593. * @param {string} codecs
  2594. * @return {string}
  2595. * @private
  2596. */
  2597. static guessContentType_(mimeType, codecs) {
  2598. const fullMimeType = shaka.util.MimeUtils.getFullType(mimeType, codecs);
  2599. if (shaka.text.TextEngine.isTypeSupported(fullMimeType)) {
  2600. // If it's supported by TextEngine, it's definitely text.
  2601. // We don't check MediaSourceEngine, because that would report support
  2602. // for platform-supported video and audio types as well.
  2603. return shaka.util.ManifestParserUtils.ContentType.TEXT;
  2604. }
  2605. // Otherwise, just split the MIME type. This handles video and audio
  2606. // types well.
  2607. return mimeType.split('/')[0];
  2608. }
  2609. /**
  2610. * Create a networking request. This will manage the request using the
  2611. * parser's operation manager.
  2612. *
  2613. * @param {shaka.extern.Request} request
  2614. * @param {shaka.net.NetworkingEngine.RequestType} type
  2615. * @param {shaka.extern.RequestContext=} context
  2616. * @return {!Promise.<shaka.extern.Response>}
  2617. * @private
  2618. */
  2619. makeNetworkRequest_(request, type, context) {
  2620. const op = this.playerInterface_.networkingEngine.request(
  2621. type, request, context);
  2622. this.operationManager_.manage(op);
  2623. return op.promise;
  2624. }
  2625. /**
  2626. * @param {!shaka.extern.xml.Node} patchNode
  2627. * @private
  2628. */
  2629. updatePatchLocationNodes_(patchNode) {
  2630. const TXml = shaka.util.TXml;
  2631. TXml.modifyNodes(this.patchLocationNodes_, patchNode);
  2632. }
  2633. /**
  2634. * @return {!Array<string>}
  2635. * @private
  2636. */
  2637. getPatchLocationUris_() {
  2638. const TXml = shaka.util.TXml;
  2639. const mpdId = this.manifestPatchContext_.mpdId;
  2640. const publishTime = this.manifestPatchContext_.publishTime;
  2641. if (!mpdId || !publishTime || !this.patchLocationNodes_.length) {
  2642. return [];
  2643. }
  2644. const now = Date.now() / 1000;
  2645. const patchLocations = this.patchLocationNodes_.filter((patchLocation) => {
  2646. const ttl = TXml.parseNonNegativeInt(patchLocation.attributes['ttl']);
  2647. return !ttl || publishTime + ttl > now;
  2648. })
  2649. .map(TXml.getContents)
  2650. .filter(shaka.util.Functional.isNotNull);
  2651. if (!patchLocations.length) {
  2652. return [];
  2653. }
  2654. return shaka.util.ManifestParserUtils.resolveUris(
  2655. this.manifestUris_, patchLocations);
  2656. }
  2657. };
  2658. /**
  2659. * @typedef {{
  2660. * mpdId: string,
  2661. * type: string,
  2662. * mediaPresentationDuration: ?number,
  2663. * profiles: !Array.<string>,
  2664. * availabilityTimeOffset: number,
  2665. * getBaseUris: ?function():!Array.<string>,
  2666. * publishTime: number
  2667. * }}
  2668. *
  2669. * @property {string} mpdId
  2670. * ID of the original MPD file.
  2671. * @property {string} type
  2672. * Specifies the type of the dash manifest i.e. "static"
  2673. * @property {?number} mediaPresentationDuration
  2674. * Media presentation duration, or null if unknown.
  2675. * @property {!Array.<string>} profiles
  2676. * Profiles of DASH are defined to enable interoperability and the
  2677. * signaling of the use of features.
  2678. * @property {number} availabilityTimeOffset
  2679. * Specifies the total availabilityTimeOffset of the segment.
  2680. * @property {?function():!Array.<string>} getBaseUris
  2681. * An array of absolute base URIs.
  2682. * @property {number} publishTime
  2683. * Time when manifest has been published, in seconds.
  2684. */
  2685. shaka.dash.DashParser.PatchContext;
  2686. /**
  2687. * @const {string}
  2688. * @private
  2689. */
  2690. shaka.dash.DashParser.SCTE214_ = 'urn:scte:dash:scte214-extensions';
  2691. /**
  2692. * @typedef {
  2693. * function(!Array.<string>, ?number, ?number, boolean):
  2694. * !Promise.<BufferSource>
  2695. * }
  2696. */
  2697. shaka.dash.DashParser.RequestSegmentCallback;
  2698. /**
  2699. * @typedef {{
  2700. * segmentBase: ?shaka.extern.xml.Node,
  2701. * segmentList: ?shaka.extern.xml.Node,
  2702. * segmentTemplate: ?shaka.extern.xml.Node,
  2703. * getBaseUris: function():!Array.<string>,
  2704. * width: (number|undefined),
  2705. * height: (number|undefined),
  2706. * contentType: string,
  2707. * mimeType: string,
  2708. * codecs: string,
  2709. * frameRate: (number|undefined),
  2710. * pixelAspectRatio: (string|undefined),
  2711. * emsgSchemeIdUris: !Array.<string>,
  2712. * id: ?string,
  2713. * position: (number|undefined),
  2714. * language: ?string,
  2715. * numChannels: ?number,
  2716. * audioSamplingRate: ?number,
  2717. * availabilityTimeOffset: number,
  2718. * initialization: ?string,
  2719. * aesKey: (shaka.extern.aesKey|undefined),
  2720. * segmentSequenceCadence: number,
  2721. * label: ?string
  2722. * }}
  2723. *
  2724. * @description
  2725. * A collection of elements and properties which are inherited across levels
  2726. * of a DASH manifest.
  2727. *
  2728. * @property {?shaka.extern.xml.Node} segmentBase
  2729. * The XML node for SegmentBase.
  2730. * @property {?shaka.extern.xml.Node} segmentList
  2731. * The XML node for SegmentList.
  2732. * @property {?shaka.extern.xml.Node} segmentTemplate
  2733. * The XML node for SegmentTemplate.
  2734. * @property {function():!Array.<string>} getBaseUris
  2735. * Function than returns an array of absolute base URIs for the frame.
  2736. * @property {(number|undefined)} width
  2737. * The inherited width value.
  2738. * @property {(number|undefined)} height
  2739. * The inherited height value.
  2740. * @property {string} contentType
  2741. * The inherited media type.
  2742. * @property {string} mimeType
  2743. * The inherited MIME type value.
  2744. * @property {string} codecs
  2745. * The inherited codecs value.
  2746. * @property {(number|undefined)} frameRate
  2747. * The inherited framerate value.
  2748. * @property {(string|undefined)} pixelAspectRatio
  2749. * The inherited pixel aspect ratio value.
  2750. * @property {!Array.<string>} emsgSchemeIdUris
  2751. * emsg registered schemeIdUris.
  2752. * @property {?string} id
  2753. * The ID of the element.
  2754. * @property {number|undefined} position
  2755. * Position of the element used for indexing in case of no id
  2756. * @property {?string} language
  2757. * The original language of the element.
  2758. * @property {?number} numChannels
  2759. * The number of audio channels, or null if unknown.
  2760. * @property {?number} audioSamplingRate
  2761. * Specifies the maximum sampling rate of the content, or null if unknown.
  2762. * @property {number} availabilityTimeOffset
  2763. * Specifies the total availabilityTimeOffset of the segment, or 0 if unknown.
  2764. * @property {?string} initialization
  2765. * Specifies the file where the init segment is located, or null.
  2766. * @property {(shaka.extern.aesKey|undefined)} aesKey
  2767. * AES-128 Content protection key
  2768. * @property {number} segmentSequenceCadence
  2769. * Specifies the cadence of independent segments in Segment Sequence
  2770. * Representation.
  2771. * @property {?string} label
  2772. * Label or null if unknown.
  2773. */
  2774. shaka.dash.DashParser.InheritanceFrame;
  2775. /**
  2776. * @typedef {{
  2777. * dynamic: boolean,
  2778. * presentationTimeline: !shaka.media.PresentationTimeline,
  2779. * period: ?shaka.dash.DashParser.InheritanceFrame,
  2780. * periodInfo: ?shaka.dash.DashParser.PeriodInfo,
  2781. * adaptationSet: ?shaka.dash.DashParser.InheritanceFrame,
  2782. * representation: ?shaka.dash.DashParser.InheritanceFrame,
  2783. * bandwidth: number,
  2784. * indexRangeWarningGiven: boolean,
  2785. * availabilityTimeOffset: number,
  2786. * mediaPresentationDuration: ?number,
  2787. * profiles: !Array.<string>,
  2788. * roles: ?Array.<string>
  2789. * }}
  2790. *
  2791. * @description
  2792. * Contains context data for the streams. This is designed to be
  2793. * shallow-copyable, so the parser must overwrite (not modify) each key as the
  2794. * parser moves through the manifest and the parsing context changes.
  2795. *
  2796. * @property {boolean} dynamic
  2797. * True if the MPD is dynamic (not all segments available at once)
  2798. * @property {!shaka.media.PresentationTimeline} presentationTimeline
  2799. * The PresentationTimeline.
  2800. * @property {?shaka.dash.DashParser.InheritanceFrame} period
  2801. * The inheritance from the Period element.
  2802. * @property {?shaka.dash.DashParser.PeriodInfo} periodInfo
  2803. * The Period info for the current Period.
  2804. * @property {?shaka.dash.DashParser.InheritanceFrame} adaptationSet
  2805. * The inheritance from the AdaptationSet element.
  2806. * @property {?shaka.dash.DashParser.InheritanceFrame} representation
  2807. * The inheritance from the Representation element.
  2808. * @property {number} bandwidth
  2809. * The bandwidth of the Representation, or zero if missing.
  2810. * @property {boolean} indexRangeWarningGiven
  2811. * True if the warning about SegmentURL@indexRange has been printed.
  2812. * @property {number} availabilityTimeOffset
  2813. * The sum of the availabilityTimeOffset values that apply to the element.
  2814. * @property {!Array.<string>} profiles
  2815. * Profiles of DASH are defined to enable interoperability and the signaling
  2816. * of the use of features.
  2817. * @property {?number} mediaPresentationDuration
  2818. * Media presentation duration, or null if unknown.
  2819. */
  2820. shaka.dash.DashParser.Context;
  2821. /**
  2822. * @typedef {{
  2823. * start: number,
  2824. * duration: ?number,
  2825. * node: !shaka.extern.xml.Node,
  2826. * isLastPeriod: boolean
  2827. * }}
  2828. *
  2829. * @description
  2830. * Contains information about a Period element.
  2831. *
  2832. * @property {number} start
  2833. * The start time of the period.
  2834. * @property {?number} duration
  2835. * The duration of the period; or null if the duration is not given. This
  2836. * will be non-null for all periods except the last.
  2837. * @property {!shaka.extern.xml.Node} node
  2838. * The XML Node for the Period.
  2839. * @property {boolean} isLastPeriod
  2840. * Whether this Period is the last one in the manifest.
  2841. */
  2842. shaka.dash.DashParser.PeriodInfo;
  2843. /**
  2844. * @typedef {{
  2845. * id: string,
  2846. * contentType: ?string,
  2847. * language: string,
  2848. * main: boolean,
  2849. * streams: !Array.<shaka.extern.Stream>,
  2850. * drmInfos: !Array.<shaka.extern.DrmInfo>,
  2851. * trickModeFor: ?string,
  2852. * representationIds: !Array.<string>
  2853. * }}
  2854. *
  2855. * @description
  2856. * Contains information about an AdaptationSet element.
  2857. *
  2858. * @property {string} id
  2859. * The unique ID of the adaptation set.
  2860. * @property {?string} contentType
  2861. * The content type of the AdaptationSet.
  2862. * @property {string} language
  2863. * The language of the AdaptationSet.
  2864. * @property {boolean} main
  2865. * Whether the AdaptationSet has the 'main' type.
  2866. * @property {!Array.<shaka.extern.Stream>} streams
  2867. * The streams this AdaptationSet contains.
  2868. * @property {!Array.<shaka.extern.DrmInfo>} drmInfos
  2869. * The DRM info for the AdaptationSet.
  2870. * @property {?string} trickModeFor
  2871. * If non-null, this AdaptationInfo represents trick mode tracks. This
  2872. * property is the ID of the normal AdaptationSet these tracks should be
  2873. * associated with.
  2874. * @property {!Array.<string>} representationIds
  2875. * An array of the IDs of the Representations this AdaptationSet contains.
  2876. */
  2877. shaka.dash.DashParser.AdaptationInfo;
  2878. /**
  2879. * @typedef {function():!Promise.<shaka.media.SegmentIndex>}
  2880. * @description
  2881. * An async function which generates and returns a SegmentIndex.
  2882. */
  2883. shaka.dash.DashParser.GenerateSegmentIndexFunction;
  2884. /**
  2885. * @typedef {{
  2886. * generateSegmentIndex: shaka.dash.DashParser.GenerateSegmentIndexFunction
  2887. * }}
  2888. *
  2889. * @description
  2890. * Contains information about a Stream. This is passed from the createStreamInfo
  2891. * methods.
  2892. *
  2893. * @property {shaka.dash.DashParser.GenerateSegmentIndexFunction}
  2894. * generateSegmentIndex
  2895. * An async function to create the SegmentIndex for the stream.
  2896. */
  2897. shaka.dash.DashParser.StreamInfo;
  2898. shaka.media.ManifestParser.registerParserByMime(
  2899. 'application/dash+xml', () => new shaka.dash.DashParser());
  2900. shaka.media.ManifestParser.registerParserByMime(
  2901. 'video/vnd.mpeg.dash.mpd', () => new shaka.dash.DashParser());