Source: lib/mss/mss_parser.js

  1. /*! @license
  2. * Shaka Player
  3. * Copyright 2016 Google LLC
  4. * SPDX-License-Identifier: Apache-2.0
  5. */
  6. goog.provide('shaka.mss.MssParser');
  7. goog.require('goog.asserts');
  8. goog.require('shaka.Deprecate');
  9. goog.require('shaka.abr.Ewma');
  10. goog.require('shaka.log');
  11. goog.require('shaka.media.InitSegmentReference');
  12. goog.require('shaka.media.ManifestParser');
  13. goog.require('shaka.media.PresentationTimeline');
  14. goog.require('shaka.media.QualityObserver');
  15. goog.require('shaka.media.SegmentIndex');
  16. goog.require('shaka.media.SegmentReference');
  17. goog.require('shaka.mss.ContentProtection');
  18. goog.require('shaka.net.NetworkingEngine');
  19. goog.require('shaka.util.Error');
  20. goog.require('shaka.util.LanguageUtils');
  21. goog.require('shaka.util.ManifestParserUtils');
  22. goog.require('shaka.util.MimeUtils');
  23. goog.require('shaka.util.Mp4Generator');
  24. goog.require('shaka.util.OperationManager');
  25. goog.require('shaka.util.PlayerConfiguration');
  26. goog.require('shaka.util.Timer');
  27. goog.require('shaka.util.TXml');
  28. goog.require('shaka.util.XmlUtils');
  29. /**
  30. * Creates a new MSS parser.
  31. *
  32. * @implements {shaka.extern.ManifestParser}
  33. * @export
  34. */
  35. shaka.mss.MssParser = class {
  36. /** Creates a new MSS parser. */
  37. constructor() {
  38. /** @private {?shaka.extern.ManifestConfiguration} */
  39. this.config_ = null;
  40. /** @private {?shaka.extern.ManifestParser.PlayerInterface} */
  41. this.playerInterface_ = null;
  42. /** @private {!Array.<string>} */
  43. this.manifestUris_ = [];
  44. /** @private {?shaka.extern.Manifest} */
  45. this.manifest_ = null;
  46. /** @private {number} */
  47. this.globalId_ = 1;
  48. /**
  49. * The update period in seconds, or 0 for no updates.
  50. * @private {number}
  51. */
  52. this.updatePeriod_ = 0;
  53. /** @private {?shaka.media.PresentationTimeline} */
  54. this.presentationTimeline_ = null;
  55. /**
  56. * An ewma that tracks how long updates take.
  57. * This is to mitigate issues caused by slow parsing on embedded devices.
  58. * @private {!shaka.abr.Ewma}
  59. */
  60. this.averageUpdateDuration_ = new shaka.abr.Ewma(5);
  61. /** @private {shaka.util.Timer} */
  62. this.updateTimer_ = new shaka.util.Timer(() => {
  63. this.onUpdate_();
  64. });
  65. /** @private {!shaka.util.OperationManager} */
  66. this.operationManager_ = new shaka.util.OperationManager();
  67. /**
  68. * @private {!Map.<number, !BufferSource>}
  69. */
  70. this.initSegmentDataByStreamId_ = new Map();
  71. /** @private {function():boolean} */
  72. this.isPreloadFn_ = () => false;
  73. }
  74. /**
  75. * @param {shaka.extern.ManifestConfiguration} config
  76. * @param {(function():boolean)=} isPreloadFn
  77. * @override
  78. * @exportInterface
  79. */
  80. configure(config, isPreloadFn) {
  81. goog.asserts.assert(config.mss != null,
  82. 'MssManifestConfiguration should not be null!');
  83. this.config_ = config;
  84. if (isPreloadFn) {
  85. this.isPreloadFn_ = isPreloadFn;
  86. }
  87. }
  88. /**
  89. * @override
  90. * @exportInterface
  91. */
  92. async start(uri, playerInterface) {
  93. goog.asserts.assert(this.config_, 'Must call configure() before start()!');
  94. this.manifestUris_ = [uri];
  95. this.playerInterface_ = playerInterface;
  96. await this.requestManifest_();
  97. // Make sure that the parser has not been destroyed.
  98. if (!this.playerInterface_) {
  99. throw new shaka.util.Error(
  100. shaka.util.Error.Severity.CRITICAL,
  101. shaka.util.Error.Category.PLAYER,
  102. shaka.util.Error.Code.OPERATION_ABORTED);
  103. }
  104. this.setUpdateTimer_();
  105. goog.asserts.assert(this.manifest_, 'Manifest should be non-null!');
  106. return this.manifest_;
  107. }
  108. /**
  109. * Called when the update timer ticks.
  110. *
  111. * @return {!Promise}
  112. * @private
  113. */
  114. async onUpdate_() {
  115. goog.asserts.assert(this.updatePeriod_ >= 0,
  116. 'There should be an update period');
  117. shaka.log.info('Updating manifest...');
  118. try {
  119. await this.requestManifest_();
  120. } catch (error) {
  121. goog.asserts.assert(error instanceof shaka.util.Error,
  122. 'Should only receive a Shaka error');
  123. // Try updating again, but ensure we haven't been destroyed.
  124. if (this.playerInterface_) {
  125. // We will retry updating, so override the severity of the error.
  126. error.severity = shaka.util.Error.Severity.RECOVERABLE;
  127. this.playerInterface_.onError(error);
  128. }
  129. }
  130. // Detect a call to stop()
  131. if (!this.playerInterface_) {
  132. return;
  133. }
  134. this.setUpdateTimer_();
  135. }
  136. /**
  137. * Sets the update timer. Does nothing if the manifest is not live.
  138. *
  139. * @private
  140. */
  141. setUpdateTimer_() {
  142. if (this.updatePeriod_ <= 0) {
  143. return;
  144. }
  145. const finalDelay = Math.max(
  146. shaka.mss.MssParser.MIN_UPDATE_PERIOD_,
  147. this.updatePeriod_,
  148. this.averageUpdateDuration_.getEstimate());
  149. // We do not run the timer as repeating because part of update is async and
  150. // we need schedule the update after it finished.
  151. this.updateTimer_.tickAfter(/* seconds= */ finalDelay);
  152. }
  153. /**
  154. * @override
  155. * @exportInterface
  156. */
  157. stop() {
  158. this.playerInterface_ = null;
  159. this.config_ = null;
  160. this.manifestUris_ = [];
  161. this.manifest_ = null;
  162. if (this.updateTimer_ != null) {
  163. this.updateTimer_.stop();
  164. this.updateTimer_ = null;
  165. }
  166. this.initSegmentDataByStreamId_.clear();
  167. return this.operationManager_.destroy();
  168. }
  169. /**
  170. * @override
  171. * @exportInterface
  172. */
  173. async update() {
  174. try {
  175. await this.requestManifest_();
  176. } catch (error) {
  177. if (!this.playerInterface_ || !error) {
  178. return;
  179. }
  180. goog.asserts.assert(error instanceof shaka.util.Error, 'Bad error type');
  181. this.playerInterface_.onError(error);
  182. }
  183. }
  184. /**
  185. * @override
  186. * @exportInterface
  187. */
  188. onExpirationUpdated(sessionId, expiration) {
  189. // No-op
  190. }
  191. /**
  192. * @override
  193. * @exportInterface
  194. */
  195. onInitialVariantChosen(variant) {
  196. // No-op
  197. }
  198. /**
  199. * @override
  200. * @exportInterface
  201. */
  202. banLocation(uri) {
  203. // No-op
  204. }
  205. /** @override */
  206. setMediaElement(mediaElement) {
  207. // No-op
  208. }
  209. /**
  210. * Makes a network request for the manifest and parses the resulting data.
  211. *
  212. * @private
  213. */
  214. async requestManifest_() {
  215. const requestType = shaka.net.NetworkingEngine.RequestType.MANIFEST;
  216. const type = shaka.net.NetworkingEngine.AdvancedRequestType.MSS;
  217. const request = shaka.net.NetworkingEngine.makeRequest(
  218. this.manifestUris_, this.config_.retryParameters);
  219. const networkingEngine = this.playerInterface_.networkingEngine;
  220. const startTime = Date.now();
  221. const operation = networkingEngine.request(requestType, request, {
  222. type,
  223. isPreload: this.isPreloadFn_(),
  224. });
  225. this.operationManager_.manage(operation);
  226. const response = await operation.promise;
  227. // Detect calls to stop().
  228. if (!this.playerInterface_) {
  229. return;
  230. }
  231. // For redirections add the response uri to the first entry in the
  232. // Manifest Uris array.
  233. if (response.uri && !this.manifestUris_.includes(response.uri)) {
  234. this.manifestUris_.unshift(response.uri);
  235. }
  236. // This may throw, but it will result in a failed promise.
  237. this.parseManifest_(response.data, response.uri);
  238. // Keep track of how long the longest manifest update took.
  239. const endTime = Date.now();
  240. const updateDuration = (endTime - startTime) / 1000.0;
  241. this.averageUpdateDuration_.sample(1, updateDuration);
  242. }
  243. /**
  244. * Parses the manifest XML. This also handles updates and will update the
  245. * stored manifest.
  246. *
  247. * @param {BufferSource} data
  248. * @param {string} finalManifestUri The final manifest URI, which may
  249. * differ from this.manifestUri_ if there has been a redirect.
  250. * @return {!Promise}
  251. * @private
  252. */
  253. parseManifest_(data, finalManifestUri) {
  254. let manifestData = data;
  255. const manifestPreprocessor = this.config_.mss.manifestPreprocessor;
  256. const defaultManifestPreprocessor =
  257. shaka.util.PlayerConfiguration.defaultManifestPreprocessor;
  258. if (manifestPreprocessor != defaultManifestPreprocessor) {
  259. shaka.Deprecate.deprecateFeature(5,
  260. 'manifest.mss.manifestPreprocessor configuration',
  261. 'Please Use manifest.mss.manifestPreprocessorTXml instead.');
  262. const mssElement =
  263. shaka.util.XmlUtils.parseXml(manifestData, 'SmoothStreamingMedia');
  264. if (!mssElement) {
  265. throw new shaka.util.Error(
  266. shaka.util.Error.Severity.CRITICAL,
  267. shaka.util.Error.Category.MANIFEST,
  268. shaka.util.Error.Code.MSS_INVALID_XML,
  269. finalManifestUri);
  270. }
  271. manifestPreprocessor(mssElement);
  272. manifestData = shaka.util.XmlUtils.toArrayBuffer(mssElement);
  273. }
  274. const mss = shaka.util.TXml.parseXml(manifestData, 'SmoothStreamingMedia');
  275. if (!mss) {
  276. throw new shaka.util.Error(
  277. shaka.util.Error.Severity.CRITICAL,
  278. shaka.util.Error.Category.MANIFEST,
  279. shaka.util.Error.Code.MSS_INVALID_XML,
  280. finalManifestUri);
  281. }
  282. const manifestPreprocessorTXml = this.config_.mss.manifestPreprocessorTXml;
  283. const defaultManifestPreprocessorTXml =
  284. shaka.util.PlayerConfiguration.defaultManifestPreprocessorTXml;
  285. if (manifestPreprocessorTXml != defaultManifestPreprocessorTXml) {
  286. manifestPreprocessorTXml(mss);
  287. }
  288. this.processManifest_(mss, finalManifestUri);
  289. return Promise.resolve();
  290. }
  291. /**
  292. * Takes a formatted MSS and converts it into a manifest.
  293. *
  294. * @param {!shaka.extern.xml.Node} mss
  295. * @param {string} finalManifestUri The final manifest URI, which may
  296. * differ from this.manifestUri_ if there has been a redirect.
  297. * @private
  298. */
  299. processManifest_(mss, finalManifestUri) {
  300. const TXml = shaka.util.TXml;
  301. if (!this.presentationTimeline_) {
  302. this.presentationTimeline_ = new shaka.media.PresentationTimeline(
  303. /* presentationStartTime= */ null, /* delay= */ 0);
  304. }
  305. const isLive = TXml.parseAttr(mss, 'IsLive',
  306. TXml.parseBoolean, /* defaultValue= */ false);
  307. if (isLive) {
  308. throw new shaka.util.Error(
  309. shaka.util.Error.Severity.CRITICAL,
  310. shaka.util.Error.Category.MANIFEST,
  311. shaka.util.Error.Code.MSS_LIVE_CONTENT_NOT_SUPPORTED);
  312. }
  313. this.presentationTimeline_.setStatic(!isLive);
  314. const timescale = TXml.parseAttr(mss, 'TimeScale',
  315. TXml.parseNonNegativeInt, shaka.mss.MssParser.DEFAULT_TIME_SCALE_);
  316. goog.asserts.assert(timescale && timescale >= 0,
  317. 'Timescale must be defined!');
  318. let dvrWindowLength = TXml.parseAttr(mss, 'DVRWindowLength',
  319. TXml.parseNonNegativeInt);
  320. // If the DVRWindowLength field is omitted for a live presentation or set
  321. // to 0, the DVR window is effectively infinite
  322. if (isLive && (dvrWindowLength === 0 || isNaN(dvrWindowLength))) {
  323. dvrWindowLength = Infinity;
  324. }
  325. // Start-over
  326. const canSeek = TXml.parseAttr(mss, 'CanSeek',
  327. TXml.parseBoolean, /* defaultValue= */ false);
  328. if (dvrWindowLength === 0 && canSeek) {
  329. dvrWindowLength = Infinity;
  330. }
  331. let segmentAvailabilityDuration = null;
  332. if (dvrWindowLength && dvrWindowLength > 0) {
  333. segmentAvailabilityDuration = dvrWindowLength / timescale;
  334. }
  335. // If it's live, we check for an override.
  336. if (isLive && !isNaN(this.config_.availabilityWindowOverride)) {
  337. segmentAvailabilityDuration = this.config_.availabilityWindowOverride;
  338. }
  339. // If it's null, that means segments are always available. This is always
  340. // the case for VOD, and sometimes the case for live.
  341. if (segmentAvailabilityDuration == null) {
  342. segmentAvailabilityDuration = Infinity;
  343. }
  344. this.presentationTimeline_.setSegmentAvailabilityDuration(
  345. segmentAvailabilityDuration);
  346. // Duration in timescale units.
  347. const duration = TXml.parseAttr(mss, 'Duration',
  348. TXml.parseNonNegativeInt, Infinity);
  349. goog.asserts.assert(duration && duration >= 0,
  350. 'Duration must be defined!');
  351. if (!isLive) {
  352. this.presentationTimeline_.setDuration(duration / timescale);
  353. }
  354. /** @type {!shaka.mss.MssParser.Context} */
  355. const context = {
  356. variants: [],
  357. textStreams: [],
  358. timescale: timescale,
  359. duration: duration / timescale,
  360. };
  361. this.parseStreamIndexes_(mss, context);
  362. // These steps are not done on manifest update.
  363. if (!this.manifest_) {
  364. this.manifest_ = {
  365. presentationTimeline: this.presentationTimeline_,
  366. variants: context.variants,
  367. textStreams: context.textStreams,
  368. imageStreams: [],
  369. offlineSessionIds: [],
  370. minBufferTime: 0,
  371. sequenceMode: this.config_.mss.sequenceMode,
  372. ignoreManifestTimestampsInSegmentsMode: false,
  373. type: shaka.media.ManifestParser.MSS,
  374. serviceDescription: null,
  375. nextUrl: null,
  376. periodCount: 1,
  377. gapCount: 0,
  378. isLowLatency: false,
  379. startTime: null,
  380. };
  381. // This is the first point where we have a meaningful presentation start
  382. // time, and we need to tell PresentationTimeline that so that it can
  383. // maintain consistency from here on.
  384. this.presentationTimeline_.lockStartTime();
  385. } else {
  386. // Just update the variants and text streams.
  387. this.manifest_.variants = context.variants;
  388. this.manifest_.textStreams = context.textStreams;
  389. // Re-filter the manifest. This will check any configured restrictions on
  390. // new variants, and will pass any new init data to DrmEngine to ensure
  391. // that key rotation works correctly.
  392. this.playerInterface_.filter(this.manifest_);
  393. }
  394. }
  395. /**
  396. * @param {!shaka.extern.xml.Node} mss
  397. * @param {!shaka.mss.MssParser.Context} context
  398. * @private
  399. */
  400. parseStreamIndexes_(mss, context) {
  401. const ContentProtection = shaka.mss.ContentProtection;
  402. const TXml = shaka.util.TXml;
  403. const ContentType = shaka.util.ManifestParserUtils.ContentType;
  404. const protectionElems = TXml.findChildren(mss, 'Protection');
  405. const drmInfos = ContentProtection.parseFromProtection(
  406. protectionElems, this.config_.mss.keySystemsBySystemId);
  407. const audioStreams = [];
  408. const videoStreams = [];
  409. const textStreams = [];
  410. const streamIndexes = TXml.findChildren(mss, 'StreamIndex');
  411. for (const streamIndex of streamIndexes) {
  412. const qualityLevels = TXml.findChildren(streamIndex, 'QualityLevel');
  413. const timeline = this.createTimeline_(
  414. streamIndex, context.timescale, context.duration);
  415. // For each QualityLevel node, create a stream element
  416. for (const qualityLevel of qualityLevels) {
  417. const stream = this.createStream_(
  418. streamIndex, qualityLevel, timeline, drmInfos, context);
  419. if (!stream) {
  420. // Skip unsupported stream
  421. continue;
  422. }
  423. if (stream.type == ContentType.AUDIO &&
  424. !this.config_.disableAudio) {
  425. audioStreams.push(stream);
  426. } else if (stream.type == ContentType.VIDEO &&
  427. !this.config_.disableVideo) {
  428. videoStreams.push(stream);
  429. } else if (stream.type == ContentType.TEXT &&
  430. !this.config_.disableText) {
  431. textStreams.push(stream);
  432. }
  433. }
  434. }
  435. const variants = [];
  436. for (const audio of (audioStreams.length > 0 ? audioStreams : [null])) {
  437. for (const video of (videoStreams.length > 0 ? videoStreams : [null])) {
  438. variants.push(this.createVariant_(audio, video));
  439. }
  440. }
  441. context.variants = variants;
  442. context.textStreams = textStreams;
  443. }
  444. /**
  445. * @param {!shaka.extern.xml.Node} streamIndex
  446. * @param {!shaka.extern.xml.Node} qualityLevel
  447. * @param {!Array.<shaka.mss.MssParser.TimeRange>} timeline
  448. * @param {!Array.<shaka.extern.DrmInfo>} drmInfos
  449. * @param {!shaka.mss.MssParser.Context} context
  450. * @return {?shaka.extern.Stream}
  451. * @private
  452. */
  453. createStream_(streamIndex, qualityLevel, timeline, drmInfos, context) {
  454. const TXml = shaka.util.TXml;
  455. const ContentType = shaka.util.ManifestParserUtils.ContentType;
  456. const MssParser = shaka.mss.MssParser;
  457. const type = streamIndex.attributes['Type'];
  458. const isValidType = type === 'audio' || type === 'video' ||
  459. type === 'text';
  460. if (!isValidType) {
  461. shaka.log.alwaysWarn('Ignoring unrecognized type:', type);
  462. return null;
  463. }
  464. const lang = streamIndex.attributes['Language'];
  465. const id = this.globalId_++;
  466. const bandwidth = TXml.parseAttr(
  467. qualityLevel, 'Bitrate', TXml.parsePositiveInt);
  468. const width = TXml.parseAttr(
  469. qualityLevel, 'MaxWidth', TXml.parsePositiveInt);
  470. const height = TXml.parseAttr(
  471. qualityLevel, 'MaxHeight', TXml.parsePositiveInt);
  472. const channelsCount = TXml.parseAttr(
  473. qualityLevel, 'Channels', TXml.parsePositiveInt);
  474. const audioSamplingRate = TXml.parseAttr(
  475. qualityLevel, 'SamplingRate', TXml.parsePositiveInt);
  476. let duration = context.duration;
  477. if (timeline.length) {
  478. const start = timeline[0].start;
  479. const end = timeline[timeline.length - 1].end;
  480. duration = end - start;
  481. }
  482. const presentationDuration = this.presentationTimeline_.getDuration();
  483. this.presentationTimeline_.setDuration(
  484. Math.min(duration, presentationDuration));
  485. /** @type {!shaka.extern.Stream} */
  486. const stream = {
  487. id: id,
  488. originalId: streamIndex.attributes['Name'] || String(id),
  489. groupId: null,
  490. createSegmentIndex: () => Promise.resolve(),
  491. closeSegmentIndex: () => Promise.resolve(),
  492. segmentIndex: null,
  493. mimeType: '',
  494. codecs: '',
  495. frameRate: undefined,
  496. pixelAspectRatio: undefined,
  497. bandwidth: bandwidth || 0,
  498. width: width || undefined,
  499. height: height || undefined,
  500. kind: '',
  501. encrypted: drmInfos.length > 0,
  502. drmInfos: drmInfos,
  503. keyIds: new Set(),
  504. language: shaka.util.LanguageUtils.normalize(lang || 'und'),
  505. originalLanguage: lang,
  506. label: '',
  507. type: '',
  508. primary: false,
  509. trickModeVideo: null,
  510. emsgSchemeIdUris: [],
  511. roles: [],
  512. forced: false,
  513. channelsCount: channelsCount,
  514. audioSamplingRate: audioSamplingRate,
  515. spatialAudio: false,
  516. closedCaptions: null,
  517. hdr: undefined,
  518. colorGamut: undefined,
  519. videoLayout: undefined,
  520. tilesLayout: undefined,
  521. matchedStreams: [],
  522. mssPrivateData: {
  523. duration: duration,
  524. timescale: context.timescale,
  525. codecPrivateData: null,
  526. },
  527. accessibilityPurpose: null,
  528. external: false,
  529. fastSwitching: false,
  530. fullMimeTypes: new Set(),
  531. };
  532. // This is specifically for text tracks.
  533. const subType = streamIndex.attributes['Subtype'];
  534. if (subType) {
  535. const role = MssParser.ROLE_MAPPING_[subType];
  536. if (role) {
  537. stream.roles.push(role);
  538. }
  539. if (role === 'main') {
  540. stream.primary = true;
  541. }
  542. }
  543. let fourCCValue = qualityLevel.attributes['FourCC'];
  544. // If FourCC not defined at QualityLevel level,
  545. // then get it from StreamIndex level
  546. if (fourCCValue === null || fourCCValue === '') {
  547. fourCCValue = streamIndex.attributes['FourCC'];
  548. }
  549. // If still not defined (optional for audio stream,
  550. // see https://msdn.microsoft.com/en-us/library/ff728116%28v=vs.95%29.aspx),
  551. // then we consider the stream is an audio AAC stream
  552. if (!fourCCValue) {
  553. if (type === 'audio') {
  554. fourCCValue = 'AAC';
  555. } else if (type === 'video') {
  556. shaka.log.alwaysWarn('FourCC is not defined whereas it is required ' +
  557. 'for a QualityLevel element for a StreamIndex of type "video"');
  558. return null;
  559. }
  560. }
  561. // Check if codec is supported
  562. if (!MssParser.SUPPORTED_CODECS_.includes(fourCCValue.toUpperCase())) {
  563. shaka.log.alwaysWarn('Codec not supported:', fourCCValue);
  564. return null;
  565. }
  566. const codecPrivateData = this.getCodecPrivateData_(
  567. qualityLevel, type, fourCCValue, stream);
  568. stream.mssPrivateData.codecPrivateData = codecPrivateData;
  569. switch (type) {
  570. case 'audio':
  571. if (!codecPrivateData) {
  572. shaka.log.alwaysWarn('Quality unsupported without CodecPrivateData',
  573. type);
  574. return null;
  575. }
  576. stream.type = ContentType.AUDIO;
  577. // This mimetype is fake to allow the transmuxing.
  578. stream.mimeType = 'mss/audio/mp4';
  579. stream.codecs = this.getAACCodec_(
  580. qualityLevel, fourCCValue, codecPrivateData);
  581. break;
  582. case 'video':
  583. if (!codecPrivateData) {
  584. shaka.log.alwaysWarn('Quality unsupported without CodecPrivateData',
  585. type);
  586. return null;
  587. }
  588. stream.type = ContentType.VIDEO;
  589. // This mimetype is fake to allow the transmuxing.
  590. stream.mimeType = 'mss/video/mp4';
  591. stream.codecs = this.getH264Codec_(
  592. qualityLevel, codecPrivateData);
  593. break;
  594. case 'text':
  595. stream.type = ContentType.TEXT;
  596. stream.mimeType = 'application/mp4';
  597. if (fourCCValue === 'TTML' || fourCCValue === 'DFXP') {
  598. stream.codecs = 'stpp';
  599. }
  600. break;
  601. }
  602. stream.fullMimeTypes.add(shaka.util.MimeUtils.getFullType(
  603. stream.mimeType, stream.codecs));
  604. // Lazy-Load the segment index to avoid create all init segment at the
  605. // same time
  606. stream.createSegmentIndex = () => {
  607. if (stream.segmentIndex) {
  608. return Promise.resolve();
  609. }
  610. let initSegmentData;
  611. if (this.initSegmentDataByStreamId_.has(stream.id)) {
  612. initSegmentData = this.initSegmentDataByStreamId_.get(stream.id);
  613. } else {
  614. let videoNalus = [];
  615. if (stream.type == ContentType.VIDEO) {
  616. const codecPrivateData = stream.mssPrivateData.codecPrivateData;
  617. videoNalus = codecPrivateData.split('00000001').slice(1);
  618. }
  619. /** @type {shaka.util.Mp4Generator.StreamInfo} */
  620. const streamInfo = {
  621. id: stream.id,
  622. type: stream.type,
  623. codecs: stream.codecs,
  624. encrypted: stream.encrypted,
  625. timescale: stream.mssPrivateData.timescale,
  626. duration: stream.mssPrivateData.duration,
  627. videoNalus: videoNalus,
  628. audioConfig: new Uint8Array([]),
  629. videoConfig: new Uint8Array([]),
  630. hSpacing: 0,
  631. vSpacing: 0,
  632. data: null, // Data is not necessary for init segement.
  633. stream: stream,
  634. };
  635. const mp4Generator = new shaka.util.Mp4Generator([streamInfo]);
  636. initSegmentData = mp4Generator.initSegment();
  637. this.initSegmentDataByStreamId_.set(stream.id, initSegmentData);
  638. }
  639. const qualityInfo =
  640. shaka.media.QualityObserver.createQualityInfo(stream);
  641. const initSegmentRef = new shaka.media.InitSegmentReference(
  642. () => [],
  643. /* startByte= */ 0,
  644. /* endByte= */ null,
  645. qualityInfo,
  646. stream.mssPrivateData.timescale,
  647. initSegmentData);
  648. const segments = this.createSegments_(initSegmentRef,
  649. stream, streamIndex, timeline);
  650. stream.segmentIndex = new shaka.media.SegmentIndex(segments);
  651. return Promise.resolve();
  652. };
  653. stream.closeSegmentIndex = () => {
  654. // If we have a segment index, release it.
  655. if (stream.segmentIndex) {
  656. stream.segmentIndex.release();
  657. stream.segmentIndex = null;
  658. }
  659. };
  660. return stream;
  661. }
  662. /**
  663. * @param {!shaka.extern.xml.Node} qualityLevel
  664. * @param {string} type
  665. * @param {string} fourCCValue
  666. * @param {!shaka.extern.Stream} stream
  667. * @return {?string}
  668. * @private
  669. */
  670. getCodecPrivateData_(qualityLevel, type, fourCCValue, stream) {
  671. const codecPrivateData = qualityLevel.attributes['CodecPrivateData'];
  672. if (codecPrivateData) {
  673. return codecPrivateData;
  674. }
  675. if (type !== 'audio') {
  676. return null;
  677. }
  678. // For the audio we can reconstruct the CodecPrivateData
  679. // By default stereo
  680. const channels = stream.channelsCount || 2;
  681. // By default 44,1kHz.
  682. const samplingRate = stream.audioSamplingRate || 44100;
  683. const samplingFrequencyIndex = {
  684. 96000: 0x0,
  685. 88200: 0x1,
  686. 64000: 0x2,
  687. 48000: 0x3,
  688. 44100: 0x4,
  689. 32000: 0x5,
  690. 24000: 0x6,
  691. 22050: 0x7,
  692. 16000: 0x8,
  693. 12000: 0x9,
  694. 11025: 0xA,
  695. 8000: 0xB,
  696. 7350: 0xC,
  697. };
  698. const indexFreq = samplingFrequencyIndex[samplingRate];
  699. if (fourCCValue === 'AACH') {
  700. // High Efficiency AAC Profile
  701. const objectType = 0x05;
  702. // 4 bytes :
  703. // XXXXX XXXX XXXX XXXX
  704. // 'ObjectType' 'Freq Index' 'Channels value' 'Extens Sampl Freq'
  705. // XXXXX XXX XXXXXXX
  706. // 'ObjectType' 'GAS' 'alignment = 0'
  707. const data = new Uint8Array(4);
  708. // In HE AAC Extension Sampling frequence
  709. // equals to SamplingRate * 2
  710. const extensionSamplingFrequencyIndex =
  711. samplingFrequencyIndex[samplingRate * 2];
  712. // Freq Index is present for 3 bits in the first byte, last bit is in
  713. // the second
  714. data[0] = (objectType << 3) | (indexFreq >> 1);
  715. data[1] = (indexFreq << 7) | (channels << 3) |
  716. (extensionSamplingFrequencyIndex >> 1);
  717. // Origin object type equals to 2 => AAC Main Low Complexity
  718. data[2] = (extensionSamplingFrequencyIndex << 7) | (0x02 << 2);
  719. // Slignment bits
  720. data[3] = 0x0;
  721. // Put the 4 bytes in an 16 bits array
  722. const arr16 = new Uint16Array(2);
  723. arr16[0] = (data[0] << 8) + data[1];
  724. arr16[1] = (data[2] << 8) + data[3];
  725. // Convert decimal to hex value
  726. return arr16[0].toString(16) + arr16[1].toString(16);
  727. } else {
  728. // AAC Main Low Complexity
  729. const objectType = 0x02;
  730. // 2 bytes:
  731. // XXXXX XXXX XXXX XXX
  732. // 'ObjectType' 'Freq Index' 'Channels value' 'GAS = 000'
  733. const data = new Uint8Array(2);
  734. // Freq Index is present for 3 bits in the first byte, last bit is in
  735. // the second
  736. data[0] = (objectType << 3) | (indexFreq >> 1);
  737. data[1] = (indexFreq << 7) | (channels << 3);
  738. // Put the 2 bytes in an 16 bits array
  739. const arr16 = new Uint16Array(1);
  740. arr16[0] = (data[0] << 8) + data[1];
  741. // Convert decimal to hex value
  742. return arr16[0].toString(16);
  743. }
  744. }
  745. /**
  746. * @param {!shaka.extern.xml.Node} qualityLevel
  747. * @param {string} fourCCValue
  748. * @param {?string} codecPrivateData
  749. * @return {string}
  750. * @private
  751. */
  752. getAACCodec_(qualityLevel, fourCCValue, codecPrivateData) {
  753. let objectType = 0;
  754. // Chrome problem, in implicit AAC HE definition, so when AACH is detected
  755. // in FourCC set objectType to 5 => strange, it should be 2
  756. if (fourCCValue === 'AACH') {
  757. objectType = 0x05;
  758. }
  759. if (!codecPrivateData) {
  760. // AAC Main Low Complexity => object Type = 2
  761. objectType = 0x02;
  762. if (fourCCValue === 'AACH') {
  763. // High Efficiency AAC Profile = object Type = 5 SBR
  764. objectType = 0x05;
  765. }
  766. } else if (objectType === 0) {
  767. objectType = (parseInt(codecPrivateData.substr(0, 2), 16) & 0xF8) >> 3;
  768. }
  769. return 'mp4a.40.' + objectType;
  770. }
  771. /**
  772. * @param {!shaka.extern.xml.Node} qualityLevel
  773. * @param {?string} codecPrivateData
  774. * @return {string}
  775. * @private
  776. */
  777. getH264Codec_(qualityLevel, codecPrivateData) {
  778. // Extract from the CodecPrivateData field the hexadecimal representation
  779. // of the following three bytes in the sequence parameter set NAL unit.
  780. // => Find the SPS nal header
  781. const nalHeader = /00000001[0-9]7/.exec(codecPrivateData);
  782. if (!nalHeader.length) {
  783. return '';
  784. }
  785. if (!codecPrivateData) {
  786. return '';
  787. }
  788. // => Find the 6 characters after the SPS nalHeader (if it exists)
  789. const avcoti = codecPrivateData.substr(
  790. codecPrivateData.indexOf(nalHeader[0]) + 10, 6);
  791. return 'avc1.' + avcoti;
  792. }
  793. /**
  794. * @param {!shaka.media.InitSegmentReference} initSegmentRef
  795. * @param {!shaka.extern.Stream} stream
  796. * @param {!shaka.extern.xml.Node} streamIndex
  797. * @param {!Array.<shaka.mss.MssParser.TimeRange>} timeline
  798. * @return {!Array.<!shaka.media.SegmentReference>}
  799. * @private
  800. */
  801. createSegments_(initSegmentRef, stream, streamIndex, timeline) {
  802. const ManifestParserUtils = shaka.util.ManifestParserUtils;
  803. const url = streamIndex.attributes['Url'];
  804. goog.asserts.assert(url, 'Missing URL for segments');
  805. const mediaUrl = url.replace('{bitrate}', String(stream.bandwidth));
  806. const segments = [];
  807. for (const time of timeline) {
  808. const getUris = () => {
  809. return ManifestParserUtils.resolveUris(this.manifestUris_,
  810. [mediaUrl.replace('{start time}', String(time.unscaledStart))]);
  811. };
  812. segments.push(new shaka.media.SegmentReference(
  813. time.start,
  814. time.end,
  815. getUris,
  816. /* startByte= */ 0,
  817. /* endByte= */ null,
  818. initSegmentRef,
  819. /* timestampOffset= */ 0,
  820. /* appendWindowStart= */ 0,
  821. /* appendWindowEnd= */ stream.mssPrivateData.duration));
  822. }
  823. return segments;
  824. }
  825. /**
  826. * Expands a streamIndex into an array-based timeline. The results are in
  827. * seconds.
  828. *
  829. * @param {!shaka.extern.xml.Node} streamIndex
  830. * @param {number} timescale
  831. * @param {number} duration The duration in seconds.
  832. * @return {!Array.<shaka.mss.MssParser.TimeRange>}
  833. * @private
  834. */
  835. createTimeline_(streamIndex, timescale, duration) {
  836. goog.asserts.assert(
  837. timescale > 0 && timescale < Infinity,
  838. 'timescale must be a positive, finite integer');
  839. goog.asserts.assert(
  840. duration > 0, 'duration must be a positive integer');
  841. const TXml = shaka.util.TXml;
  842. const timePoints = TXml.findChildren(streamIndex, 'c');
  843. /** @type {!Array.<shaka.mss.MssParser.TimeRange>} */
  844. const timeline = [];
  845. let lastEndTime = 0;
  846. for (let i = 0; i < timePoints.length; ++i) {
  847. const timePoint = timePoints[i];
  848. const next = timePoints[i + 1];
  849. const t =
  850. TXml.parseAttr(timePoint, 't', TXml.parseNonNegativeInt);
  851. const d =
  852. TXml.parseAttr(timePoint, 'd', TXml.parseNonNegativeInt);
  853. const r = TXml.parseAttr(timePoint, 'r', TXml.parseInt);
  854. if (!d) {
  855. shaka.log.warning(
  856. '"c" element must have a duration:',
  857. 'ignoring the remaining "c" elements.', timePoint);
  858. return timeline;
  859. }
  860. let startTime = t != null ? t : lastEndTime;
  861. let repeat = r || 0;
  862. if (repeat < 0) {
  863. if (next) {
  864. const nextStartTime =
  865. TXml.parseAttr(next, 't', TXml.parseNonNegativeInt);
  866. if (nextStartTime == null) {
  867. shaka.log.warning(
  868. 'An "c" element cannot have a negative repeat',
  869. 'if the next "c" element does not have a valid start time:',
  870. 'ignoring the remaining "c" elements.', timePoint);
  871. return timeline;
  872. } else if (startTime >= nextStartTime) {
  873. shaka.log.warning(
  874. 'An "c" element cannot have a negative repeatif its start ',
  875. 'time exceeds the next "c" element\'s start time:',
  876. 'ignoring the remaining "c" elements.', timePoint);
  877. return timeline;
  878. }
  879. repeat = Math.ceil((nextStartTime - startTime) / d) - 1;
  880. } else {
  881. if (duration == Infinity) {
  882. // The MSS spec. actually allows the last "c" element to have a
  883. // negative repeat value even when it has an infinite
  884. // duration. No one uses this feature and no one ever should,
  885. // ever.
  886. shaka.log.warning(
  887. 'The last "c" element cannot have a negative repeat',
  888. 'if the Period has an infinite duration:',
  889. 'ignoring the last "c" element.', timePoint);
  890. return timeline;
  891. } else if (startTime / timescale >= duration) {
  892. shaka.log.warning(
  893. 'The last "c" element cannot have a negative repeat',
  894. 'if its start time exceeds the duration:',
  895. 'igoring the last "c" element.', timePoint);
  896. return timeline;
  897. }
  898. repeat = Math.ceil((duration * timescale - startTime) / d) - 1;
  899. }
  900. }
  901. for (let j = 0; j <= repeat; ++j) {
  902. const endTime = startTime + d;
  903. const item = {
  904. start: startTime / timescale,
  905. end: endTime / timescale,
  906. unscaledStart: startTime,
  907. };
  908. timeline.push(item);
  909. startTime = endTime;
  910. lastEndTime = endTime;
  911. }
  912. }
  913. return timeline;
  914. }
  915. /**
  916. * @param {?shaka.extern.Stream} audioStream
  917. * @param {?shaka.extern.Stream} videoStream
  918. * @return {!shaka.extern.Variant}
  919. * @private
  920. */
  921. createVariant_(audioStream, videoStream) {
  922. const ContentType = shaka.util.ManifestParserUtils.ContentType;
  923. goog.asserts.assert(!audioStream ||
  924. audioStream.type == ContentType.AUDIO, 'Audio parameter mismatch!');
  925. goog.asserts.assert(!videoStream ||
  926. videoStream.type == ContentType.VIDEO, 'Video parameter mismatch!');
  927. let bandwidth = 0;
  928. if (audioStream && audioStream.bandwidth && audioStream.bandwidth > 0) {
  929. bandwidth += audioStream.bandwidth;
  930. }
  931. if (videoStream && videoStream.bandwidth && videoStream.bandwidth > 0) {
  932. bandwidth += videoStream.bandwidth;
  933. }
  934. return {
  935. id: this.globalId_++,
  936. language: audioStream ? audioStream.language : 'und',
  937. disabledUntilTime: 0,
  938. primary: (!!audioStream && audioStream.primary) ||
  939. (!!videoStream && videoStream.primary),
  940. audio: audioStream,
  941. video: videoStream,
  942. bandwidth: bandwidth,
  943. allowedByApplication: true,
  944. allowedByKeySystem: true,
  945. decodingInfos: [],
  946. };
  947. }
  948. };
  949. /**
  950. * Contains the minimum amount of time, in seconds, between manifest update
  951. * requests.
  952. *
  953. * @private
  954. * @const {number}
  955. */
  956. shaka.mss.MssParser.MIN_UPDATE_PERIOD_ = 3;
  957. /**
  958. * @private
  959. * @const {number}
  960. */
  961. shaka.mss.MssParser.DEFAULT_TIME_SCALE_ = 1e7;
  962. /**
  963. * MSS supported codecs.
  964. *
  965. * @private
  966. * @const {!Array.<string>}
  967. */
  968. shaka.mss.MssParser.SUPPORTED_CODECS_ = [
  969. 'AAC',
  970. 'AACL',
  971. 'AACH',
  972. 'AACP',
  973. 'AVC1',
  974. 'H264',
  975. 'TTML',
  976. 'DFXP',
  977. ];
  978. /**
  979. * MPEG-DASH Role and accessibility mapping for text tracks according to
  980. * ETSI TS 103 285 v1.1.1 (section 7.1.2)
  981. *
  982. * @const {!Object.<string, string>}
  983. * @private
  984. */
  985. shaka.mss.MssParser.ROLE_MAPPING_ = {
  986. 'CAPT': 'main',
  987. 'SUBT': 'alternate',
  988. 'DESC': 'main',
  989. };
  990. /**
  991. * @typedef {{
  992. * variants: !Array.<shaka.extern.Variant>,
  993. * textStreams: !Array.<shaka.extern.Stream>,
  994. * timescale: number,
  995. * duration: number
  996. * }}
  997. *
  998. * @property {!Array.<shaka.extern.Variant>} variants
  999. * The presentation's Variants.
  1000. * @property {!Array.<shaka.extern.Stream>} textStreams
  1001. * The presentation's text streams.
  1002. * @property {number} timescale
  1003. * The presentation's timescale.
  1004. * @property {number} duration
  1005. * The presentation's duration.
  1006. */
  1007. shaka.mss.MssParser.Context;
  1008. /**
  1009. * @typedef {{
  1010. * start: number,
  1011. * unscaledStart: number,
  1012. * end: number
  1013. * }}
  1014. *
  1015. * @description
  1016. * Defines a time range of a media segment. Times are in seconds.
  1017. *
  1018. * @property {number} start
  1019. * The start time of the range.
  1020. * @property {number} unscaledStart
  1021. * The start time of the range in representation timescale units.
  1022. * @property {number} end
  1023. * The end time (exclusive) of the range.
  1024. */
  1025. shaka.mss.MssParser.TimeRange;
  1026. shaka.media.ManifestParser.registerParserByMime(
  1027. 'application/vnd.ms-sstr+xml', () => new shaka.mss.MssParser());