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