Source: lib/dash/segment_template.js

  1. /*! @license
  2. * Shaka Player
  3. * Copyright 2016 Google LLC
  4. * SPDX-License-Identifier: Apache-2.0
  5. */
  6. goog.provide('shaka.dash.SegmentTemplate');
  7. goog.require('goog.asserts');
  8. goog.require('shaka.dash.MpdUtils');
  9. goog.require('shaka.dash.SegmentBase');
  10. goog.require('shaka.log');
  11. goog.require('shaka.media.InitSegmentReference');
  12. goog.require('shaka.media.SegmentIndex');
  13. goog.require('shaka.media.SegmentReference');
  14. goog.require('shaka.util.Error');
  15. goog.require('shaka.util.IReleasable');
  16. goog.require('shaka.util.ManifestParserUtils');
  17. goog.require('shaka.util.ObjectUtils');
  18. goog.require('shaka.util.StringUtils');
  19. goog.require('shaka.util.TXml');
  20. goog.requireType('shaka.dash.DashParser');
  21. goog.requireType('shaka.media.PresentationTimeline');
  22. /**
  23. * @summary A set of functions for parsing SegmentTemplate elements.
  24. */
  25. shaka.dash.SegmentTemplate = class {
  26. /**
  27. * Creates a new StreamInfo object.
  28. * Updates the existing SegmentIndex, if any.
  29. *
  30. * @param {shaka.dash.DashParser.Context} context
  31. * @param {shaka.dash.DashParser.RequestSegmentCallback} requestSegment
  32. * @param {!Map<string, !shaka.extern.Stream>} streamMap
  33. * @param {boolean} isUpdate True if the manifest is being updated.
  34. * @param {number} segmentLimit The maximum number of segments to generate for
  35. * a SegmentTemplate with fixed duration.
  36. * @param {!Map<string, number>} periodDurationMap
  37. * @param {shaka.extern.aesKey|undefined} aesKey
  38. * @param {?number} lastSegmentNumber
  39. * @param {boolean} isPatchUpdate
  40. * @param {
  41. * !Map<string, {endTime: number, timeline: number, reps: Array<string>}>
  42. * } continuityCache
  43. * @return {shaka.dash.DashParser.StreamInfo}
  44. */
  45. static createStreamInfo(
  46. context, requestSegment, streamMap, isUpdate, segmentLimit,
  47. periodDurationMap, aesKey, lastSegmentNumber, isPatchUpdate,
  48. continuityCache) {
  49. goog.asserts.assert(context.representation.segmentTemplate,
  50. 'Should only be called with SegmentTemplate ' +
  51. 'or segment info defined');
  52. const MpdUtils = shaka.dash.MpdUtils;
  53. const SegmentTemplate = shaka.dash.SegmentTemplate;
  54. const TimelineSegmentIndex = shaka.dash.TimelineSegmentIndex;
  55. if (!isPatchUpdate && !context.representation.initialization) {
  56. context.representation.initialization =
  57. MpdUtils.inheritAttribute(
  58. context, SegmentTemplate.fromInheritance_, 'initialization');
  59. }
  60. const initSegmentReference = context.representation.initialization ?
  61. SegmentTemplate.createInitSegment_(context, aesKey) : null;
  62. /** @type {shaka.dash.SegmentTemplate.SegmentTemplateInfo} */
  63. const info = SegmentTemplate.parseSegmentTemplateInfo_(context);
  64. SegmentTemplate.checkSegmentTemplateInfo_(context, info);
  65. // Direct fields of context will be reassigned by the parser before
  66. // generateSegmentIndex is called. So we must make a shallow copy first,
  67. // and use that in the generateSegmentIndex callbacks.
  68. const shallowCopyOfContext =
  69. shaka.util.ObjectUtils.shallowCloneObject(context);
  70. if (info.indexTemplate) {
  71. shaka.dash.SegmentBase.checkSegmentIndexSupport(
  72. context, initSegmentReference);
  73. return {
  74. endTime: -1,
  75. timeline: -1,
  76. generateSegmentIndex: () => {
  77. return SegmentTemplate.generateSegmentIndexFromIndexTemplate_(
  78. shallowCopyOfContext, requestSegment, initSegmentReference,
  79. info);
  80. },
  81. timescale: info.timescale,
  82. };
  83. } else if (info.segmentDuration) {
  84. if (!isUpdate &&
  85. context.adaptationSet.contentType !== 'image' &&
  86. context.adaptationSet.contentType !== 'text') {
  87. const periodStart = context.periodInfo.start;
  88. const periodId = context.period.id;
  89. const initialPeriodDuration = context.periodInfo.duration;
  90. const periodDuration =
  91. (periodId != null && periodDurationMap.get(periodId)) ||
  92. initialPeriodDuration;
  93. const periodEnd = periodDuration ?
  94. (periodStart + periodDuration) : Infinity;
  95. context.presentationTimeline.notifyMaxSegmentDuration(
  96. info.segmentDuration);
  97. context.presentationTimeline.notifyPeriodDuration(
  98. periodStart, periodEnd);
  99. }
  100. return {
  101. endTime: -1,
  102. timeline: -1,
  103. generateSegmentIndex: () => {
  104. return SegmentTemplate.generateSegmentIndexFromDuration_(
  105. shallowCopyOfContext, info, segmentLimit, initSegmentReference,
  106. periodDurationMap, aesKey, lastSegmentNumber,
  107. context.representation.segmentSequenceCadence);
  108. },
  109. timescale: info.timescale,
  110. };
  111. } else {
  112. /** @type {shaka.media.SegmentIndex} */
  113. let segmentIndex = null;
  114. let id = null;
  115. let stream = null;
  116. if (context.period.id && context.representation.id) {
  117. // Only check/store the index if period and representation IDs are set.
  118. id = context.period.id + ',' + context.representation.id;
  119. stream = streamMap.get(id);
  120. if (stream) {
  121. segmentIndex = stream.segmentIndex;
  122. }
  123. }
  124. const periodStart = context.periodInfo.start;
  125. const periodEnd = context.periodInfo.duration ? periodStart +
  126. context.periodInfo.duration : Infinity;
  127. shaka.log.debug(`New manifest ${periodStart} - ${periodEnd}`);
  128. if (!segmentIndex) {
  129. let newTimeline = 0;
  130. let timelineToUse = -1;
  131. if (context.period.id != null && context.representation.id != null) {
  132. const cache = continuityCache.get(context.period.id);
  133. if (cache) {
  134. // if we're on the current period still, use that timeline
  135. timelineToUse = cache.timeline;
  136. } else {
  137. // if we're on a new period, calculate timeline to use
  138. for (const value of continuityCache.values()) {
  139. const threshold =
  140. shaka.util.ManifestParserUtils.GAP_OVERLAP_TOLERANCE_SECONDS;
  141. if (Math.abs(info.scaledPresentationTimeOffset - value.endTime) <=
  142. threshold && value.reps.includes(context.representation.id)) {
  143. timelineToUse = value.timeline;
  144. break;
  145. } else if (value.timeline >= newTimeline) {
  146. newTimeline = value.timeline + 1;
  147. }
  148. }
  149. }
  150. }
  151. if (timelineToUse == -1) {
  152. timelineToUse = newTimeline;
  153. }
  154. shaka.log.debug(`Creating TSI with end ${periodEnd}`);
  155. segmentIndex = new TimelineSegmentIndex(
  156. info,
  157. context.representation.originalId,
  158. context.bandwidth,
  159. context.representation.getBaseUris,
  160. context.urlParams,
  161. periodStart,
  162. periodEnd,
  163. initSegmentReference,
  164. aesKey,
  165. context.representation.segmentSequenceCadence,
  166. timelineToUse,
  167. );
  168. } else {
  169. const tsi = /** @type {!TimelineSegmentIndex} */(segmentIndex);
  170. tsi.appendTemplateInfo(
  171. info, periodStart, periodEnd, initSegmentReference);
  172. const availabilityStart =
  173. context.presentationTimeline.getSegmentAvailabilityStart();
  174. tsi.evict(availabilityStart);
  175. }
  176. if (info.timeline &&
  177. context.adaptationSet.contentType !== 'image' &&
  178. context.adaptationSet.contentType !== 'text') {
  179. const tsi = /** @type {!TimelineSegmentIndex} */(segmentIndex);
  180. // getTimeline is the info.timeline but fitted to the period.
  181. const timeline = tsi.getTimeline();
  182. context.presentationTimeline.notifyTimeRange(
  183. timeline,
  184. periodStart);
  185. }
  186. if (stream && context.dynamic) {
  187. stream.segmentIndex = segmentIndex;
  188. }
  189. const timeline = info.timeline;
  190. const lastItem = timeline && timeline[timeline.length-1];
  191. const endTime = lastItem ?
  192. lastItem.end + info.scaledPresentationTimeOffset :
  193. -1;
  194. let continuityTimeline = -1;
  195. if (segmentIndex instanceof shaka.dash.TimelineSegmentIndex) {
  196. continuityTimeline = segmentIndex.continuityTimeline();
  197. }
  198. return {
  199. endTime,
  200. timeline: continuityTimeline,
  201. generateSegmentIndex: () => {
  202. // If segmentIndex is deleted, or segmentIndex's references are
  203. // released by closeSegmentIndex(), we should set the value of
  204. // segmentIndex again.
  205. if (segmentIndex instanceof shaka.dash.TimelineSegmentIndex &&
  206. segmentIndex.isEmpty()) {
  207. segmentIndex.appendTemplateInfo(info, periodStart,
  208. periodEnd, initSegmentReference);
  209. }
  210. return Promise.resolve(segmentIndex);
  211. },
  212. timescale: info.timescale,
  213. };
  214. }
  215. }
  216. /**
  217. * Ingests Patch MPD segments into timeline.
  218. *
  219. * @param {!shaka.dash.DashParser.Context} context
  220. * @param {shaka.extern.xml.Node} patchNode
  221. */
  222. static modifyTimepoints(context, patchNode) {
  223. const MpdUtils = shaka.dash.MpdUtils;
  224. const SegmentTemplate = shaka.dash.SegmentTemplate;
  225. const TXml = shaka.util.TXml;
  226. const timelineNode = MpdUtils.inheritChild(context,
  227. SegmentTemplate.fromInheritance_, 'SegmentTimeline');
  228. goog.asserts.assert(timelineNode, 'timeline node not found');
  229. const timepoints = TXml.findChildren(timelineNode, 'S');
  230. goog.asserts.assert(timepoints, 'timepoints should exist');
  231. TXml.modifyNodes(timepoints, patchNode);
  232. timelineNode.children = timepoints;
  233. }
  234. /**
  235. * Removes all segments from timeline.
  236. *
  237. * @param {!shaka.dash.DashParser.Context} context
  238. */
  239. static removeTimepoints(context) {
  240. const MpdUtils = shaka.dash.MpdUtils;
  241. const SegmentTemplate = shaka.dash.SegmentTemplate;
  242. const timelineNode = MpdUtils.inheritChild(context,
  243. SegmentTemplate.fromInheritance_, 'SegmentTimeline');
  244. goog.asserts.assert(timelineNode, 'timeline node not found');
  245. timelineNode.children = [];
  246. }
  247. /**
  248. * @param {?shaka.dash.DashParser.InheritanceFrame} frame
  249. * @return {?shaka.extern.xml.Node}
  250. * @private
  251. */
  252. static fromInheritance_(frame) {
  253. return frame.segmentTemplate;
  254. }
  255. /**
  256. * Parses a SegmentTemplate element into an info object.
  257. *
  258. * @param {shaka.dash.DashParser.Context} context
  259. * @return {shaka.dash.SegmentTemplate.SegmentTemplateInfo}
  260. * @private
  261. */
  262. static parseSegmentTemplateInfo_(context) {
  263. const SegmentTemplate = shaka.dash.SegmentTemplate;
  264. const MpdUtils = shaka.dash.MpdUtils;
  265. const StringUtils = shaka.util.StringUtils;
  266. const segmentInfo =
  267. MpdUtils.parseSegmentInfo(context, SegmentTemplate.fromInheritance_);
  268. const media = MpdUtils.inheritAttribute(
  269. context, SegmentTemplate.fromInheritance_, 'media');
  270. const index = MpdUtils.inheritAttribute(
  271. context, SegmentTemplate.fromInheritance_, 'index');
  272. const k = MpdUtils.inheritAttribute(
  273. context, SegmentTemplate.fromInheritance_, 'k');
  274. let numChunks = 0;
  275. if (k) {
  276. numChunks = parseInt(k, 10);
  277. }
  278. return {
  279. unscaledSegmentDuration: segmentInfo.unscaledSegmentDuration,
  280. segmentDuration: segmentInfo.segmentDuration,
  281. timescale: segmentInfo.timescale,
  282. startNumber: segmentInfo.startNumber,
  283. scaledPresentationTimeOffset: segmentInfo.scaledPresentationTimeOffset,
  284. unscaledPresentationTimeOffset:
  285. segmentInfo.unscaledPresentationTimeOffset,
  286. timeline: segmentInfo.timeline,
  287. mediaTemplate: media && StringUtils.htmlUnescape(media),
  288. indexTemplate: index,
  289. mimeType: context.representation.mimeType,
  290. codecs: context.representation.codecs,
  291. bandwidth: context.bandwidth,
  292. numChunks: numChunks,
  293. };
  294. }
  295. /**
  296. * Verifies a SegmentTemplate info object.
  297. *
  298. * @param {shaka.dash.DashParser.Context} context
  299. * @param {shaka.dash.SegmentTemplate.SegmentTemplateInfo} info
  300. * @private
  301. */
  302. static checkSegmentTemplateInfo_(context, info) {
  303. let n = 0;
  304. n += info.indexTemplate ? 1 : 0;
  305. n += info.timeline ? 1 : 0;
  306. n += info.segmentDuration ? 1 : 0;
  307. if (n == 0) {
  308. shaka.log.error(
  309. 'SegmentTemplate does not contain any segment information:',
  310. 'the SegmentTemplate must contain either an index URL template',
  311. 'a SegmentTimeline, or a segment duration.',
  312. context.representation);
  313. throw new shaka.util.Error(
  314. shaka.util.Error.Severity.CRITICAL,
  315. shaka.util.Error.Category.MANIFEST,
  316. shaka.util.Error.Code.DASH_NO_SEGMENT_INFO);
  317. } else if (n != 1) {
  318. shaka.log.warning(
  319. 'SegmentTemplate contains multiple segment information sources:',
  320. 'the SegmentTemplate should only contain an index URL template,',
  321. 'a SegmentTimeline or a segment duration.',
  322. context.representation);
  323. if (info.indexTemplate) {
  324. shaka.log.info('Using the index URL template by default.');
  325. info.timeline = null;
  326. info.unscaledSegmentDuration = null;
  327. info.segmentDuration = null;
  328. } else {
  329. goog.asserts.assert(info.timeline, 'There should be a timeline');
  330. shaka.log.info('Using the SegmentTimeline by default.');
  331. info.unscaledSegmentDuration = null;
  332. info.segmentDuration = null;
  333. }
  334. }
  335. if (!info.indexTemplate && !info.mediaTemplate) {
  336. shaka.log.error(
  337. 'SegmentTemplate does not contain sufficient segment information:',
  338. 'the SegmentTemplate\'s media URL template is missing.',
  339. context.representation);
  340. throw new shaka.util.Error(
  341. shaka.util.Error.Severity.CRITICAL,
  342. shaka.util.Error.Category.MANIFEST,
  343. shaka.util.Error.Code.DASH_NO_SEGMENT_INFO);
  344. }
  345. }
  346. /**
  347. * Generates a SegmentIndex from an index URL template.
  348. *
  349. * @param {shaka.dash.DashParser.Context} context
  350. * @param {shaka.dash.DashParser.RequestSegmentCallback} requestSegment
  351. * @param {shaka.media.InitSegmentReference} init
  352. * @param {shaka.dash.SegmentTemplate.SegmentTemplateInfo} info
  353. * @return {!Promise<shaka.media.SegmentIndex>}
  354. * @private
  355. */
  356. static generateSegmentIndexFromIndexTemplate_(
  357. context, requestSegment, init, info) {
  358. const MpdUtils = shaka.dash.MpdUtils;
  359. const ManifestParserUtils = shaka.util.ManifestParserUtils;
  360. goog.asserts.assert(info.indexTemplate, 'must be using index template');
  361. const filledTemplate = MpdUtils.fillUriTemplate(
  362. info.indexTemplate, context.representation.originalId,
  363. null, null, context.bandwidth || null, null);
  364. const resolvedUris = ManifestParserUtils.resolveUris(
  365. context.representation.getBaseUris(), [filledTemplate]);
  366. return shaka.dash.SegmentBase.generateSegmentIndexFromUris(
  367. context, requestSegment, init, resolvedUris, 0, null,
  368. info.scaledPresentationTimeOffset);
  369. }
  370. /**
  371. * Generates a SegmentIndex from fixed-duration segments.
  372. *
  373. * @param {shaka.dash.DashParser.Context} context
  374. * @param {shaka.dash.SegmentTemplate.SegmentTemplateInfo} info
  375. * @param {number} segmentLimit The maximum number of segments to generate.
  376. * @param {shaka.media.InitSegmentReference} initSegmentReference
  377. * @param {!Map<string, number>} periodDurationMap
  378. * @param {shaka.extern.aesKey|undefined} aesKey
  379. * @param {?number} lastSegmentNumber
  380. * @param {number} segmentSequenceCadence
  381. * @return {!Promise<shaka.media.SegmentIndex>}
  382. * @private
  383. */
  384. static generateSegmentIndexFromDuration_(
  385. context, info, segmentLimit, initSegmentReference, periodDurationMap,
  386. aesKey, lastSegmentNumber, segmentSequenceCadence) {
  387. goog.asserts.assert(info.mediaTemplate,
  388. 'There should be a media template with duration');
  389. const MpdUtils = shaka.dash.MpdUtils;
  390. const ManifestParserUtils = shaka.util.ManifestParserUtils;
  391. const presentationTimeline = context.presentationTimeline;
  392. // Capture values that could change as the parsing context moves on to
  393. // other parts of the manifest.
  394. const periodStart = context.periodInfo.start;
  395. const periodId = context.period.id;
  396. const initialPeriodDuration = context.periodInfo.duration;
  397. // For multi-period live streams the period duration may not be known until
  398. // the following period appears in an updated manifest. periodDurationMap
  399. // provides the updated period duration.
  400. const getPeriodEnd = () => {
  401. const periodDuration =
  402. (periodId != null && periodDurationMap.get(periodId)) ||
  403. initialPeriodDuration;
  404. const periodEnd = periodDuration ?
  405. (periodStart + periodDuration) : Infinity;
  406. return periodEnd;
  407. };
  408. const segmentDuration = info.segmentDuration;
  409. goog.asserts.assert(
  410. segmentDuration != null, 'Segment duration must not be null!');
  411. const startNumber = info.startNumber;
  412. const template = info.mediaTemplate;
  413. const bandwidth = context.bandwidth || null;
  414. const id = context.representation.id;
  415. const getBaseUris = context.representation.getBaseUris;
  416. const urlParams = context.urlParams;
  417. const timestampOffset = periodStart - info.scaledPresentationTimeOffset;
  418. // Computes the range of presentation timestamps both within the period and
  419. // available. This is an intersection of the period range and the
  420. // availability window.
  421. const computeAvailablePeriodRange = () => {
  422. return [
  423. Math.max(
  424. presentationTimeline.getSegmentAvailabilityStart(),
  425. periodStart),
  426. Math.min(
  427. presentationTimeline.getSegmentAvailabilityEnd(),
  428. getPeriodEnd()),
  429. ];
  430. };
  431. // Computes the range of absolute positions both within the period and
  432. // available. The range is inclusive. These are the positions for which we
  433. // will generate segment references.
  434. const computeAvailablePositionRange = () => {
  435. // In presentation timestamps.
  436. const availablePresentationTimes = computeAvailablePeriodRange();
  437. goog.asserts.assert(availablePresentationTimes.every(isFinite),
  438. 'Available presentation times must be finite!');
  439. goog.asserts.assert(availablePresentationTimes.every((x) => x >= 0),
  440. 'Available presentation times must be positive!');
  441. goog.asserts.assert(segmentDuration != null,
  442. 'Segment duration must not be null!');
  443. // In period-relative timestamps.
  444. const availablePeriodTimes =
  445. availablePresentationTimes.map((x) => x - periodStart);
  446. // These may sometimes be reversed ([1] <= [0]) if the period is
  447. // completely unavailable. The logic will still work if this happens,
  448. // because we will simply generate no references.
  449. // In period-relative positions (0-based).
  450. const availablePeriodPositions = [
  451. Math.ceil(availablePeriodTimes[0] / segmentDuration),
  452. Math.ceil(availablePeriodTimes[1] / segmentDuration) - 1,
  453. ];
  454. // For Low Latency we can request the partial current position.
  455. if (context.representation.availabilityTimeOffset) {
  456. availablePeriodPositions[1]++;
  457. }
  458. // In absolute positions.
  459. const availablePresentationPositions =
  460. availablePeriodPositions.map((x) => x + startNumber);
  461. return availablePresentationPositions;
  462. };
  463. // For Live, we must limit the initial SegmentIndex in size, to avoid
  464. // consuming too much CPU or memory for content with gigantic
  465. // timeShiftBufferDepth (which can have values up to and including
  466. // Infinity).
  467. const range = computeAvailablePositionRange();
  468. const minPosition = context.dynamic ?
  469. Math.max(range[0], range[1] - segmentLimit + 1) :
  470. range[0];
  471. const maxPosition = lastSegmentNumber || range[1];
  472. const references = [];
  473. const createReference = (position) => {
  474. // These inner variables are all scoped to the inner loop, and can be used
  475. // safely in the callback below.
  476. goog.asserts.assert(segmentDuration != null,
  477. 'Segment duration must not be null!');
  478. // Relative to the period start.
  479. const positionWithinPeriod = position - startNumber;
  480. const segmentPeriodTime = positionWithinPeriod * segmentDuration;
  481. const unscaledSegmentDuration = info.unscaledSegmentDuration;
  482. goog.asserts.assert(unscaledSegmentDuration != null,
  483. 'Segment duration must not be null!');
  484. // The original media timestamp from the timeline is what is expected in
  485. // the $Time$ template. (Or based on duration, in this case.) It should
  486. // not be adjusted with presentationTimeOffset or the Period start.
  487. let timeReplacement = positionWithinPeriod * unscaledSegmentDuration;
  488. if ('BigInt' in window && timeReplacement > Number.MAX_SAFE_INTEGER) {
  489. timeReplacement =
  490. BigInt(positionWithinPeriod) * BigInt(unscaledSegmentDuration);
  491. }
  492. // Relative to the presentation.
  493. const segmentStart = segmentPeriodTime + periodStart;
  494. const trueSegmentEnd = segmentStart + segmentDuration;
  495. // Cap the segment end at the period end so that references from the
  496. // next period will fit neatly after it.
  497. const segmentEnd = Math.min(trueSegmentEnd, getPeriodEnd());
  498. // This condition will be true unless the segmentStart was >= periodEnd.
  499. // If we've done the position calculations correctly, this won't happen.
  500. goog.asserts.assert(segmentStart < segmentEnd,
  501. 'Generated a segment outside of the period!');
  502. const partialSegmentRefs = [];
  503. const numChunks = info.numChunks;
  504. if (numChunks) {
  505. const partialDuration = (segmentEnd - segmentStart) / numChunks;
  506. for (let i = 0; i < numChunks; i++) {
  507. const start = segmentStart + partialDuration * i;
  508. const end = start + partialDuration;
  509. const subNumber = i + 1;
  510. const getPartialUris = () => {
  511. const mediaUri = MpdUtils.fillUriTemplate(
  512. template, id, position, subNumber, bandwidth, timeReplacement);
  513. return ManifestParserUtils.resolveUris(
  514. getBaseUris(), [mediaUri], urlParams());
  515. };
  516. const partial = new shaka.media.SegmentReference(
  517. start,
  518. end,
  519. getPartialUris,
  520. /* startByte= */ 0,
  521. /* endByte= */ null,
  522. initSegmentReference,
  523. timestampOffset,
  524. /* appendWindowStart= */ periodStart,
  525. /* appendWindowEnd= */ getPeriodEnd(),
  526. /* partialReferences= */ [],
  527. /* tilesLayout= */ '',
  528. /* tileDuration= */ null,
  529. /* syncTime= */ null,
  530. shaka.media.SegmentReference.Status.AVAILABLE,
  531. aesKey);
  532. partial.codecs = context.representation.codecs;
  533. partial.mimeType = context.representation.mimeType;
  534. if (segmentSequenceCadence == 0) {
  535. if (i > 0) {
  536. partial.markAsNonIndependent();
  537. }
  538. } else if ((i % segmentSequenceCadence) != 0) {
  539. partial.markAsNonIndependent();
  540. }
  541. partialSegmentRefs.push(partial);
  542. }
  543. }
  544. const getUris = () => {
  545. if (numChunks) {
  546. return [];
  547. }
  548. const mediaUri = MpdUtils.fillUriTemplate(
  549. template, id, position, /* subNumber= */ null, bandwidth,
  550. timeReplacement);
  551. return ManifestParserUtils.resolveUris(
  552. getBaseUris(), [mediaUri], urlParams());
  553. };
  554. const ref = new shaka.media.SegmentReference(
  555. segmentStart,
  556. segmentEnd,
  557. getUris,
  558. /* startByte= */ 0,
  559. /* endByte= */ null,
  560. initSegmentReference,
  561. timestampOffset,
  562. /* appendWindowStart= */ periodStart,
  563. /* appendWindowEnd= */ getPeriodEnd(),
  564. partialSegmentRefs,
  565. /* tilesLayout= */ '',
  566. /* tileDuration= */ null,
  567. /* syncTime= */ null,
  568. shaka.media.SegmentReference.Status.AVAILABLE,
  569. aesKey,
  570. partialSegmentRefs.length > 0);
  571. ref.codecs = context.representation.codecs;
  572. ref.mimeType = context.representation.mimeType;
  573. ref.bandwidth = context.bandwidth;
  574. // This is necessary information for thumbnail streams:
  575. ref.trueEndTime = trueSegmentEnd;
  576. return ref;
  577. };
  578. for (let position = minPosition; position <= maxPosition; ++position) {
  579. const reference = createReference(position);
  580. references.push(reference);
  581. }
  582. /** @type {shaka.media.SegmentIndex} */
  583. const segmentIndex = new shaka.media.SegmentIndex(references);
  584. // If the availability timeline currently ends before the period, we will
  585. // need to add references over time.
  586. const willNeedToAddReferences =
  587. presentationTimeline.getSegmentAvailabilityEnd() < getPeriodEnd();
  588. // When we start a live stream with a period that ends within the
  589. // availability window we will not need to add more references, but we will
  590. // need to evict old references.
  591. const willNeedToEvictReferences = presentationTimeline.isLive();
  592. if (willNeedToAddReferences || willNeedToEvictReferences) {
  593. // The period continues to get longer over time, so check for new
  594. // references once every |segmentDuration| seconds.
  595. // We clamp to |minPosition| in case the initial range was reversed and no
  596. // references were generated. Otherwise, the update would start creating
  597. // negative positions for segments in periods which begin in the future.
  598. let nextPosition = Math.max(minPosition, maxPosition + 1);
  599. let updateTime = segmentDuration;
  600. // For low latency we need to evict very frequently.
  601. if (context.representation.availabilityTimeOffset) {
  602. updateTime = 0.1;
  603. }
  604. segmentIndex.updateEvery(updateTime, () => {
  605. // Evict any references outside the window.
  606. const availabilityStartTime =
  607. presentationTimeline.getSegmentAvailabilityStart();
  608. segmentIndex.evict(availabilityStartTime);
  609. // Compute any new references that need to be added.
  610. const [_, maxPosition] = computeAvailablePositionRange();
  611. const references = [];
  612. while (nextPosition <= maxPosition) {
  613. const reference = createReference(nextPosition);
  614. references.push(reference);
  615. nextPosition++;
  616. }
  617. // The timer must continue firing until the entire period is
  618. // unavailable, so that all references will be evicted.
  619. if (availabilityStartTime > getPeriodEnd() && !references.length) {
  620. // Signal stop.
  621. return null;
  622. }
  623. return references;
  624. });
  625. }
  626. return Promise.resolve(segmentIndex);
  627. }
  628. /**
  629. * Creates an init segment reference from a context object.
  630. *
  631. * @param {shaka.dash.DashParser.Context} context
  632. * @param {shaka.extern.aesKey|undefined} aesKey
  633. * @return {shaka.media.InitSegmentReference}
  634. * @private
  635. */
  636. static createInitSegment_(context, aesKey) {
  637. const MpdUtils = shaka.dash.MpdUtils;
  638. const ManifestParserUtils = shaka.util.ManifestParserUtils;
  639. const SegmentTemplate = shaka.dash.SegmentTemplate;
  640. let initialization = context.representation.initialization;
  641. if (!initialization) {
  642. initialization = MpdUtils.inheritAttribute(
  643. context, SegmentTemplate.fromInheritance_, 'initialization');
  644. }
  645. if (!initialization) {
  646. return null;
  647. }
  648. initialization = shaka.util.StringUtils.htmlUnescape(initialization);
  649. const repId = context.representation.originalId;
  650. const bandwidth = context.bandwidth || null;
  651. const getBaseUris = context.representation.getBaseUris;
  652. const urlParams = context.urlParams;
  653. const getUris = () => {
  654. goog.asserts.assert(initialization, 'Should have returned earlier');
  655. const filledTemplate = MpdUtils.fillUriTemplate(
  656. initialization, repId, null, null, bandwidth, null);
  657. const resolvedUris = ManifestParserUtils.resolveUris(
  658. getBaseUris(), [filledTemplate], urlParams());
  659. return resolvedUris;
  660. };
  661. const qualityInfo = shaka.dash.SegmentBase.createQualityInfo(context);
  662. const encrypted = context.adaptationSet.encrypted;
  663. const ref = new shaka.media.InitSegmentReference(
  664. getUris,
  665. /* startByte= */ 0,
  666. /* endByte= */ null,
  667. qualityInfo,
  668. /* timescale= */ null,
  669. /* segmentData= */ null,
  670. aesKey,
  671. encrypted);
  672. ref.codecs = context.representation.codecs;
  673. ref.mimeType = context.representation.mimeType;
  674. if (context.periodInfo) {
  675. ref.boundaryEnd = context.periodInfo.start + context.periodInfo.duration;
  676. }
  677. return ref;
  678. }
  679. };
  680. /**
  681. * A SegmentIndex that returns segments references on demand from
  682. * a segment timeline.
  683. *
  684. * @extends shaka.media.SegmentIndex
  685. * @implements {shaka.util.IReleasable}
  686. * @implements {Iterable<!shaka.media.SegmentReference>}
  687. *
  688. * @private
  689. *
  690. */
  691. shaka.dash.TimelineSegmentIndex = class extends shaka.media.SegmentIndex {
  692. /**
  693. *
  694. * @param {!shaka.dash.SegmentTemplate.SegmentTemplateInfo} templateInfo
  695. * @param {?string} representationId
  696. * @param {number} bandwidth
  697. * @param {function(): Array<string>} getBaseUris
  698. * @param {function():string} urlParams
  699. * @param {number} periodStart
  700. * @param {number} periodEnd
  701. * @param {shaka.media.InitSegmentReference} initSegmentReference
  702. * @param {shaka.extern.aesKey|undefined} aesKey
  703. * @param {number} segmentSequenceCadence
  704. * @param {number} timeline
  705. */
  706. constructor(templateInfo, representationId, bandwidth, getBaseUris,
  707. urlParams, periodStart, periodEnd, initSegmentReference,
  708. aesKey, segmentSequenceCadence, timeline) {
  709. super([]);
  710. /** @private {?shaka.dash.SegmentTemplate.SegmentTemplateInfo} */
  711. this.templateInfo_ = templateInfo;
  712. /** @private {?string} */
  713. this.representationId_ = representationId;
  714. /** @private {number} */
  715. this.bandwidth_ = bandwidth;
  716. /** @private {function(): Array<string>} */
  717. this.getBaseUris_ = getBaseUris;
  718. /** @private {function():string} */
  719. this.urlParams_ = urlParams;
  720. /** @private {number} */
  721. this.periodStart_ = periodStart;
  722. /** @private {number} */
  723. this.periodEnd_ = periodEnd;
  724. /** @private {shaka.media.InitSegmentReference} */
  725. this.initSegmentReference_ = initSegmentReference;
  726. /** @private {shaka.extern.aesKey|undefined} */
  727. this.aesKey_ = aesKey;
  728. /** @private {number} */
  729. this.segmentSequenceCadence_ = segmentSequenceCadence;
  730. /** @private {number} */
  731. this.timeline_ = timeline;
  732. this.fitTimeline();
  733. }
  734. /**
  735. * @override
  736. */
  737. getNumReferences() {
  738. if (this.templateInfo_) {
  739. return this.templateInfo_.timeline.length;
  740. } else {
  741. return 0;
  742. }
  743. }
  744. /**
  745. * @override
  746. */
  747. release() {
  748. super.release();
  749. this.templateInfo_ = null;
  750. // We cannot release other fields, as segment index can
  751. // be recreated using only template info.
  752. }
  753. /**
  754. * @override
  755. */
  756. evict(time) {
  757. if (!this.templateInfo_) {
  758. return;
  759. }
  760. shaka.log.debug(`${this.representationId_} Evicting at ${time}`);
  761. let numToEvict = 0;
  762. const timeline = this.templateInfo_.timeline;
  763. for (let i = 0; i < timeline.length; i += 1) {
  764. const range = timeline[i];
  765. const end = range.end + this.periodStart_;
  766. const start = range.start + this.periodStart_;
  767. if (end <= time) {
  768. shaka.log.debug(`Evicting ${start} - ${end}`);
  769. numToEvict += 1;
  770. } else {
  771. break;
  772. }
  773. }
  774. if (numToEvict > 0) {
  775. this.templateInfo_.timeline = timeline.slice(numToEvict);
  776. if (this.references.length >= numToEvict) {
  777. this.references = this.references.slice(numToEvict);
  778. }
  779. this.numEvicted_ += numToEvict;
  780. if (this.getNumReferences() === 0) {
  781. this.release();
  782. }
  783. }
  784. }
  785. /**
  786. * Merge new template info
  787. * @param {shaka.dash.SegmentTemplate.SegmentTemplateInfo} info
  788. * @param {number} periodStart
  789. * @param {number} periodEnd
  790. * @param {shaka.media.InitSegmentReference} initSegmentReference
  791. */
  792. appendTemplateInfo(info, periodStart, periodEnd, initSegmentReference) {
  793. this.updateInitSegmentReference(initSegmentReference);
  794. if (!this.templateInfo_) {
  795. this.templateInfo_ = info;
  796. this.periodStart_ = periodStart;
  797. this.periodEnd_ = periodEnd;
  798. } else {
  799. const currentTimeline = this.templateInfo_.timeline;
  800. if (this.templateInfo_.mediaTemplate !== info.mediaTemplate) {
  801. this.templateInfo_.mediaTemplate = info.mediaTemplate;
  802. }
  803. // Append timeline
  804. let newEntries;
  805. if (currentTimeline.length) {
  806. const lastCurrentEntry = currentTimeline[currentTimeline.length - 1];
  807. newEntries = info.timeline.filter((entry) => {
  808. return entry.end > lastCurrentEntry.end;
  809. });
  810. } else {
  811. newEntries = info.timeline.slice();
  812. }
  813. if (newEntries.length > 0) {
  814. shaka.log.debug(`Appending ${newEntries.length} entries`);
  815. this.templateInfo_.timeline.push(...newEntries);
  816. }
  817. if (this.periodEnd_ !== periodEnd) {
  818. this.periodEnd_ = periodEnd;
  819. }
  820. }
  821. this.fitTimeline();
  822. }
  823. /**
  824. * Updates the init segment reference and propagates the update to all
  825. * references.
  826. * @param {shaka.media.InitSegmentReference} initSegmentReference
  827. */
  828. updateInitSegmentReference(initSegmentReference) {
  829. if (this.initSegmentReference_ === initSegmentReference) {
  830. return;
  831. }
  832. this.initSegmentReference_ = initSegmentReference;
  833. for (const reference of this.references) {
  834. if (reference) {
  835. reference.updateInitSegmentReference(initSegmentReference);
  836. }
  837. }
  838. }
  839. /**
  840. *
  841. * @param {number} time
  842. */
  843. isBeforeFirstEntry(time) {
  844. const hasTimeline = this.templateInfo_ &&
  845. this.templateInfo_.timeline && this.templateInfo_.timeline.length;
  846. if (hasTimeline) {
  847. const timeline = this.templateInfo_.timeline;
  848. return time < timeline[0].start + this.periodStart_;
  849. } else {
  850. return false;
  851. }
  852. }
  853. /**
  854. * Fit timeline entries to period boundaries
  855. */
  856. fitTimeline() {
  857. if (!this.templateInfo_ || this.getIsImmutable()) {
  858. return;
  859. }
  860. const timeline = this.templateInfo_.timeline;
  861. goog.asserts.assert(timeline, 'Timeline should be non-null!');
  862. const newTimeline = [];
  863. for (const range of timeline) {
  864. if (range.start >= this.periodEnd_) {
  865. // Starts after end of period.
  866. } else if (range.end <= 0) {
  867. // Ends before start of period.
  868. } else {
  869. // Usable.
  870. newTimeline.push(range);
  871. }
  872. }
  873. this.templateInfo_.timeline = newTimeline;
  874. this.evict(this.periodStart_);
  875. // Do NOT adjust last range to match period end! With high precision
  876. // timestamps several recalculations may give wrong results on less precise
  877. // platforms. To mitigate that, we're using cached |periodEnd_| value in
  878. // find/get() methods whenever possible.
  879. }
  880. /**
  881. * Get the current timeline
  882. * @return {!Array<shaka.media.PresentationTimeline.TimeRange>}
  883. */
  884. getTimeline() {
  885. if (!this.templateInfo_) {
  886. return [];
  887. }
  888. const timeline = this.templateInfo_.timeline;
  889. goog.asserts.assert(timeline, 'Timeline should be non-null!');
  890. return timeline;
  891. }
  892. /**
  893. * @override
  894. */
  895. find(time) {
  896. shaka.log.debug(`Find ${time}`);
  897. if (this.isBeforeFirstEntry(time)) {
  898. return this.numEvicted_;
  899. }
  900. if (!this.templateInfo_) {
  901. return null;
  902. }
  903. const timeline = this.templateInfo_.timeline;
  904. // Early exit if the time isn't within this period
  905. if (time < this.periodStart_ || time >= this.periodEnd_) {
  906. return null;
  907. }
  908. const lastIndex = timeline.length - 1;
  909. for (let i = 0; i < timeline.length; i++) {
  910. const range = timeline[i];
  911. const start = range.start + this.periodStart_;
  912. // A rounding error can cause /time/ to equal e.endTime or fall in between
  913. // the references by a fraction of a second. To account for this, we use
  914. // the start of the next segment as /end/, unless this is the last
  915. // reference, in which case we use the period end as the /end/
  916. let end;
  917. if (i < lastIndex) {
  918. end = timeline[i + 1].start + this.periodStart_;
  919. } else if (this.periodEnd_ === Infinity) {
  920. end = range.end + this.periodStart_;
  921. } else {
  922. end = this.periodEnd_;
  923. }
  924. if ((time >= start) && (time < end)) {
  925. return i + this.numEvicted_;
  926. }
  927. }
  928. return null;
  929. }
  930. /**
  931. * @override
  932. */
  933. get(position) {
  934. const correctedPosition = position - this.numEvicted_;
  935. if (correctedPosition < 0 ||
  936. correctedPosition >= this.getNumReferences() || !this.templateInfo_) {
  937. return null;
  938. }
  939. let ref = this.references[correctedPosition];
  940. if (!ref) {
  941. const range = this.templateInfo_.timeline[correctedPosition];
  942. const segmentReplacement = range.segmentPosition;
  943. // The original media timestamp from the timeline is what is expected in
  944. // the $Time$ template. It should not be adjusted with
  945. // presentationTimeOffset or the Period start, but
  946. // unscaledPresentationTimeOffset was already subtracted from the times
  947. // in timeline.
  948. const timeReplacement = range.unscaledStart +
  949. this.templateInfo_.unscaledPresentationTimeOffset;
  950. const timestampOffset = this.periodStart_ -
  951. this.templateInfo_.scaledPresentationTimeOffset;
  952. const trueSegmentEnd = this.periodStart_ + range.end;
  953. let segmentEnd = trueSegmentEnd;
  954. if (correctedPosition === this.getNumReferences() - 1 &&
  955. this.periodEnd_ !== Infinity) {
  956. // See https://github.com/shaka-project/shaka-player/issues/8672
  957. if (Math.abs(segmentEnd - this.periodEnd_) > 0.1) {
  958. segmentEnd = Math.min(segmentEnd, this.periodEnd_);
  959. } else {
  960. segmentEnd = this.periodEnd_;
  961. }
  962. }
  963. const codecs = this.templateInfo_.codecs;
  964. const mimeType = this.templateInfo_.mimeType;
  965. const bandwidth = this.templateInfo_.bandwidth;
  966. const partialSegmentRefs = [];
  967. const partialDuration = (range.end - range.start) / range.partialSegments;
  968. for (let i = 0; i < range.partialSegments; i++) {
  969. const start = range.start + partialDuration * i;
  970. const end = start + partialDuration;
  971. const subNumber = i + 1;
  972. let uris = null;
  973. const getPartialUris = () => {
  974. if (!this.templateInfo_) {
  975. return [];
  976. }
  977. if (uris == null) {
  978. uris = shaka.dash.TimelineSegmentIndex.createUris_(
  979. this.templateInfo_.mediaTemplate,
  980. this.representationId_,
  981. segmentReplacement,
  982. this.bandwidth_,
  983. timeReplacement,
  984. subNumber,
  985. this.getBaseUris_,
  986. this.urlParams_);
  987. }
  988. return uris;
  989. };
  990. const partial = new shaka.media.SegmentReference(
  991. this.periodStart_ + start,
  992. this.periodStart_ + end,
  993. getPartialUris,
  994. /* startByte= */ 0,
  995. /* endByte= */ null,
  996. this.initSegmentReference_,
  997. timestampOffset,
  998. this.periodStart_,
  999. this.periodEnd_,
  1000. /* partialReferences= */ [],
  1001. /* tilesLayout= */ '',
  1002. /* tileDuration= */ null,
  1003. /* syncTime= */ null,
  1004. shaka.media.SegmentReference.Status.AVAILABLE,
  1005. this.aesKey_);
  1006. partial.codecs = codecs;
  1007. partial.mimeType = mimeType;
  1008. partial.bandwidth = bandwidth;
  1009. if (this.segmentSequenceCadence_ == 0) {
  1010. if (i > 0) {
  1011. partial.markAsNonIndependent();
  1012. }
  1013. } else if ((i % this.segmentSequenceCadence_) != 0) {
  1014. partial.markAsNonIndependent();
  1015. }
  1016. partialSegmentRefs.push(partial);
  1017. }
  1018. const createUrisCb = () => {
  1019. if (range.partialSegments > 0 || !this.templateInfo_) {
  1020. return [];
  1021. }
  1022. return shaka.dash.TimelineSegmentIndex
  1023. .createUris_(
  1024. this.templateInfo_.mediaTemplate,
  1025. this.representationId_,
  1026. segmentReplacement,
  1027. this.bandwidth_,
  1028. timeReplacement,
  1029. /* subNumber= */ null,
  1030. this.getBaseUris_,
  1031. this.urlParams_,
  1032. );
  1033. };
  1034. ref = new shaka.media.SegmentReference(
  1035. this.periodStart_ + range.start,
  1036. segmentEnd,
  1037. createUrisCb,
  1038. /* startByte= */ 0,
  1039. /* endByte= */ null,
  1040. this.initSegmentReference_,
  1041. timestampOffset,
  1042. this.periodStart_,
  1043. this.periodEnd_,
  1044. partialSegmentRefs,
  1045. /* tilesLayout= */ '',
  1046. /* tileDuration= */ null,
  1047. /* syncTime= */ null,
  1048. shaka.media.SegmentReference.Status.AVAILABLE,
  1049. this.aesKey_,
  1050. /* allPartialSegments= */ range.partialSegments > 0);
  1051. ref.codecs = codecs;
  1052. ref.mimeType = mimeType;
  1053. ref.trueEndTime = trueSegmentEnd;
  1054. ref.bandwidth = bandwidth;
  1055. this.references[correctedPosition] = ref;
  1056. }
  1057. return ref;
  1058. }
  1059. /**
  1060. * @override
  1061. */
  1062. forEachTopLevelReference(fn) {
  1063. this.fitTimeline();
  1064. for (let i = 0; i < this.getNumReferences(); i++) {
  1065. const reference = this.get(i + this.numEvicted_);
  1066. if (reference) {
  1067. fn(reference);
  1068. }
  1069. }
  1070. }
  1071. /**
  1072. * Fill in a specific template with values to get the segment uris
  1073. *
  1074. * @return {!Array<string>}
  1075. * @private
  1076. */
  1077. static createUris_(mediaTemplate, repId, segmentReplacement,
  1078. bandwidth, timeReplacement, subNumber, getBaseUris, urlParams) {
  1079. const mediaUri = shaka.dash.MpdUtils.fillUriTemplate(
  1080. mediaTemplate, repId,
  1081. segmentReplacement, subNumber, bandwidth || null, timeReplacement);
  1082. return shaka.util.ManifestParserUtils
  1083. .resolveUris(getBaseUris(), [mediaUri], urlParams())
  1084. .map((g) => {
  1085. return g.toString();
  1086. });
  1087. }
  1088. /**
  1089. * Return the continuity timeline associated with the current
  1090. * TimelineSegmentIndex.
  1091. * In the context of a multiperiod dash stream, the continuous periods as
  1092. * outlined in the IOP will return the same timeline value.
  1093. *
  1094. * @override
  1095. */
  1096. continuityTimeline() {
  1097. return this.timeline_;
  1098. }
  1099. };
  1100. /**
  1101. * @typedef {{
  1102. * timescale: number,
  1103. * unscaledSegmentDuration: ?number,
  1104. * segmentDuration: ?number,
  1105. * startNumber: number,
  1106. * scaledPresentationTimeOffset: number,
  1107. * unscaledPresentationTimeOffset: number,
  1108. * timeline: Array<shaka.media.PresentationTimeline.TimeRange>,
  1109. * mediaTemplate: ?string,
  1110. * indexTemplate: ?string,
  1111. * mimeType: string,
  1112. * codecs: string,
  1113. * bandwidth: number,
  1114. * numChunks: number
  1115. * }}
  1116. *
  1117. * @description
  1118. * Contains information about a SegmentTemplate.
  1119. *
  1120. * @property {number} timescale
  1121. * The time-scale of the representation.
  1122. * @property {?number} unscaledSegmentDuration
  1123. * The duration of the segments in seconds, in timescale units.
  1124. * @property {?number} segmentDuration
  1125. * The duration of the segments in seconds, if given.
  1126. * @property {number} startNumber
  1127. * The start number of the segments; 1 or greater.
  1128. * @property {number} scaledPresentationTimeOffset
  1129. * The presentation time offset of the representation, in seconds.
  1130. * @property {number} unscaledPresentationTimeOffset
  1131. * The presentation time offset of the representation, in timescale units.
  1132. * @property {Array<shaka.media.PresentationTimeline.TimeRange>} timeline
  1133. * The timeline of the representation, if given. Times in seconds.
  1134. * @property {?string} mediaTemplate
  1135. * The media URI template, if given.
  1136. * @property {?string} indexTemplate
  1137. * The index URI template, if given.
  1138. * @property {string} mimeType
  1139. * The mimeType.
  1140. * @property {string} codecs
  1141. * The codecs.
  1142. * @property {number} bandwidth
  1143. * The bandwidth.
  1144. * @property {number} numChunks
  1145. * The number of chunks in each segment.
  1146. */
  1147. shaka.dash.SegmentTemplate.SegmentTemplateInfo;