Source: lib/util/player_configuration.js

  1. /*! @license
  2. * Shaka Player
  3. * Copyright 2016 Google LLC
  4. * SPDX-License-Identifier: Apache-2.0
  5. */
  6. goog.provide('shaka.util.PlayerConfiguration');
  7. goog.require('goog.asserts');
  8. goog.require('shaka.abr.SimpleAbrManager');
  9. goog.require('shaka.config.AutoShowText');
  10. goog.require('shaka.config.CodecSwitchingStrategy');
  11. goog.require('shaka.config.CrossBoundaryStrategy');
  12. goog.require('shaka.drm.DrmUtils');
  13. goog.require('shaka.drm.FairPlay');
  14. goog.require('shaka.log');
  15. goog.require('shaka.media.Capabilities');
  16. goog.require('shaka.media.PreferenceBasedCriteria');
  17. goog.require('shaka.net.NetworkingEngine');
  18. goog.require('shaka.util.ConfigUtils');
  19. goog.require('shaka.util.LanguageUtils');
  20. goog.require('shaka.util.ManifestParserUtils');
  21. goog.require('shaka.util.Platform');
  22. /**
  23. * @final
  24. * @export
  25. */
  26. shaka.util.PlayerConfiguration = class {
  27. /**
  28. * @return {shaka.extern.PlayerConfiguration}
  29. * @export
  30. */
  31. static createDefault() {
  32. // This is a relatively safe default in the absence of clues from the
  33. // browser. For slower connections, the default estimate may be too high.
  34. const bandwidthEstimate = 1e6; // 1Mbps
  35. const minBytes = 16e3;
  36. let abrMaxHeight = Infinity;
  37. // Some browsers implement the Network Information API, which allows
  38. // retrieving information about a user's network connection.
  39. if (navigator.connection) {
  40. // If the user has checked a box in the browser to ask it to use less
  41. // data, the browser will expose this intent via connection.saveData.
  42. // When that is true, we will default the max ABR height to 360p. Apps
  43. // can override this if they wish.
  44. //
  45. // The decision to use 360p was somewhat arbitrary. We needed a default
  46. // limit, and rather than restrict to a certain bandwidth, we decided to
  47. // restrict resolution. This will implicitly restrict bandwidth and
  48. // therefore save data. We (Shaka+Chrome) judged that:
  49. // - HD would be inappropriate
  50. // - If a user is asking their browser to save data, 360p it reasonable
  51. // - 360p would not look terrible on small mobile device screen
  52. // We also found that:
  53. // - YouTube's website on mobile defaults to 360p (as of 2018)
  54. // - iPhone 6, in portrait mode, has a physical resolution big enough
  55. // for 360p widescreen, but a little smaller than 480p widescreen
  56. // (https://apple.co/2yze4es)
  57. // If the content's lowest resolution is above 360p, AbrManager will use
  58. // the lowest resolution.
  59. if (navigator.connection.saveData) {
  60. abrMaxHeight = 360;
  61. }
  62. }
  63. const drm = {
  64. retryParameters: shaka.net.NetworkingEngine.defaultRetryParameters(),
  65. // These will all be verified by special cases in mergeConfigObjects_():
  66. servers: {}, // key is arbitrary key system ID, value must be string
  67. clearKeys: {}, // key is arbitrary key system ID, value must be string
  68. advanced: {}, // key is arbitrary key system ID, value is a record type
  69. delayLicenseRequestUntilPlayed: false,
  70. persistentSessionOnlinePlayback: false,
  71. persistentSessionsMetadata: [],
  72. initDataTransform: (initData, initDataType, drmInfo) => {
  73. if (shaka.drm.DrmUtils.isMediaKeysPolyfilled('apple') &&
  74. initDataType == 'skd') {
  75. const cert = drmInfo.serverCertificate;
  76. const contentId =
  77. shaka.drm.FairPlay.defaultGetContentId(initData);
  78. initData = shaka.drm.FairPlay.initDataTransform(
  79. initData, contentId, cert);
  80. }
  81. return initData;
  82. },
  83. logLicenseExchange: false,
  84. updateExpirationTime: 1,
  85. preferredKeySystems: [],
  86. keySystemsMapping: {},
  87. // The Xbox One browser does not detect DRM key changes signalled by a
  88. // change in the PSSH in media segments. We need to parse PSSH from media
  89. // segments to detect key changes.
  90. parseInbandPsshEnabled: shaka.util.Platform.isXboxOne(),
  91. minHdcpVersion: '',
  92. ignoreDuplicateInitData: !shaka.util.Platform.isTizen2(),
  93. defaultAudioRobustnessForWidevine: 'SW_SECURE_CRYPTO',
  94. defaultVideoRobustnessForWidevine: 'SW_SECURE_DECODE',
  95. };
  96. // The Xbox One and PS4 only support the Playready DRM, so they should
  97. // prefer that key system by default to improve startup performance.
  98. if (shaka.util.Platform.isXboxOne() ||
  99. shaka.util.Platform.isPS4()) {
  100. drm.preferredKeySystems.push('com.microsoft.playready');
  101. }
  102. let codecSwitchingStrategy = shaka.config.CodecSwitchingStrategy.RELOAD;
  103. let multiTypeVariantsAllowed = false;
  104. if (shaka.media.Capabilities.isChangeTypeSupported() &&
  105. shaka.util.Platform.supportsSmoothCodecSwitching()) {
  106. codecSwitchingStrategy = shaka.config.CodecSwitchingStrategy.SMOOTH;
  107. multiTypeVariantsAllowed = true;
  108. }
  109. const manifest = {
  110. retryParameters: shaka.net.NetworkingEngine.defaultRetryParameters(),
  111. availabilityWindowOverride: NaN,
  112. disableAudio: false,
  113. disableVideo: false,
  114. disableText: false,
  115. disableThumbnails: false,
  116. disableIFrames: false,
  117. defaultPresentationDelay: 0,
  118. segmentRelativeVttTiming: false,
  119. raiseFatalErrorOnManifestUpdateRequestFailure: false,
  120. continueLoadingWhenPaused: true,
  121. ignoreSupplementalCodecs: false,
  122. updatePeriod: -1,
  123. ignoreDrmInfo: false,
  124. dash: {
  125. clockSyncUri: '',
  126. disableXlinkProcessing: true,
  127. xlinkFailGracefully: false,
  128. ignoreMinBufferTime: false,
  129. autoCorrectDrift: true,
  130. initialSegmentLimit: 1000,
  131. ignoreSuggestedPresentationDelay: false,
  132. ignoreEmptyAdaptationSet: false,
  133. ignoreMaxSegmentDuration: false,
  134. keySystemsByURI: {
  135. 'urn:uuid:1077efec-c0b2-4d02-ace3-3c1e52e2fb4b':
  136. 'org.w3.clearkey',
  137. 'urn:uuid:e2719d58-a985-b3c9-781a-b030af78d30e':
  138. 'org.w3.clearkey',
  139. 'urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed':
  140. 'com.widevine.alpha',
  141. 'urn:uuid:9a04f079-9840-4286-ab92-e65be0885f95':
  142. 'com.microsoft.playready',
  143. 'urn:uuid:79f0049a-4098-8642-ab92-e65be0885f95':
  144. 'com.microsoft.playready',
  145. 'urn:uuid:94ce86fb-07ff-4f43-adb8-93d2fa968ca2':
  146. 'com.apple.fps',
  147. 'urn:uuid:3d5e6d35-9b9a-41e8-b843-dd3c6e72c42c':
  148. 'com.huawei.wiseplay',
  149. },
  150. manifestPreprocessor:
  151. shaka.util.PlayerConfiguration.defaultManifestPreprocessor,
  152. manifestPreprocessorTXml:
  153. shaka.util.PlayerConfiguration.defaultManifestPreprocessorTXml,
  154. sequenceMode: false,
  155. multiTypeVariantsAllowed,
  156. useStreamOnceInPeriodFlattening: false,
  157. enableFastSwitching: true,
  158. },
  159. hls: {
  160. ignoreTextStreamFailures: false,
  161. ignoreImageStreamFailures: false,
  162. defaultAudioCodec: 'mp4a.40.2',
  163. defaultVideoCodec: 'avc1.42E01E',
  164. ignoreManifestProgramDateTime: false,
  165. ignoreManifestProgramDateTimeForTypes: [],
  166. mediaPlaylistFullMimeType:
  167. 'video/mp2t; codecs="avc1.42E01E, mp4a.40.2"',
  168. liveSegmentsDelay: 3,
  169. sequenceMode: shaka.util.Platform.supportsSequenceMode(),
  170. ignoreManifestTimestampsInSegmentsMode: false,
  171. disableCodecGuessing: false,
  172. disableClosedCaptionsDetection: false,
  173. allowLowLatencyByteRangeOptimization: true,
  174. allowRangeRequestsToGuessMimeType: false,
  175. },
  176. mss: {
  177. manifestPreprocessor:
  178. shaka.util.PlayerConfiguration.defaultManifestPreprocessor,
  179. manifestPreprocessorTXml:
  180. shaka.util.PlayerConfiguration.defaultManifestPreprocessorTXml,
  181. sequenceMode: false,
  182. keySystemsBySystemId: {
  183. '9a04f079-9840-4286-ab92-e65be0885f95':
  184. 'com.microsoft.playready',
  185. '79f0049a-4098-8642-ab92-e65be0885f95':
  186. 'com.microsoft.playready',
  187. },
  188. },
  189. };
  190. const streaming = {
  191. retryParameters: shaka.net.NetworkingEngine.defaultRetryParameters(),
  192. // Need some operation in the callback or else closure may remove calls
  193. // to the function as it would be a no-op. The operation can't just be a
  194. // log message, because those are stripped in the compiled build.
  195. failureCallback: (error) => {
  196. shaka.log.error('Unhandled streaming error', error);
  197. return shaka.util.ConfigUtils.referenceParametersAndReturn(
  198. [error],
  199. undefined);
  200. },
  201. rebufferingGoal: 0,
  202. bufferingGoal: 10,
  203. bufferBehind: 30,
  204. evictionGoal: 1,
  205. ignoreTextStreamFailures: false,
  206. alwaysStreamText: false,
  207. startAtSegmentBoundary: false,
  208. gapDetectionThreshold: 0.5,
  209. gapPadding: 0,
  210. gapJumpTimerTime: 0.25 /* seconds */,
  211. durationBackoff: 1,
  212. // Offset by 5 seconds since Chromecast takes a few seconds to start
  213. // playing after a seek, even when buffered.
  214. safeSeekOffset: 5,
  215. safeSeekEndOffset: 0,
  216. stallEnabled: true,
  217. stallThreshold: 1 /* seconds */,
  218. stallSkip: 0.1 /* seconds */,
  219. useNativeHlsForFairPlay: true,
  220. // If we are within 2 seconds of the start of a live segment, fetch the
  221. // previous one. This allows for segment drift, but won't download an
  222. // extra segment if we aren't close to the start.
  223. // When low latency streaming is enabled, inaccurateManifestTolerance
  224. // will default to 0 if not specified.
  225. inaccurateManifestTolerance: 2,
  226. lowLatencyMode: false,
  227. forceHTTP: false,
  228. forceHTTPS: false,
  229. minBytesForProgressEvents: minBytes,
  230. preferNativeDash: false,
  231. preferNativeHls: false,
  232. updateIntervalSeconds: 1,
  233. observeQualityChanges: false,
  234. maxDisabledTime: 30,
  235. // When low latency streaming is enabled, segmentPrefetchLimit will
  236. // default to 2 if not specified.
  237. segmentPrefetchLimit: 1,
  238. prefetchAudioLanguages: [],
  239. disableAudioPrefetch: false,
  240. disableTextPrefetch: false,
  241. disableVideoPrefetch: false,
  242. liveSync: {
  243. enabled: false,
  244. targetLatency: 0.5,
  245. targetLatencyTolerance: 0.5,
  246. maxPlaybackRate: 1.1,
  247. minPlaybackRate: 0.95,
  248. panicMode: false,
  249. panicThreshold: 60,
  250. dynamicTargetLatency: {
  251. enabled: false,
  252. stabilityThreshold: 60,
  253. rebufferIncrement: 0.5,
  254. maxAttempts: 10,
  255. maxLatency: 4,
  256. minLatency: 1,
  257. },
  258. },
  259. allowMediaSourceRecoveries: true,
  260. minTimeBetweenRecoveries: 5,
  261. vodDynamicPlaybackRate: false,
  262. vodDynamicPlaybackRateLowBufferRate: 0.95,
  263. vodDynamicPlaybackRateBufferRatio: 0.5,
  264. preloadNextUrlWindow: 30,
  265. loadTimeout: 30,
  266. clearDecodingCache: shaka.util.Platform.isPS4() ||
  267. shaka.util.Platform.isPS5(),
  268. dontChooseCodecs: false,
  269. shouldFixTimestampOffset: shaka.util.Platform.isWebOS() ||
  270. shaka.util.Platform.isTizen(),
  271. avoidEvictionOnQuotaExceededError: false,
  272. crossBoundaryStrategy: shaka.config.CrossBoundaryStrategy.KEEP,
  273. };
  274. // WebOS, Tizen, Chromecast and Hisense have long hardware pipelines
  275. // that respond slowly to seeking.
  276. // Therefore we should not seek when we detect a stall
  277. // on one of these platforms. Instead, default stallSkip to 0 to force the
  278. // stall detector to pause and play instead.
  279. if (shaka.util.Platform.isWebOS() ||
  280. shaka.util.Platform.isTizen() ||
  281. shaka.util.Platform.isChromecast() ||
  282. shaka.util.Platform.isHisense()) {
  283. streaming.stallSkip = 0;
  284. }
  285. if (shaka.util.Platform.isLegacyEdge() ||
  286. shaka.util.Platform.isXboxOne()) {
  287. streaming.gapPadding = 0.01;
  288. }
  289. if (shaka.util.Platform.isTizen()) {
  290. streaming.gapPadding = 2;
  291. }
  292. if (shaka.util.Platform.isWebOS3()) {
  293. streaming.crossBoundaryStrategy =
  294. shaka.config.CrossBoundaryStrategy.RESET;
  295. }
  296. if (shaka.util.Platform.isTizen3()) {
  297. streaming.crossBoundaryStrategy =
  298. shaka.config.CrossBoundaryStrategy.RESET_TO_ENCRYPTED;
  299. }
  300. const offline = {
  301. // We need to set this to a throw-away implementation for now as our
  302. // default implementation will need to reference other fields in the
  303. // config. We will set it to our intended implementation after we have
  304. // the top-level object created.
  305. // eslint-disable-next-line require-await
  306. trackSelectionCallback: async (tracks) => tracks,
  307. downloadSizeCallback: async (sizeEstimate) => {
  308. if (navigator.storage && navigator.storage.estimate) {
  309. const estimate = await navigator.storage.estimate();
  310. // Limit to 95% of quota.
  311. return estimate.usage + sizeEstimate < estimate.quota * 0.95;
  312. } else {
  313. return true;
  314. }
  315. },
  316. // Need some operation in the callback or else closure may remove calls
  317. // to the function as it would be a no-op. The operation can't just be a
  318. // log message, because those are stripped in the compiled build.
  319. progressCallback: (content, progress) => {
  320. return shaka.util.ConfigUtils.referenceParametersAndReturn(
  321. [content, progress],
  322. undefined);
  323. },
  324. // By default we use persistent licenses as forces errors to surface if
  325. // a platform does not support offline licenses rather than causing
  326. // unexpected behaviours when someone tries to plays downloaded content
  327. // without a persistent license.
  328. usePersistentLicense: true,
  329. numberOfParallelDownloads: 5,
  330. };
  331. const abr = {
  332. enabled: true,
  333. useNetworkInformation: true,
  334. defaultBandwidthEstimate: bandwidthEstimate,
  335. switchInterval: 8,
  336. bandwidthUpgradeTarget: 0.85,
  337. bandwidthDowngradeTarget: 0.95,
  338. restrictions: {
  339. minWidth: 0,
  340. maxWidth: Infinity,
  341. minHeight: 0,
  342. maxHeight: abrMaxHeight,
  343. minPixels: 0,
  344. maxPixels: Infinity,
  345. minFrameRate: 0,
  346. maxFrameRate: Infinity,
  347. minBandwidth: 0,
  348. maxBandwidth: Infinity,
  349. minChannelsCount: 0,
  350. maxChannelsCount: Infinity,
  351. },
  352. advanced: {
  353. minTotalBytes: 128e3,
  354. minBytes,
  355. fastHalfLife: 2,
  356. slowHalfLife: 5,
  357. },
  358. restrictToElementSize: false,
  359. restrictToScreenSize: false,
  360. ignoreDevicePixelRatio: false,
  361. clearBufferSwitch: false,
  362. safeMarginSwitch: 0,
  363. cacheLoadThreshold: 20,
  364. minTimeToSwitch: shaka.util.Platform.isApple() ? 0.5 : 0,
  365. preferNetworkInformationBandwidth: false,
  366. };
  367. const cmcd = {
  368. enabled: false,
  369. sessionId: '',
  370. contentId: '',
  371. rtpSafetyFactor: 5,
  372. useHeaders: false,
  373. includeKeys: [],
  374. version: 1,
  375. };
  376. const cmsd = {
  377. enabled: true,
  378. applyMaximumSuggestedBitrate: true,
  379. estimatedThroughputWeightRatio: 0.5,
  380. };
  381. const lcevc = {
  382. enabled: false,
  383. dynamicPerformanceScaling: true,
  384. logLevel: 0,
  385. drawLogo: false,
  386. poster: true,
  387. };
  388. const mediaSource = {
  389. codecSwitchingStrategy: codecSwitchingStrategy,
  390. addExtraFeaturesToSourceBuffer: (mimeType) => {
  391. return shaka.util.ConfigUtils.referenceParametersAndReturn(
  392. [mimeType],
  393. '');
  394. },
  395. forceTransmux: false,
  396. insertFakeEncryptionInInit: true,
  397. modifyCueCallback: (cue, uri) => {
  398. return shaka.util.ConfigUtils.referenceParametersAndReturn(
  399. [cue, uri],
  400. undefined);
  401. },
  402. dispatchAllEmsgBoxes: false,
  403. };
  404. let customPlayheadTracker = false;
  405. let skipPlayDetection = false;
  406. let supportsMultipleMediaElements = true;
  407. if (shaka.util.Platform.isSmartTV()) {
  408. customPlayheadTracker = true;
  409. skipPlayDetection = true;
  410. supportsMultipleMediaElements = false;
  411. }
  412. const ads = {
  413. customPlayheadTracker,
  414. skipPlayDetection,
  415. supportsMultipleMediaElements,
  416. disableHLSInterstitial: false,
  417. disableDASHInterstitial: false,
  418. allowPreloadOnDomElements: true,
  419. };
  420. const textDisplayer = {
  421. captionsUpdatePeriod: 0.25,
  422. fontScaleFactor: 1,
  423. };
  424. const AutoShowText = shaka.config.AutoShowText;
  425. /** @type {shaka.extern.PlayerConfiguration} */
  426. const config = {
  427. drm: drm,
  428. manifest: manifest,
  429. streaming: streaming,
  430. mediaSource: mediaSource,
  431. offline: offline,
  432. abrFactory: () => new shaka.abr.SimpleAbrManager(),
  433. adaptationSetCriteriaFactory:
  434. (...args) => new shaka.media.PreferenceBasedCriteria(...args),
  435. abr: abr,
  436. autoShowText: AutoShowText.IF_SUBTITLES_MAY_BE_NEEDED,
  437. preferredAudioLanguage: '',
  438. preferredAudioLabel: '',
  439. preferredTextLanguage: '',
  440. preferredVariantRole: '',
  441. preferredTextRole: '',
  442. preferredAudioChannelCount: 2,
  443. preferredVideoHdrLevel: 'AUTO',
  444. preferredVideoLayout: '',
  445. preferredVideoLabel: '',
  446. preferredVideoCodecs: [],
  447. preferredAudioCodecs: [],
  448. preferredTextFormats: [],
  449. preferForcedSubs: false,
  450. preferSpatialAudio: false,
  451. preferredDecodingAttributes: [],
  452. restrictions: {
  453. minWidth: 0,
  454. maxWidth: Infinity,
  455. minHeight: 0,
  456. maxHeight: Infinity,
  457. minPixels: 0,
  458. maxPixels: Infinity,
  459. minFrameRate: 0,
  460. maxFrameRate: Infinity,
  461. minBandwidth: 0,
  462. maxBandwidth: Infinity,
  463. minChannelsCount: 0,
  464. maxChannelsCount: Infinity,
  465. },
  466. playRangeStart: 0,
  467. playRangeEnd: Infinity,
  468. textDisplayer: textDisplayer,
  469. textDisplayFactory: () => null,
  470. cmcd: cmcd,
  471. cmsd: cmsd,
  472. lcevc: lcevc,
  473. ads: ads,
  474. ignoreHardwareResolution: false,
  475. };
  476. // Add this callback so that we can reference the preferred audio language
  477. // through the config object so that if it gets updated, we have the
  478. // updated value.
  479. // eslint-disable-next-line require-await
  480. offline.trackSelectionCallback = async (tracks) => {
  481. return shaka.util.PlayerConfiguration.defaultTrackSelect(
  482. tracks, config.preferredAudioLanguage,
  483. config.preferredVideoHdrLevel);
  484. };
  485. return config;
  486. }
  487. /**
  488. * @return {!Object}
  489. * @export
  490. */
  491. static createDefaultForLL() {
  492. return {
  493. streaming: {
  494. inaccurateManifestTolerance: 0,
  495. segmentPrefetchLimit: 2,
  496. updateIntervalSeconds: 0.1,
  497. maxDisabledTime: 1,
  498. retryParameters: {
  499. baseDelay: 100,
  500. },
  501. },
  502. manifest: {
  503. dash: {
  504. autoCorrectDrift: false,
  505. },
  506. retryParameters: {
  507. baseDelay: 100,
  508. },
  509. },
  510. drm: {
  511. retryParameters: {
  512. baseDelay: 100,
  513. },
  514. },
  515. };
  516. }
  517. /**
  518. * Merges the given configuration changes into the given destination. This
  519. * uses the default Player configurations as the template.
  520. *
  521. * @param {shaka.extern.PlayerConfiguration} destination
  522. * @param {!Object} updates
  523. * @param {shaka.extern.PlayerConfiguration=} template
  524. * @return {boolean}
  525. * @export
  526. */
  527. static mergeConfigObjects(destination, updates, template) {
  528. const overrides = {
  529. '.drm.keySystemsMapping': '',
  530. '.drm.servers': '',
  531. '.drm.clearKeys': '',
  532. '.drm.advanced': {
  533. distinctiveIdentifierRequired: false,
  534. persistentStateRequired: false,
  535. videoRobustness: [],
  536. audioRobustness: [],
  537. sessionType: '',
  538. serverCertificate: new Uint8Array(0),
  539. serverCertificateUri: '',
  540. individualizationServer: '',
  541. headers: {},
  542. },
  543. };
  544. return shaka.util.ConfigUtils.mergeConfigObjects(
  545. destination, updates,
  546. template || shaka.util.PlayerConfiguration.createDefault(), overrides,
  547. '');
  548. }
  549. /**
  550. * @param {!Array<shaka.extern.Track>} tracks
  551. * @param {string} preferredAudioLanguage
  552. * @param {string} preferredVideoHdrLevel
  553. * @return {!Array<shaka.extern.Track>}
  554. */
  555. static defaultTrackSelect(
  556. tracks, preferredAudioLanguage, preferredVideoHdrLevel) {
  557. const ContentType = shaka.util.ManifestParserUtils.ContentType;
  558. const LanguageUtils = shaka.util.LanguageUtils;
  559. let hdrLevel = preferredVideoHdrLevel;
  560. if (hdrLevel == 'AUTO') {
  561. const someHLG = tracks.some((track) => {
  562. if (track.hdr && track.hdr == 'HLG') {
  563. return true;
  564. }
  565. return false;
  566. });
  567. hdrLevel = shaka.util.Platform.getHdrLevel(someHLG);
  568. }
  569. /** @type {!Array<shaka.extern.Track>} */
  570. const allVariants = tracks.filter((track) => {
  571. if (track.type != 'variant') {
  572. return false;
  573. }
  574. if (track.hdr && track.hdr != hdrLevel) {
  575. return false;
  576. }
  577. return true;
  578. });
  579. /** @type {!Array<shaka.extern.Track>} */
  580. let selectedVariants = [];
  581. // Find the locale that best matches our preferred audio locale.
  582. const closestLocale = LanguageUtils.findClosestLocale(
  583. preferredAudioLanguage,
  584. allVariants.map((variant) => variant.language));
  585. // If we found a locale that was close to our preference, then only use
  586. // variants that use that locale.
  587. if (closestLocale) {
  588. selectedVariants = allVariants.filter((variant) => {
  589. const locale = LanguageUtils.normalize(variant.language);
  590. return locale == closestLocale;
  591. });
  592. }
  593. // If we failed to get a language match, go with primary.
  594. if (selectedVariants.length == 0) {
  595. selectedVariants = allVariants.filter((variant) => {
  596. return variant.primary;
  597. });
  598. }
  599. // Otherwise, there is no good way to choose the language, so we don't
  600. // choose a language at all.
  601. if (selectedVariants.length == 0) {
  602. // Issue a warning, but only if the content has multiple languages.
  603. // Otherwise, this warning would just be noise.
  604. const languages = new Set(allVariants.map((track) => {
  605. return track.language;
  606. }));
  607. if (languages.size > 1) {
  608. shaka.log.warning('Could not choose a good audio track based on ' +
  609. 'language preferences or primary tracks. An ' +
  610. 'arbitrary language will be stored!');
  611. }
  612. // Default back to all variants.
  613. selectedVariants = allVariants;
  614. }
  615. // From previously selected variants, choose the SD ones (height <= 480).
  616. const tracksByHeight = selectedVariants.filter((track) => {
  617. return track.height && track.height <= 480;
  618. });
  619. // If variants don't have video or no video with height <= 480 was
  620. // found, proceed with the previously selected tracks.
  621. if (tracksByHeight.length) {
  622. // Sort by resolution, then select all variants which match the height
  623. // of the highest SD res. There may be multiple audio bitrates for the
  624. // same video resolution.
  625. tracksByHeight.sort((a, b) => {
  626. // The items in this list have already been screened for height, but the
  627. // compiler doesn't know that.
  628. goog.asserts.assert(a.height != null, 'Null height');
  629. goog.asserts.assert(b.height != null, 'Null height');
  630. return b.height - a.height;
  631. });
  632. selectedVariants = tracksByHeight.filter((track) => {
  633. return track.height == tracksByHeight[0].height;
  634. });
  635. }
  636. /** @type {!Array<shaka.extern.Track>} */
  637. const selectedTracks = [];
  638. // If there are multiple matches at different audio bitrates, select the
  639. // middle bandwidth one.
  640. if (selectedVariants.length) {
  641. const middleIndex = Math.floor(selectedVariants.length / 2);
  642. selectedVariants.sort((a, b) => a.bandwidth - b.bandwidth);
  643. selectedTracks.push(selectedVariants[middleIndex]);
  644. }
  645. // Since this default callback is used primarily by our own demo app and by
  646. // app developers who haven't thought about which tracks they want, we
  647. // should select all image/text tracks, regardless of language. This makes
  648. // for a better demo for us, and does not rely on user preferences for the
  649. // unconfigured app.
  650. for (const track of tracks) {
  651. if (track.type == ContentType.TEXT || track.type == ContentType.IMAGE) {
  652. selectedTracks.push(track);
  653. }
  654. }
  655. return selectedTracks;
  656. }
  657. /**
  658. * @param {!Element} element
  659. * @return {!Element}
  660. */
  661. static defaultManifestPreprocessor(element) {
  662. return shaka.util.ConfigUtils.referenceParametersAndReturn(
  663. [element],
  664. element);
  665. }
  666. /**
  667. * @param {!shaka.extern.xml.Node} element
  668. * @return {!shaka.extern.xml.Node}
  669. */
  670. static defaultManifestPreprocessorTXml(element) {
  671. return shaka.util.ConfigUtils.referenceParametersAndReturn(
  672. [element],
  673. element);
  674. }
  675. };