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.log');
  12. goog.require('shaka.net.NetworkingEngine');
  13. goog.require('shaka.util.ConfigUtils');
  14. goog.require('shaka.util.FairPlayUtils');
  15. goog.require('shaka.util.LanguageUtils');
  16. goog.require('shaka.util.ManifestParserUtils');
  17. goog.require('shaka.util.Platform');
  18. /**
  19. * @final
  20. * @export
  21. */
  22. shaka.util.PlayerConfiguration = class {
  23. /**
  24. * @return {shaka.extern.PlayerConfiguration}
  25. * @export
  26. */
  27. static createDefault() {
  28. // This is a relatively safe default in the absence of clues from the
  29. // browser. For slower connections, the default estimate may be too high.
  30. const bandwidthEstimate = 1e6; // 1Mbps
  31. let abrMaxHeight = Infinity;
  32. // Some browsers implement the Network Information API, which allows
  33. // retrieving information about a user's network connection.
  34. if (navigator.connection) {
  35. // If the user has checked a box in the browser to ask it to use less
  36. // data, the browser will expose this intent via connection.saveData.
  37. // When that is true, we will default the max ABR height to 360p. Apps
  38. // can override this if they wish.
  39. //
  40. // The decision to use 360p was somewhat arbitrary. We needed a default
  41. // limit, and rather than restrict to a certain bandwidth, we decided to
  42. // restrict resolution. This will implicitly restrict bandwidth and
  43. // therefore save data. We (Shaka+Chrome) judged that:
  44. // - HD would be inappropriate
  45. // - If a user is asking their browser to save data, 360p it reasonable
  46. // - 360p would not look terrible on small mobile device screen
  47. // We also found that:
  48. // - YouTube's website on mobile defaults to 360p (as of 2018)
  49. // - iPhone 6, in portrait mode, has a physical resolution big enough
  50. // for 360p widescreen, but a little smaller than 480p widescreen
  51. // (https://apple.co/2yze4es)
  52. // If the content's lowest resolution is above 360p, AbrManager will use
  53. // the lowest resolution.
  54. if (navigator.connection.saveData) {
  55. abrMaxHeight = 360;
  56. }
  57. }
  58. const drm = {
  59. retryParameters: shaka.net.NetworkingEngine.defaultRetryParameters(),
  60. // These will all be verified by special cases in mergeConfigObjects_():
  61. servers: {}, // key is arbitrary key system ID, value must be string
  62. clearKeys: {}, // key is arbitrary key system ID, value must be string
  63. advanced: {}, // key is arbitrary key system ID, value is a record type
  64. delayLicenseRequestUntilPlayed: false,
  65. persistentSessionOnlinePlayback: false,
  66. persistentSessionsMetadata: [],
  67. initDataTransform: (initData, initDataType, drmInfo) => {
  68. if (shaka.util.Platform.isMediaKeysPolyfilled() &&
  69. initDataType == 'skd') {
  70. const cert = drmInfo.serverCertificate;
  71. const contentId =
  72. shaka.util.FairPlayUtils.defaultGetContentId(initData);
  73. initData = shaka.util.FairPlayUtils.initDataTransform(
  74. initData, contentId, cert);
  75. }
  76. return initData;
  77. },
  78. logLicenseExchange: false,
  79. updateExpirationTime: 1,
  80. preferredKeySystems: [],
  81. keySystemsMapping: {},
  82. // The Xbox One browser does not detect DRM key changes signalled by a
  83. // change in the PSSH in media segments. We need to parse PSSH from media
  84. // segments to detect key changes.
  85. parseInbandPsshEnabled: shaka.util.Platform.isXboxOne(),
  86. minHdcpVersion: '',
  87. ignoreDuplicateInitData: !shaka.util.Platform.isTizen2(),
  88. };
  89. const manifest = {
  90. retryParameters: shaka.net.NetworkingEngine.defaultRetryParameters(),
  91. availabilityWindowOverride: NaN,
  92. disableAudio: false,
  93. disableVideo: false,
  94. disableText: false,
  95. disableThumbnails: false,
  96. defaultPresentationDelay: 0,
  97. segmentRelativeVttTiming: false,
  98. raiseFatalErrorOnManifestUpdateRequestFailure: false,
  99. dash: {
  100. clockSyncUri: '',
  101. ignoreDrmInfo: false,
  102. disableXlinkProcessing: false,
  103. xlinkFailGracefully: false,
  104. ignoreMinBufferTime: false,
  105. autoCorrectDrift: true,
  106. initialSegmentLimit: 1000,
  107. ignoreSuggestedPresentationDelay: false,
  108. ignoreEmptyAdaptationSet: false,
  109. ignoreMaxSegmentDuration: false,
  110. keySystemsByURI: {
  111. 'urn:uuid:1077efec-c0b2-4d02-ace3-3c1e52e2fb4b':
  112. 'org.w3.clearkey',
  113. 'urn:uuid:e2719d58-a985-b3c9-781a-b030af78d30e':
  114. 'org.w3.clearkey',
  115. 'urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed':
  116. 'com.widevine.alpha',
  117. 'urn:uuid:9a04f079-9840-4286-ab92-e65be0885f95':
  118. 'com.microsoft.playready',
  119. 'urn:uuid:79f0049a-4098-8642-ab92-e65be0885f95':
  120. 'com.microsoft.playready',
  121. 'urn:uuid:f239e769-efa3-4850-9c16-a903c6932efb':
  122. 'com.adobe.primetime',
  123. },
  124. manifestPreprocessor: (element) => {
  125. return shaka.util.ConfigUtils.referenceParametersAndReturn(
  126. [element],
  127. element);
  128. },
  129. sequenceMode: false,
  130. enableAudioGroups: false,
  131. },
  132. hls: {
  133. ignoreTextStreamFailures: false,
  134. ignoreImageStreamFailures: false,
  135. defaultAudioCodec: 'mp4a.40.2',
  136. defaultVideoCodec: 'avc1.42E01E',
  137. ignoreManifestProgramDateTime: false,
  138. mediaPlaylistFullMimeType:
  139. 'video/mp2t; codecs="avc1.42E01E, mp4a.40.2"',
  140. useSafariBehaviorForLive: true,
  141. liveSegmentsDelay: 3,
  142. sequenceMode: shaka.util.Platform.supportsSequenceMode(),
  143. ignoreManifestTimestampsInSegmentsMode: false,
  144. disableCodecGuessing: false,
  145. allowLowLatencyByteRangeOptimization: true,
  146. },
  147. mss: {
  148. manifestPreprocessor: (element) => {
  149. return shaka.util.ConfigUtils.referenceParametersAndReturn(
  150. [element],
  151. element);
  152. },
  153. sequenceMode: false,
  154. keySystemsBySystemId: {
  155. '9a04f079-9840-4286-ab92-e65be0885f95':
  156. 'com.microsoft.playready',
  157. '79f0049a-4098-8642-ab92-e65be0885f95':
  158. 'com.microsoft.playready',
  159. },
  160. },
  161. };
  162. const streaming = {
  163. retryParameters: shaka.net.NetworkingEngine.defaultRetryParameters(),
  164. // Need some operation in the callback or else closure may remove calls
  165. // to the function as it would be a no-op. The operation can't just be a
  166. // log message, because those are stripped in the compiled build.
  167. failureCallback: (error) => {
  168. shaka.log.error('Unhandled streaming error', error);
  169. return shaka.util.ConfigUtils.referenceParametersAndReturn(
  170. [error],
  171. undefined);
  172. },
  173. // When low latency streaming is enabled, rebufferingGoal will default to
  174. // 0.01 if not specified.
  175. rebufferingGoal: 2,
  176. bufferingGoal: 10,
  177. bufferBehind: 30,
  178. ignoreTextStreamFailures: false,
  179. alwaysStreamText: false,
  180. startAtSegmentBoundary: false,
  181. gapDetectionThreshold: 0.5,
  182. gapJumpTimerTime: 0.25 /* seconds */,
  183. durationBackoff: 1,
  184. // Offset by 5 seconds since Chromecast takes a few seconds to start
  185. // playing after a seek, even when buffered.
  186. safeSeekOffset: 5,
  187. stallEnabled: true,
  188. stallThreshold: 1 /* seconds */,
  189. stallSkip: 0.1 /* seconds */,
  190. useNativeHlsOnSafari: true,
  191. // If we are within 2 seconds of the start of a live segment, fetch the
  192. // previous one. This allows for segment drift, but won't download an
  193. // extra segment if we aren't close to the start.
  194. // When low latency streaming is enabled, inaccurateManifestTolerance
  195. // will default to 0 if not specified.
  196. inaccurateManifestTolerance: 2,
  197. lowLatencyMode: false,
  198. autoLowLatencyMode: false,
  199. forceHTTPS: false,
  200. preferNativeHls: false,
  201. updateIntervalSeconds: 1,
  202. dispatchAllEmsgBoxes: false,
  203. observeQualityChanges: false,
  204. maxDisabledTime: 30,
  205. parsePrftBox: false,
  206. // When low latency streaming is enabled, segmentPrefetchLimit will
  207. // default to 2 if not specified.
  208. segmentPrefetchLimit: 0,
  209. liveSync: false,
  210. liveSyncMaxLatency: 1,
  211. liveSyncPlaybackRate: 1.1,
  212. liveSyncMinLatency: 0,
  213. liveSyncMinPlaybackRate: 1,
  214. };
  215. // WebOS, Tizen, Chromecast and Hisense have long hardware pipelines
  216. // that respond slowly to seeking.
  217. // Therefore we should not seek when we detect a stall
  218. // on one of these platforms. Instead, default stallSkip to 0 to force the
  219. // stall detector to pause and play instead.
  220. if (shaka.util.Platform.isWebOS() ||
  221. shaka.util.Platform.isTizen() ||
  222. shaka.util.Platform.isChromecast() ||
  223. shaka.util.Platform.isHisense()) {
  224. streaming.stallSkip = 0;
  225. }
  226. const offline = {
  227. // We need to set this to a throw-away implementation for now as our
  228. // default implementation will need to reference other fields in the
  229. // config. We will set it to our intended implementation after we have
  230. // the top-level object created.
  231. // eslint-disable-next-line require-await
  232. trackSelectionCallback: async (tracks) => tracks,
  233. downloadSizeCallback: async (sizeEstimate) => {
  234. if (navigator.storage && navigator.storage.estimate) {
  235. const estimate = await navigator.storage.estimate();
  236. // Limit to 95% of quota.
  237. return estimate.usage + sizeEstimate < estimate.quota * 0.95;
  238. } else {
  239. return true;
  240. }
  241. },
  242. // Need some operation in the callback or else closure may remove calls
  243. // to the function as it would be a no-op. The operation can't just be a
  244. // log message, because those are stripped in the compiled build.
  245. progressCallback: (content, progress) => {
  246. return shaka.util.ConfigUtils.referenceParametersAndReturn(
  247. [content, progress],
  248. undefined);
  249. },
  250. // By default we use persistent licenses as forces errors to surface if
  251. // a platform does not support offline licenses rather than causing
  252. // unexpected behaviours when someone tries to plays downloaded content
  253. // without a persistent license.
  254. usePersistentLicense: true,
  255. numberOfParallelDownloads: 5,
  256. };
  257. const abr = {
  258. enabled: true,
  259. useNetworkInformation: true,
  260. defaultBandwidthEstimate: bandwidthEstimate,
  261. switchInterval: 8,
  262. bandwidthUpgradeTarget: 0.85,
  263. bandwidthDowngradeTarget: 0.95,
  264. restrictions: {
  265. minWidth: 0,
  266. maxWidth: Infinity,
  267. minHeight: 0,
  268. maxHeight: abrMaxHeight,
  269. minPixels: 0,
  270. maxPixels: Infinity,
  271. minFrameRate: 0,
  272. maxFrameRate: Infinity,
  273. minBandwidth: 0,
  274. maxBandwidth: Infinity,
  275. },
  276. advanced: {
  277. minTotalBytes: 128e3,
  278. minBytes: 16e3,
  279. fastHalfLife: 2,
  280. slowHalfLife: 5,
  281. },
  282. restrictToElementSize: false,
  283. restrictToScreenSize: false,
  284. ignoreDevicePixelRatio: false,
  285. clearBufferSwitch: false,
  286. safeMarginSwitch: 0,
  287. };
  288. const cmcd = {
  289. enabled: false,
  290. sessionId: '',
  291. contentId: '',
  292. useHeaders: false,
  293. };
  294. const lcevc = {
  295. enabled: false,
  296. dynamicPerformanceScaling: true,
  297. logLevel: 0,
  298. drawLogo: false,
  299. };
  300. let codecSwitchingStrategy = shaka.config.CodecSwitchingStrategy.RELOAD;
  301. if (shaka.util.Platform.supportsSmoothCodecSwitching()) {
  302. codecSwitchingStrategy = shaka.config.CodecSwitchingStrategy.SMOOTH;
  303. }
  304. const mediaSource = {
  305. codecSwitchingStrategy: codecSwitchingStrategy,
  306. sourceBufferExtraFeatures: '',
  307. forceTransmux: false,
  308. insertFakeEncryptionInInit: true,
  309. };
  310. const ads = {
  311. customPlayheadTracker: false,
  312. };
  313. const AutoShowText = shaka.config.AutoShowText;
  314. /** @type {shaka.extern.PlayerConfiguration} */
  315. const config = {
  316. drm: drm,
  317. manifest: manifest,
  318. streaming: streaming,
  319. mediaSource: mediaSource,
  320. offline: offline,
  321. abrFactory: () => new shaka.abr.SimpleAbrManager(),
  322. abr: abr,
  323. autoShowText: AutoShowText.IF_SUBTITLES_MAY_BE_NEEDED,
  324. preferredAudioLanguage: '',
  325. preferredAudioLabel: '',
  326. preferredTextLanguage: '',
  327. preferredVariantRole: '',
  328. preferredTextRole: '',
  329. preferredAudioChannelCount: 2,
  330. preferredVideoHdrLevel: 'AUTO',
  331. preferredVideoLayout: '',
  332. preferredVideoCodecs: [],
  333. preferredAudioCodecs: [],
  334. preferForcedSubs: false,
  335. preferredDecodingAttributes: [],
  336. restrictions: {
  337. minWidth: 0,
  338. maxWidth: Infinity,
  339. minHeight: 0,
  340. maxHeight: Infinity,
  341. minPixels: 0,
  342. maxPixels: Infinity,
  343. minFrameRate: 0,
  344. maxFrameRate: Infinity,
  345. minBandwidth: 0,
  346. maxBandwidth: Infinity,
  347. },
  348. playRangeStart: 0,
  349. playRangeEnd: Infinity,
  350. textDisplayFactory: () => null,
  351. cmcd: cmcd,
  352. lcevc: lcevc,
  353. ads: ads,
  354. };
  355. // Add this callback so that we can reference the preferred audio language
  356. // through the config object so that if it gets updated, we have the
  357. // updated value.
  358. // eslint-disable-next-line require-await
  359. offline.trackSelectionCallback = async (tracks) => {
  360. return shaka.util.PlayerConfiguration.defaultTrackSelect(
  361. tracks, config.preferredAudioLanguage,
  362. config.preferredVideoHdrLevel);
  363. };
  364. return config;
  365. }
  366. /**
  367. * Merges the given configuration changes into the given destination. This
  368. * uses the default Player configurations as the template.
  369. *
  370. * @param {shaka.extern.PlayerConfiguration} destination
  371. * @param {!Object} updates
  372. * @param {shaka.extern.PlayerConfiguration=} template
  373. * @return {boolean}
  374. * @export
  375. */
  376. static mergeConfigObjects(destination, updates, template) {
  377. const overrides = {
  378. '.drm.keySystemsMapping': '',
  379. '.drm.servers': '',
  380. '.drm.clearKeys': '',
  381. '.drm.advanced': {
  382. distinctiveIdentifierRequired: false,
  383. persistentStateRequired: false,
  384. videoRobustness: '',
  385. audioRobustness: '',
  386. sessionType: '',
  387. serverCertificate: new Uint8Array(0),
  388. serverCertificateUri: '',
  389. individualizationServer: '',
  390. },
  391. };
  392. return shaka.util.ConfigUtils.mergeConfigObjects(
  393. destination, updates,
  394. template || shaka.util.PlayerConfiguration.createDefault(), overrides,
  395. '');
  396. }
  397. /**
  398. * @param {!Array.<shaka.extern.Track>} tracks
  399. * @param {string} preferredAudioLanguage
  400. * @param {string} preferredVideoHdrLevel
  401. * @return {!Array.<shaka.extern.Track>}
  402. */
  403. static defaultTrackSelect(
  404. tracks, preferredAudioLanguage, preferredVideoHdrLevel) {
  405. const ContentType = shaka.util.ManifestParserUtils.ContentType;
  406. const LanguageUtils = shaka.util.LanguageUtils;
  407. let hdrLevel = preferredVideoHdrLevel;
  408. if (hdrLevel == 'AUTO') {
  409. // Auto detect the ideal HDR level.
  410. if (window.matchMedia('(color-gamut: p3)').matches) {
  411. hdrLevel = 'PQ';
  412. } else {
  413. hdrLevel = 'SDR';
  414. }
  415. }
  416. /** @type {!Array.<shaka.extern.Track>} */
  417. const allVariants = tracks.filter((track) => {
  418. if (track.type != 'variant') {
  419. return false;
  420. }
  421. if (track.hdr && track.hdr != hdrLevel) {
  422. return false;
  423. }
  424. return true;
  425. });
  426. /** @type {!Array.<shaka.extern.Track>} */
  427. let selectedVariants = [];
  428. // Find the locale that best matches our preferred audio locale.
  429. const closestLocale = LanguageUtils.findClosestLocale(
  430. preferredAudioLanguage,
  431. allVariants.map((variant) => variant.language));
  432. // If we found a locale that was close to our preference, then only use
  433. // variants that use that locale.
  434. if (closestLocale) {
  435. selectedVariants = allVariants.filter((variant) => {
  436. const locale = LanguageUtils.normalize(variant.language);
  437. return locale == closestLocale;
  438. });
  439. }
  440. // If we failed to get a language match, go with primary.
  441. if (selectedVariants.length == 0) {
  442. selectedVariants = allVariants.filter((variant) => {
  443. return variant.primary;
  444. });
  445. }
  446. // Otherwise, there is no good way to choose the language, so we don't
  447. // choose a language at all.
  448. if (selectedVariants.length == 0) {
  449. // Issue a warning, but only if the content has multiple languages.
  450. // Otherwise, this warning would just be noise.
  451. const languages = new Set(allVariants.map((track) => {
  452. return track.language;
  453. }));
  454. if (languages.size > 1) {
  455. shaka.log.warning('Could not choose a good audio track based on ' +
  456. 'language preferences or primary tracks. An ' +
  457. 'arbitrary language will be stored!');
  458. }
  459. // Default back to all variants.
  460. selectedVariants = allVariants;
  461. }
  462. // From previously selected variants, choose the SD ones (height <= 480).
  463. const tracksByHeight = selectedVariants.filter((track) => {
  464. return track.height && track.height <= 480;
  465. });
  466. // If variants don't have video or no video with height <= 480 was
  467. // found, proceed with the previously selected tracks.
  468. if (tracksByHeight.length) {
  469. // Sort by resolution, then select all variants which match the height
  470. // of the highest SD res. There may be multiple audio bitrates for the
  471. // same video resolution.
  472. tracksByHeight.sort((a, b) => {
  473. // The items in this list have already been screened for height, but the
  474. // compiler doesn't know that.
  475. goog.asserts.assert(a.height != null, 'Null height');
  476. goog.asserts.assert(b.height != null, 'Null height');
  477. return b.height - a.height;
  478. });
  479. selectedVariants = tracksByHeight.filter((track) => {
  480. return track.height == tracksByHeight[0].height;
  481. });
  482. }
  483. /** @type {!Array.<shaka.extern.Track>} */
  484. const selectedTracks = [];
  485. // If there are multiple matches at different audio bitrates, select the
  486. // middle bandwidth one.
  487. if (selectedVariants.length) {
  488. const middleIndex = Math.floor(selectedVariants.length / 2);
  489. selectedVariants.sort((a, b) => a.bandwidth - b.bandwidth);
  490. selectedTracks.push(selectedVariants[middleIndex]);
  491. }
  492. // Since this default callback is used primarily by our own demo app and by
  493. // app developers who haven't thought about which tracks they want, we
  494. // should select all image/text tracks, regardless of language. This makes
  495. // for a better demo for us, and does not rely on user preferences for the
  496. // unconfigured app.
  497. for (const track of tracks) {
  498. if (track.type == ContentType.TEXT || track.type == ContentType.IMAGE) {
  499. selectedTracks.push(track);
  500. }
  501. }
  502. return selectedTracks;
  503. }
  504. };