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